@linxiraos/pi-stats 1.4.11 → 1.4.13
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/CHANGELOG.md +11 -4
- package/THIRD-PARTY-NOTICES.txt +4 -5
- package/dist/client/index.css +1 -1
- package/dist/client/index.js +102 -99
- package/dist/types/client/api.d.ts +4 -1
- package/dist/types/client/app/nav.d.ts +1 -1
- package/dist/types/client/charts/Chart.d.ts +16 -8
- package/dist/types/client/charts/DotWhisker.d.ts +50 -0
- package/dist/types/client/charts/Sparkline.d.ts +1 -1
- package/dist/types/client/charts/Waterfall.d.ts +26 -0
- package/dist/types/client/charts/index.d.ts +2 -0
- package/dist/types/client/charts/types.d.ts +8 -2
- package/dist/types/client/i18n/messages/en.d.ts +2 -0
- package/dist/types/client/i18n/messages/nav.d.ts +2 -0
- package/dist/types/client/i18n/messages/zh-CN.d.ts +1 -1
- package/dist/types/client/routes/SpotlightRoute.d.ts +7 -0
- package/dist/types/client/routes/index.d.ts +1 -0
- package/dist/types/client/spotlight/Compounding.d.ts +8 -0
- package/dist/types/client/spotlight/Coverage.d.ts +6 -0
- package/dist/types/client/spotlight/Economics.d.ts +10 -0
- package/dist/types/client/spotlight/FetchBack.d.ts +9 -0
- package/dist/types/client/spotlight/Hero.d.ts +12 -0
- package/dist/types/client/spotlight/Overhead.d.ts +6 -0
- package/dist/types/client/spotlight/Ranking.d.ts +6 -0
- package/dist/types/client/spotlight/ResultsFeed.d.ts +6 -0
- package/dist/types/client/spotlight/Savings.d.ts +10 -0
- package/dist/types/client/spotlight/ShareTrend.d.ts +8 -0
- package/dist/types/client/spotlight/Steps.d.ts +6 -0
- package/dist/types/client/spotlight/TimeCost.d.ts +6 -0
- package/dist/types/client/spotlight/chips.d.ts +16 -0
- package/dist/types/client/spotlight/meta.d.ts +64 -0
- package/dist/types/db.d.ts +26 -0
- package/dist/types/index.d.ts +2 -1
- package/dist/types/parser.d.ts +4 -0
- package/dist/types/rollup.d.ts +22 -1
- package/dist/types/shared-types.d.ts +419 -0
- package/dist/types/spotlight-aggregator.d.ts +189 -0
- package/dist/types/spotlight-bootstrap.d.ts +32 -0
- package/dist/types/spotlight-ingest.d.ts +258 -0
- package/dist/types/spotlight-measures.d.ts +51 -0
- package/package.json +5 -5
- package/src/aggregator.ts +3 -1
- package/src/client/App.tsx +3 -0
- package/src/client/api.ts +21 -0
- package/src/client/app/nav.ts +4 -1
- package/src/client/charts/Chart.tsx +105 -22
- package/src/client/charts/DotWhisker.tsx +149 -0
- package/src/client/charts/Sparkline.tsx +3 -2
- package/src/client/charts/Waterfall.tsx +86 -0
- package/src/client/charts/index.ts +2 -0
- package/src/client/charts/types.ts +9 -2
- package/src/client/i18n/messages/nav.ts +2 -0
- package/src/client/react-css.d.ts +1 -1
- package/src/client/routes/SpotlightRoute.tsx +139 -0
- package/src/client/routes/index.ts +1 -0
- package/src/client/spotlight/Compounding.tsx +222 -0
- package/src/client/spotlight/Coverage.tsx +96 -0
- package/src/client/spotlight/Economics.tsx +167 -0
- package/src/client/spotlight/FetchBack.tsx +222 -0
- package/src/client/spotlight/Hero.tsx +177 -0
- package/src/client/spotlight/Overhead.tsx +135 -0
- package/src/client/spotlight/Ranking.tsx +248 -0
- package/src/client/spotlight/ResultsFeed.tsx +354 -0
- package/src/client/spotlight/Savings.tsx +355 -0
- package/src/client/spotlight/ShareTrend.tsx +103 -0
- package/src/client/spotlight/Steps.tsx +225 -0
- package/src/client/spotlight/TimeCost.tsx +64 -0
- package/src/client/spotlight/chips.tsx +63 -0
- package/src/client/spotlight/meta.ts +206 -0
- package/src/client/spotlight/spotlight.css +1387 -0
- package/src/client/styles.css +289 -1
- package/src/db.ts +486 -8
- package/src/index.ts +10 -1
- package/src/live.ts +21 -9
- package/src/parser.ts +36 -7
- package/src/rollup.ts +203 -10
- package/src/server.ts +42 -0
- package/src/shared-types.ts +453 -0
- package/src/spotlight-aggregator.ts +1738 -0
- package/src/spotlight-bootstrap.ts +110 -0
- package/src/spotlight-ingest.ts +981 -0
- package/src/spotlight-measures.ts +667 -0
package/src/parser.ts
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
type AssistantMessage,
|
|
6
6
|
coerceServiceTierByFamily,
|
|
7
7
|
getPremiumServiceTierRequests,
|
|
8
|
+
type MessageAttribution,
|
|
8
9
|
parseServiceTier,
|
|
9
10
|
resolveModelServiceTier,
|
|
10
11
|
type ServiceTierByFamily,
|
|
@@ -27,6 +28,13 @@ import type {
|
|
|
27
28
|
UserMessageLink,
|
|
28
29
|
UserMessageStats,
|
|
29
30
|
} from "./types";
|
|
31
|
+
import {
|
|
32
|
+
emptySpotlightRows,
|
|
33
|
+
emptySpotlightState,
|
|
34
|
+
SpotlightCollector,
|
|
35
|
+
type SpotlightParseRows,
|
|
36
|
+
type SpotlightParserState,
|
|
37
|
+
} from "./spotlight-ingest";
|
|
30
38
|
import { computeAssistantMessageMetrics } from "./model-metrics";
|
|
31
39
|
import { analysisProse, computeUserMessageMetrics } from "./user-metrics";
|
|
32
40
|
|
|
@@ -139,7 +147,7 @@ function extractUserText(content: unknown): string {
|
|
|
139
147
|
}
|
|
140
148
|
|
|
141
149
|
/**
|
|
142
|
-
* Build user-message stats from an entry. Returns null for empty
|
|
150
|
+
* Build user-message stats from an entry. Returns null for empty, synthetic, or agent-attributed content.
|
|
143
151
|
*/
|
|
144
152
|
function extractUserStats(
|
|
145
153
|
sessionFile: string,
|
|
@@ -147,8 +155,13 @@ function extractUserStats(
|
|
|
147
155
|
entry: SessionMessageEntry,
|
|
148
156
|
prevText: string,
|
|
149
157
|
): UserMessageStats | null {
|
|
150
|
-
const msg = entry.message as {
|
|
151
|
-
|
|
158
|
+
const msg = entry.message as {
|
|
159
|
+
role: "user";
|
|
160
|
+
content?: unknown;
|
|
161
|
+
synthetic?: boolean;
|
|
162
|
+
attribution?: MessageAttribution;
|
|
163
|
+
};
|
|
164
|
+
if (msg.role !== "user" || msg.synthetic || msg.attribution === "agent") return null;
|
|
152
165
|
const text = extractUserText(msg.content);
|
|
153
166
|
if (!text.trim()) return null;
|
|
154
167
|
const metrics = computeUserMessageMetrics(text, { prevText });
|
|
@@ -555,10 +568,12 @@ export function parseAllSessionEntries(bytes: Uint8Array): SessionEntry[] {
|
|
|
555
568
|
return entries;
|
|
556
569
|
}
|
|
557
570
|
|
|
558
|
-
|
|
571
|
+
/** Rebuild the cursor state of `bytes` (a transcript prefix): the last service tier and the Spotlight state. */
|
|
572
|
+
function scanPrefixState(bytes: Uint8Array, spotlight: SpotlightCollector): ServiceTierByFamily | undefined {
|
|
559
573
|
let currentServiceTier: ServiceTierByFamily | undefined;
|
|
560
574
|
visitSessionEntriesLenient(bytes, entry => {
|
|
561
575
|
if (isServiceTierChange(entry)) currentServiceTier = coerceServiceTierByFamily(entry.serviceTier);
|
|
576
|
+
else spotlight.visit(entry);
|
|
562
577
|
});
|
|
563
578
|
return currentServiceTier;
|
|
564
579
|
}
|
|
@@ -572,6 +587,8 @@ export interface SessionParserState {
|
|
|
572
587
|
mtimeMs: number;
|
|
573
588
|
checkpoint: string;
|
|
574
589
|
serviceTier: ServiceTierByFamily | null;
|
|
590
|
+
/** Absent in cursors persisted before the Spotlight tables; such a tail parse starts from an empty state. */
|
|
591
|
+
spotlight?: SpotlightParserState;
|
|
575
592
|
}
|
|
576
593
|
|
|
577
594
|
export interface ParseSessionResult {
|
|
@@ -581,6 +598,7 @@ export interface ParseSessionResult {
|
|
|
581
598
|
userLinks: UserMessageLink[];
|
|
582
599
|
toolCalls: ToolCallStats[];
|
|
583
600
|
toolResults: ToolResultLink[];
|
|
601
|
+
spotlight: SpotlightParseRows;
|
|
584
602
|
newOffset: number;
|
|
585
603
|
parserState?: SessionParserState;
|
|
586
604
|
reset?: boolean;
|
|
@@ -629,6 +647,7 @@ export async function parseSessionFile(
|
|
|
629
647
|
const toolResults: ToolResultLink[] = [];
|
|
630
648
|
// First call per id: the row `INSERT OR IGNORE` keeps, so it can be written with its result.
|
|
631
649
|
const callsById = new Map<string, ToolCallStats>();
|
|
650
|
+
let spotlight = new SpotlightCollector(sessionPath, folder, emptySpotlightState());
|
|
632
651
|
|
|
633
652
|
// The previous user message, for the whole-message repetition signal. An
|
|
634
653
|
// incremental parse starts mid-session, so the first message of a resumed
|
|
@@ -644,6 +663,7 @@ export async function parseSessionFile(
|
|
|
644
663
|
|
|
645
664
|
// Reduce each entry immediately so full replays do not retain tool-output/message bodies.
|
|
646
665
|
const visit = (entry: SessionEntry): void => {
|
|
666
|
+
spotlight.visit(entry);
|
|
647
667
|
if (isServiceTierChange(entry)) {
|
|
648
668
|
currentServiceTier = coerceServiceTierByFamily(entry.serviceTier);
|
|
649
669
|
return;
|
|
@@ -730,9 +750,14 @@ export async function parseSessionFile(
|
|
|
730
750
|
start = reset || replay ? 0 : Math.max(0, fromOffset);
|
|
731
751
|
const readStart = resume ? start : 0;
|
|
732
752
|
bytes = await file.slice(readStart, info.size).bytes();
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
753
|
+
if (resume) {
|
|
754
|
+
currentServiceTier = state?.serviceTier ?? undefined;
|
|
755
|
+
spotlight = new SpotlightCollector(sessionPath, folder, state?.spotlight ?? emptySpotlightState());
|
|
756
|
+
} else {
|
|
757
|
+
const prefix = new SpotlightCollector(sessionPath, folder, emptySpotlightState(), false);
|
|
758
|
+
currentServiceTier = scanPrefixState(bytes.subarray(0, start), prefix);
|
|
759
|
+
spotlight = new SpotlightCollector(sessionPath, folder, prefix.state);
|
|
760
|
+
}
|
|
736
761
|
read = visitSessionEntriesLenient(bytes.subarray(start - readStart), visit);
|
|
737
762
|
const newOffset = start + read;
|
|
738
763
|
const checkpointStart = Math.max(0, newOffset - CHECKPOINT_BYTES);
|
|
@@ -753,11 +778,13 @@ export async function parseSessionFile(
|
|
|
753
778
|
userLinks: [],
|
|
754
779
|
toolCalls: [],
|
|
755
780
|
toolResults: [],
|
|
781
|
+
spotlight: emptySpotlightRows(),
|
|
756
782
|
newOffset: fromOffset,
|
|
757
783
|
};
|
|
758
784
|
throw err;
|
|
759
785
|
}
|
|
760
786
|
|
|
787
|
+
await spotlight.finish();
|
|
761
788
|
const newOffset = start + read;
|
|
762
789
|
return {
|
|
763
790
|
stats,
|
|
@@ -766,6 +793,7 @@ export async function parseSessionFile(
|
|
|
766
793
|
userLinks,
|
|
767
794
|
toolCalls,
|
|
768
795
|
toolResults,
|
|
796
|
+
spotlight: spotlight.rows,
|
|
769
797
|
newOffset,
|
|
770
798
|
reset,
|
|
771
799
|
parserState: {
|
|
@@ -778,6 +806,7 @@ export async function parseSessionFile(
|
|
|
778
806
|
mtimeMs: info.mtimeMs,
|
|
779
807
|
checkpoint,
|
|
780
808
|
serviceTier: currentServiceTier ?? null,
|
|
809
|
+
spotlight: spotlight.state,
|
|
781
810
|
},
|
|
782
811
|
};
|
|
783
812
|
}
|
package/src/rollup.ts
CHANGED
|
@@ -58,8 +58,17 @@ const DAY_MS = 24 * HOUR_MS;
|
|
|
58
58
|
const ROLLUP_VERSION = "2";
|
|
59
59
|
const ROLLUP_VERSION_KEY = "rollup_version";
|
|
60
60
|
/** Bump when the dirty-marking triggers change; they are then recreated in place. */
|
|
61
|
-
const TRIGGER_VERSION = "
|
|
61
|
+
const TRIGGER_VERSION = "4";
|
|
62
62
|
const TRIGGER_VERSION_KEY = "rollup_triggers_version";
|
|
63
|
+
/**
|
|
64
|
+
* `tool_agent_rollup` (tool-result characters per hour and agent type) is built
|
|
65
|
+
* on its own dirty set, so adding it never rebuilds the other rollups. Bump to
|
|
66
|
+
* rebuild just this table.
|
|
67
|
+
*/
|
|
68
|
+
const TOOL_AGENT_VERSION = "1";
|
|
69
|
+
const TOOL_AGENT_VERSION_KEY = "tool_agent_rollup_version";
|
|
70
|
+
/** Before this, timestamps are sentinels (0) or garbage: their hours are seeded one by one, not as a range. */
|
|
71
|
+
const SANE_TIMESTAMP_MS = Date.UTC(2000, 0, 1);
|
|
63
72
|
|
|
64
73
|
/** Above this many dirty hours, reads use stale rollup rows instead of scanning dirty hours raw. */
|
|
65
74
|
const EXACT_DIRTY_LIMIT = 96;
|
|
@@ -144,11 +153,22 @@ function hourOf(column: string): string {
|
|
|
144
153
|
* Trigger statements marking a row's hour and transcript dirty (`row` is
|
|
145
154
|
* `NEW` or `OLD`), without any conflict clause.
|
|
146
155
|
*/
|
|
147
|
-
function markDirty(row: "NEW" | "OLD"): string {
|
|
156
|
+
function markDirty(row: "NEW" | "OLD", table: "messages" | "tool_calls"): string {
|
|
157
|
+
const toolAgent =
|
|
158
|
+
table === "tool_calls"
|
|
159
|
+
? `INSERT INTO tool_agent_dirty (bucket)
|
|
160
|
+
SELECT h FROM (SELECT ${hourOf(`${row}.timestamp`)} AS h) WHERE h NOT IN (SELECT bucket FROM tool_agent_dirty);`
|
|
161
|
+
: "";
|
|
148
162
|
return `INSERT INTO rollup_dirty (bucket)
|
|
149
163
|
SELECT h FROM (SELECT ${hourOf(`${row}.timestamp`)} AS h) WHERE h NOT IN (SELECT bucket FROM rollup_dirty);
|
|
150
164
|
INSERT INTO session_dirty (session_file)
|
|
151
|
-
SELECT ${row}.session_file WHERE ${row}.session_file NOT IN (SELECT session_file FROM session_dirty)
|
|
165
|
+
SELECT ${row}.session_file WHERE ${row}.session_file NOT IN (SELECT session_file FROM session_dirty);
|
|
166
|
+
${toolAgent}`;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Additive per-bucket tool-result facts per agent type (columns of `tool_calls`). */
|
|
170
|
+
function toolAgentFacts(bucketExpr: string): string {
|
|
171
|
+
return `${bucketExpr} AS bucket, agent_type, SUM(COALESCE(result_chars, 0)) AS result_chars`;
|
|
152
172
|
}
|
|
153
173
|
|
|
154
174
|
/** Per-transcript facts over `messages` (qualified by `p`); tool calls counted by subquery. */
|
|
@@ -184,9 +204,10 @@ export function ensureRollupSchema(database: Database): void {
|
|
|
184
204
|
const readMeta = (key: string) =>
|
|
185
205
|
(database.query("SELECT value FROM meta WHERE key = ?").get(key) as { value: string } | undefined)?.value;
|
|
186
206
|
const fresh = readMeta(ROLLUP_VERSION_KEY) !== ROLLUP_VERSION;
|
|
207
|
+
const toolAgentFresh = fresh || readMeta(TOOL_AGENT_VERSION_KEY) !== TOOL_AGENT_VERSION;
|
|
187
208
|
// Steady state touches no schema: DDL on every open would contend with
|
|
188
209
|
// other omp processes writing the same database.
|
|
189
|
-
if (!fresh && readMeta(TRIGGER_VERSION_KEY) === TRIGGER_VERSION) return;
|
|
210
|
+
if (!fresh && !toolAgentFresh && readMeta(TRIGGER_VERSION_KEY) === TRIGGER_VERSION) return;
|
|
190
211
|
database
|
|
191
212
|
.transaction(() => {
|
|
192
213
|
if (fresh) {
|
|
@@ -196,6 +217,10 @@ export function ensureRollupSchema(database: Database): void {
|
|
|
196
217
|
database.run("DROP TABLE IF EXISTS session_rollup");
|
|
197
218
|
database.run("DROP TABLE IF EXISTS session_dirty");
|
|
198
219
|
}
|
|
220
|
+
if (toolAgentFresh) {
|
|
221
|
+
database.run("DROP TABLE IF EXISTS tool_agent_rollup");
|
|
222
|
+
database.run("DROP TABLE IF EXISTS tool_agent_dirty");
|
|
223
|
+
}
|
|
199
224
|
database.run(`
|
|
200
225
|
CREATE TABLE IF NOT EXISTS message_rollup (
|
|
201
226
|
bucket INTEGER NOT NULL,
|
|
@@ -258,17 +283,24 @@ export function ensureRollupSchema(database: Database): void {
|
|
|
258
283
|
tool_calls INTEGER NOT NULL
|
|
259
284
|
) WITHOUT ROWID;
|
|
260
285
|
CREATE TABLE IF NOT EXISTS session_dirty (session_file TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
286
|
+
CREATE TABLE IF NOT EXISTS tool_agent_rollup (
|
|
287
|
+
bucket INTEGER NOT NULL,
|
|
288
|
+
agent_type TEXT NOT NULL,
|
|
289
|
+
result_chars INTEGER NOT NULL
|
|
290
|
+
);
|
|
291
|
+
CREATE INDEX IF NOT EXISTS idx_tool_agent_rollup_bucket ON tool_agent_rollup(bucket);
|
|
292
|
+
CREATE TABLE IF NOT EXISTS tool_agent_dirty (bucket INTEGER PRIMARY KEY) WITHOUT ROWID;
|
|
261
293
|
`);
|
|
262
294
|
// A tool share reads its assistant message, so message changes dirty the
|
|
263
295
|
// hour for both rollups (tool calls share their message's timestamp).
|
|
264
296
|
// Triggers must not use `OR IGNORE`: a trigger statement inherits the
|
|
265
297
|
// outer statement's conflict policy, and the UPSERTs in
|
|
266
298
|
// `insertMessageStats` would turn a duplicate dirty mark into a failed ingest.
|
|
267
|
-
for (const table of ["messages", "tool_calls"]) {
|
|
299
|
+
for (const table of ["messages", "tool_calls"] as const) {
|
|
268
300
|
const triggers = {
|
|
269
|
-
insert: `AFTER INSERT ON ${table} BEGIN ${markDirty("NEW")} END`,
|
|
270
|
-
delete: `AFTER DELETE ON ${table} BEGIN ${markDirty("OLD")} END`,
|
|
271
|
-
update: `AFTER UPDATE ON ${table} BEGIN ${markDirty("OLD")} ${markDirty("NEW")} END`,
|
|
301
|
+
insert: `AFTER INSERT ON ${table} BEGIN ${markDirty("NEW", table)} END`,
|
|
302
|
+
delete: `AFTER DELETE ON ${table} BEGIN ${markDirty("OLD", table)} END`,
|
|
303
|
+
update: `AFTER UPDATE ON ${table} BEGIN ${markDirty("OLD", table)} ${markDirty("NEW", table)} END`,
|
|
272
304
|
};
|
|
273
305
|
for (const [event, body] of Object.entries(triggers)) {
|
|
274
306
|
database.run(`DROP TRIGGER IF EXISTS rollup_dirty_${table}_${event}`);
|
|
@@ -292,6 +324,26 @@ export function ensureRollupSchema(database: Database): void {
|
|
|
292
324
|
.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)")
|
|
293
325
|
.run(ROLLUP_VERSION_KEY, ROLLUP_VERSION);
|
|
294
326
|
}
|
|
327
|
+
if (toolAgentFresh) {
|
|
328
|
+
// Every hour between the first and last call, seeded from two index lookups
|
|
329
|
+
// instead of a scan; hours without calls refresh to nothing.
|
|
330
|
+
database.run(`
|
|
331
|
+
WITH RECURSIVE h(bucket) AS (
|
|
332
|
+
SELECT ${hourOf("MIN(timestamp)")} FROM tool_calls WHERE timestamp >= ${SANE_TIMESTAMP_MS}
|
|
333
|
+
UNION ALL
|
|
334
|
+
SELECT bucket + ${HOUR_MS} FROM h
|
|
335
|
+
WHERE bucket + ${HOUR_MS} <= (SELECT MAX(timestamp) FROM tool_calls)
|
|
336
|
+
)
|
|
337
|
+
INSERT OR IGNORE INTO tool_agent_dirty (bucket) SELECT bucket FROM h WHERE bucket IS NOT NULL
|
|
338
|
+
`);
|
|
339
|
+
database.run(`
|
|
340
|
+
INSERT OR IGNORE INTO tool_agent_dirty (bucket)
|
|
341
|
+
SELECT DISTINCT ${hourOf("timestamp")} FROM tool_calls WHERE timestamp < ${SANE_TIMESTAMP_MS}
|
|
342
|
+
`);
|
|
343
|
+
database
|
|
344
|
+
.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)")
|
|
345
|
+
.run(TOOL_AGENT_VERSION_KEY, TOOL_AGENT_VERSION);
|
|
346
|
+
}
|
|
295
347
|
})
|
|
296
348
|
.immediate();
|
|
297
349
|
}
|
|
@@ -311,7 +363,8 @@ export function getRollupStatus(): RollupStatus {
|
|
|
311
363
|
if (!database) return { dirtyHours: 0, dirtySessions: 0 };
|
|
312
364
|
return database
|
|
313
365
|
.query(
|
|
314
|
-
|
|
366
|
+
`SELECT MAX((SELECT COUNT(*) FROM rollup_dirty), (SELECT COUNT(*) FROM tool_agent_dirty)) AS dirtyHours,
|
|
367
|
+
(SELECT COUNT(*) FROM session_dirty) AS dirtySessions`,
|
|
315
368
|
)
|
|
316
369
|
.get() as RollupStatus;
|
|
317
370
|
}
|
|
@@ -352,6 +405,23 @@ export function refreshRollupBatch(limit: number): number {
|
|
|
352
405
|
clean.run(bucket);
|
|
353
406
|
}
|
|
354
407
|
|
|
408
|
+
const agentBuckets = database
|
|
409
|
+
.query("SELECT bucket FROM tool_agent_dirty ORDER BY bucket DESC LIMIT ?")
|
|
410
|
+
.all(limit) as { bucket: number }[];
|
|
411
|
+
const clearAgent = database.query("DELETE FROM tool_agent_rollup WHERE bucket = ?");
|
|
412
|
+
const fillAgent = database.query(`
|
|
413
|
+
INSERT INTO tool_agent_rollup (bucket, agent_type, result_chars)
|
|
414
|
+
SELECT ${toolAgentFacts("?1")}
|
|
415
|
+
FROM tool_calls WHERE timestamp >= ?1 AND timestamp < ?1 + ${HOUR_MS}
|
|
416
|
+
GROUP BY agent_type
|
|
417
|
+
`);
|
|
418
|
+
const cleanAgent = database.query("DELETE FROM tool_agent_dirty WHERE bucket = ?");
|
|
419
|
+
for (const { bucket } of agentBuckets) {
|
|
420
|
+
clearAgent.run(bucket);
|
|
421
|
+
fillAgent.run(bucket);
|
|
422
|
+
cleanAgent.run(bucket);
|
|
423
|
+
}
|
|
424
|
+
|
|
355
425
|
// Transcripts are cheap (indexed by session_file); roll many per hour-batch.
|
|
356
426
|
const sessions = database
|
|
357
427
|
.query("SELECT session_file FROM session_dirty LIMIT ?")
|
|
@@ -369,7 +439,7 @@ export function refreshRollupBatch(limit: number): number {
|
|
|
369
439
|
fillSession.run(session_file);
|
|
370
440
|
cleanSession.run(session_file);
|
|
371
441
|
}
|
|
372
|
-
return buckets.length + sessions.length;
|
|
442
|
+
return buckets.length + agentBuckets.length + sessions.length;
|
|
373
443
|
});
|
|
374
444
|
return run.immediate();
|
|
375
445
|
}
|
|
@@ -1003,3 +1073,126 @@ export function getToolTimeSeries({ cutoff, bucketMs }: RangeWindow): ToolTimeSe
|
|
|
1003
1073
|
"GROUP BY 1, f.tool_name ORDER BY 1",
|
|
1004
1074
|
).map(row => ({ timestamp: row.bucket, tool: row.tool_name, calls: row.calls, errors: row.errors }));
|
|
1005
1075
|
}
|
|
1076
|
+
|
|
1077
|
+
// ---------------------------------------------------------------------------
|
|
1078
|
+
// Context facts (Spotlight tool-output share)
|
|
1079
|
+
// ---------------------------------------------------------------------------
|
|
1080
|
+
|
|
1081
|
+
/** Per-bucket context facts of every transcript of one agent type: tool-result characters and output tokens. */
|
|
1082
|
+
export interface ContextFactPoint {
|
|
1083
|
+
bucket: number;
|
|
1084
|
+
agentType: AgentType;
|
|
1085
|
+
resultChars: number;
|
|
1086
|
+
outputTokens: number;
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
/** Tool-result characters per hour and agent type over `[cutoff, now]`; same union shape as {@link toolSource}. */
|
|
1090
|
+
function toolAgentSource(database: Database, cutoff: number | null, fine: boolean): Source {
|
|
1091
|
+
if (fine) {
|
|
1092
|
+
return {
|
|
1093
|
+
sql: `SELECT ${toolAgentFacts("(timestamp / 300000) * 300000")} FROM tool_calls WHERE timestamp >= ? GROUP BY 1, agent_type`,
|
|
1094
|
+
params: [cutoff ?? 0],
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
const hi = cutoff === null ? null : Math.ceil(cutoff / HOUR_MS) * HOUR_MS;
|
|
1098
|
+
const { n } = database
|
|
1099
|
+
.query(`SELECT COUNT(*) AS n FROM (SELECT 1 FROM tool_agent_dirty LIMIT ${EXACT_DIRTY_LIMIT + 1})`)
|
|
1100
|
+
.get() as { n: number };
|
|
1101
|
+
const exact = n <= EXACT_DIRTY_LIMIT;
|
|
1102
|
+
const parts: string[] = [];
|
|
1103
|
+
const params: number[] = [];
|
|
1104
|
+
parts.push(
|
|
1105
|
+
`SELECT bucket, agent_type, result_chars FROM tool_agent_rollup
|
|
1106
|
+
WHERE ${exact ? "bucket NOT IN (SELECT bucket FROM tool_agent_dirty)" : "1"}${hi !== null ? " AND bucket >= ?" : ""}`,
|
|
1107
|
+
);
|
|
1108
|
+
if (hi !== null) params.push(hi);
|
|
1109
|
+
if (cutoff !== null && hi !== null && cutoff < hi) {
|
|
1110
|
+
parts.push(
|
|
1111
|
+
`SELECT ${toolAgentFacts(hourOf("timestamp"))} FROM tool_calls
|
|
1112
|
+
WHERE timestamp >= ? AND timestamp < ? GROUP BY 1, agent_type`,
|
|
1113
|
+
);
|
|
1114
|
+
params.push(cutoff, hi);
|
|
1115
|
+
}
|
|
1116
|
+
if (exact) {
|
|
1117
|
+
parts.push(
|
|
1118
|
+
`SELECT d.bucket AS bucket, t.agent_type AS agent_type, SUM(COALESCE(t.result_chars, 0)) AS result_chars
|
|
1119
|
+
FROM tool_agent_dirty d JOIN tool_calls t ON t.timestamp >= d.bucket AND t.timestamp < d.bucket + ${HOUR_MS}
|
|
1120
|
+
${hi !== null ? "WHERE d.bucket >= ?" : ""}
|
|
1121
|
+
GROUP BY d.bucket, t.agent_type`,
|
|
1122
|
+
);
|
|
1123
|
+
if (hi !== null) params.push(hi);
|
|
1124
|
+
}
|
|
1125
|
+
return { sql: parts.join(" UNION ALL "), params };
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
/** {@link ContextFactPoint}s over a window, from the rollups (exact while few hours are dirty). */
|
|
1129
|
+
export function getContextFactSeries(database: Database, { cutoff, bucketMs }: RangeWindow): ContextFactPoint[] {
|
|
1130
|
+
const fine = bucketMs < HOUR_MS;
|
|
1131
|
+
const normalized = normalizeCutoff(cutoff);
|
|
1132
|
+
const tools = toolAgentSource(database, normalized, fine);
|
|
1133
|
+
const messages = messageSource(database, normalized, fine);
|
|
1134
|
+
const points = new Map<string, ContextFactPoint>();
|
|
1135
|
+
const point = (bucket: number, agentType: AgentType) => {
|
|
1136
|
+
const key = `${bucket}:${agentType}`;
|
|
1137
|
+
let p = points.get(key);
|
|
1138
|
+
if (!p) {
|
|
1139
|
+
p = { bucket, agentType, resultChars: 0, outputTokens: 0 };
|
|
1140
|
+
points.set(key, p);
|
|
1141
|
+
}
|
|
1142
|
+
return p;
|
|
1143
|
+
};
|
|
1144
|
+
type Row = { bucket: number; agent_type: AgentType; n: number | null };
|
|
1145
|
+
const toolRows = database
|
|
1146
|
+
.query(
|
|
1147
|
+
`SELECT ${seriesBucket(bucketMs)} AS bucket, f.agent_type AS agent_type, SUM(f.result_chars) AS n
|
|
1148
|
+
FROM (${tools.sql}) f GROUP BY 1, 2`,
|
|
1149
|
+
)
|
|
1150
|
+
.all(...tools.params) as Row[];
|
|
1151
|
+
for (const row of toolRows) point(row.bucket, row.agent_type).resultChars += row.n ?? 0;
|
|
1152
|
+
const messageRows = database
|
|
1153
|
+
.query(
|
|
1154
|
+
`SELECT ${seriesBucket(bucketMs)} AS bucket, f.agent_type AS agent_type, SUM(f.output_tokens) AS n
|
|
1155
|
+
FROM (${messages.sql}) f GROUP BY 1, 2`,
|
|
1156
|
+
)
|
|
1157
|
+
.all(...messages.params) as Row[];
|
|
1158
|
+
for (const row of messageRows) point(row.bucket, row.agent_type).outputTokens += row.n ?? 0;
|
|
1159
|
+
return [...points.values()].sort((a, b) => a.bucket - b.bucket);
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
/** A transcript's request span and its first request's prompt (input + cache read + cache write). */
|
|
1163
|
+
export interface SessionSpan {
|
|
1164
|
+
sessionFile: string;
|
|
1165
|
+
startedAt: number;
|
|
1166
|
+
endedAt: number;
|
|
1167
|
+
firstPrompt: number;
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
/**
|
|
1171
|
+
* Spans of the transcripts with a request at or after `endedAfter` (all when null), from `session_rollup` with
|
|
1172
|
+
* the same exactness rule as {@link getSessionRollups}.
|
|
1173
|
+
*/
|
|
1174
|
+
export function getSessionSpans(database: Database, endedAfter: number | null): SessionSpan[] {
|
|
1175
|
+
const { n } = database
|
|
1176
|
+
.query(`SELECT COUNT(*) AS n FROM (SELECT 1 FROM session_dirty LIMIT ${EXACT_DIRTY_SESSIONS + 1})`)
|
|
1177
|
+
.get() as { n: number };
|
|
1178
|
+
const exact = n <= EXACT_DIRTY_SESSIONS;
|
|
1179
|
+
const parts = [
|
|
1180
|
+
`SELECT session_file, started_at, ended_at FROM session_rollup
|
|
1181
|
+
WHERE ended_at >= ?1${exact ? " AND session_file NOT IN (SELECT session_file FROM session_dirty)" : ""}`,
|
|
1182
|
+
];
|
|
1183
|
+
if (exact) {
|
|
1184
|
+
parts.push(
|
|
1185
|
+
`SELECT m.session_file, MIN(m.timestamp), MAX(m.timestamp + COALESCE(m.duration, 0))
|
|
1186
|
+
FROM session_dirty d JOIN messages m ON m.session_file = d.session_file
|
|
1187
|
+
GROUP BY m.session_file HAVING MAX(m.timestamp + COALESCE(m.duration, 0)) >= ?1`,
|
|
1188
|
+
);
|
|
1189
|
+
}
|
|
1190
|
+
return database
|
|
1191
|
+
.query(
|
|
1192
|
+
`SELECT s.session_file AS sessionFile, s.started_at AS startedAt, s.ended_at AS endedAt,
|
|
1193
|
+
COALESCE((SELECT m.input_tokens + m.cache_read_tokens + m.cache_write_tokens FROM messages m
|
|
1194
|
+
WHERE m.timestamp = s.started_at AND m.session_file = s.session_file LIMIT 1), 0) AS firstPrompt
|
|
1195
|
+
FROM (${parts.join(" UNION ALL ")}) s`,
|
|
1196
|
+
)
|
|
1197
|
+
.all(endedAfter ?? 0) as SessionSpan[];
|
|
1198
|
+
}
|
package/src/server.ts
CHANGED
|
@@ -40,6 +40,7 @@ import {
|
|
|
40
40
|
STATS_DASHBOARD_SECURITY_VERSION,
|
|
41
41
|
} from "./port-conflict";
|
|
42
42
|
import { getStatsByModel, getTimeSeries } from "./rollup";
|
|
43
|
+
import { getSpotlightDashboardStats, getSpotlightSessionContext } from "./spotlight-aggregator";
|
|
43
44
|
import {
|
|
44
45
|
buildSessionTrace,
|
|
45
46
|
getTraceEntry,
|
|
@@ -170,6 +171,33 @@ const STATS_ACTION_HEADER = "X-Zeta-Stats-Action";
|
|
|
170
171
|
/** What the page's Close calls; unset, the page offers none. */
|
|
171
172
|
let closeHandler: (() => void) | undefined;
|
|
172
173
|
|
|
174
|
+
/** Longest a Spotlight build serves later requests of its data version: its time range moves with the clock. */
|
|
175
|
+
const SPOTLIGHT_VIEW_TTL_MS = 60_000;
|
|
176
|
+
|
|
177
|
+
/** Spotlight payloads (JSON) of one live data version by `range\0agent`, with when each build started. */
|
|
178
|
+
let spotlightViews: { version: number; views: Map<string, { at: number; json: Promise<string> }> } | null = null;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* The Spotlight dashboard as JSON, built once per data version and view. Every open page refetches on each version
|
|
182
|
+
* bump and a build takes seconds on the thread that also ingests, so pages showing the same view share one build.
|
|
183
|
+
*/
|
|
184
|
+
function spotlightView(range: string | null, agent: string | null): Promise<string> {
|
|
185
|
+
const version = statsLive().status().version;
|
|
186
|
+
if (spotlightViews?.version !== version) spotlightViews = { version, views: new Map() };
|
|
187
|
+
const views = spotlightViews.views;
|
|
188
|
+
const key = `${range ?? ""}\0${agent ?? ""}`;
|
|
189
|
+
const cached = views.get(key);
|
|
190
|
+
if (cached && Date.now() - cached.at < SPOTLIGHT_VIEW_TTL_MS) return cached.json;
|
|
191
|
+
const json = getSpotlightDashboardStats(range, agent).then(stats => JSON.stringify(stats));
|
|
192
|
+
const entry = { at: Date.now(), json };
|
|
193
|
+
views.set(key, entry);
|
|
194
|
+
// A failed build is not reused.
|
|
195
|
+
json.catch(() => {
|
|
196
|
+
if (views.get(key) === entry) views.delete(key);
|
|
197
|
+
});
|
|
198
|
+
return json;
|
|
199
|
+
}
|
|
200
|
+
|
|
173
201
|
/**
|
|
174
202
|
* Let the page close the dashboard: while `close` is set, it shows a Close
|
|
175
203
|
* button (and takes Esc and Ctrl+C) that calls it. `zetacode stats` sets it while
|
|
@@ -307,6 +335,20 @@ export async function handleApi(req: Request): Promise<Response> {
|
|
|
307
335
|
const stats = await getGainDashboardStats(range, project);
|
|
308
336
|
return Response.json(stats);
|
|
309
337
|
}
|
|
338
|
+
if (path === "/api/stats/spotlight") {
|
|
339
|
+
return new Response(await spotlightView(range, url.searchParams.get("agent")), {
|
|
340
|
+
headers: { "content-type": "application/json;charset=utf-8" },
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (path === "/api/stats/spotlight/session") {
|
|
345
|
+
const file = url.searchParams.get("file");
|
|
346
|
+
if (!file) return Response.json({ error: "file required" }, { status: 400 });
|
|
347
|
+
const context = await getSpotlightSessionContext(file);
|
|
348
|
+
if (!context) return Response.json({ error: "not a Spotlight experiment session" }, { status: 404 });
|
|
349
|
+
return Response.json(context);
|
|
350
|
+
}
|
|
351
|
+
|
|
310
352
|
if (path === "/api/sessions") {
|
|
311
353
|
const limitParam = Number(url.searchParams.get("limit") ?? "100");
|
|
312
354
|
const limit = Number.isFinite(limitParam) && limitParam > 0 ? Math.floor(limitParam) : 100;
|