@linxiraos/pi-stats 1.5.14 → 1.5.16
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 +39 -16
- package/README.md +7 -1
- package/THIRD-PARTY-NOTICES.txt +1 -1
- package/dist/client/index.js +81 -81
- package/dist/types/aggregator.d.ts +1 -1
- package/dist/types/client/app/Shell.d.ts +1 -1
- package/dist/types/client/data/colors.d.ts +5 -2
- package/dist/types/client/data/view-models.d.ts +30 -11
- package/dist/types/client/types.d.ts +3 -2
- package/dist/types/db.d.ts +23 -2
- package/dist/types/gain-aggregator.d.ts +4 -4
- package/dist/types/parser.d.ts +2 -1
- package/dist/types/rollup.d.ts +12 -4
- package/dist/types/server.d.ts +2 -0
- package/dist/types/shared-types.d.ts +34 -9
- package/dist/types/side-channels.d.ts +28 -0
- package/dist/types/spotlight-ingest.d.ts +8 -5
- package/dist/types/types.d.ts +42 -1
- package/package.json +44 -44
- package/src/aggregator.ts +11 -4
- package/src/client/app/Shell.tsx +1 -1
- package/src/client/charts/TimeChart.tsx +8 -1
- package/src/client/data/colors.ts +9 -3
- package/src/client/data/range.ts +44 -7
- package/src/client/data/view-models.ts +83 -31
- package/src/client/routes/GainRoute.tsx +5 -2
- package/src/client/routes/OverviewRoute.tsx +86 -33
- package/src/client/types.ts +3 -1
- package/src/db.ts +150 -20
- package/src/gain-aggregator.ts +68 -32
- package/src/parser.ts +46 -1
- package/src/rollup.ts +112 -25
- package/src/server.ts +68 -0
- package/src/shared-types.ts +36 -9
- package/src/side-channels.ts +63 -0
- package/src/spotlight-ingest.ts +49 -23
- package/src/types.ts +36 -1
package/src/rollup.ts
CHANGED
|
@@ -27,12 +27,14 @@
|
|
|
27
27
|
|
|
28
28
|
import type { Database } from "bun:sqlite";
|
|
29
29
|
import { currentDb, unpricedRequestSql } from "./db";
|
|
30
|
+
import { isDecisionModelApi, sideChannelCategory } from "./side-channels";
|
|
30
31
|
import type {
|
|
31
32
|
AgentType,
|
|
32
33
|
AgentTypeStats,
|
|
33
34
|
AggregatedStats,
|
|
34
35
|
CostTimeSeriesPoint,
|
|
35
36
|
DailyActivityPoint,
|
|
37
|
+
DashboardStats,
|
|
36
38
|
FolderStats,
|
|
37
39
|
ModelDailyActivityPoint,
|
|
38
40
|
ModelHourlyActivityPoint,
|
|
@@ -42,10 +44,12 @@ import type {
|
|
|
42
44
|
ProviderAggregate,
|
|
43
45
|
ProviderHourlyPoint,
|
|
44
46
|
ProviderTimeSeriesPoint,
|
|
47
|
+
SideChannelStats,
|
|
45
48
|
TimeSeriesPoint,
|
|
46
49
|
ToolModelStats,
|
|
47
50
|
ToolTimeSeriesPoint,
|
|
48
51
|
ToolUsageStats,
|
|
52
|
+
UsageAttributionTotals,
|
|
49
53
|
} from "./types";
|
|
50
54
|
|
|
51
55
|
const HOUR_MS = 60 * 60 * 1000;
|
|
@@ -55,7 +59,7 @@ const DAY_MS = 24 * HOUR_MS;
|
|
|
55
59
|
* Bump when the rollup schema or fact definitions change: the tables are then
|
|
56
60
|
* dropped and every hour is rebuilt from the raw tables.
|
|
57
61
|
*/
|
|
58
|
-
const ROLLUP_VERSION = "
|
|
62
|
+
const ROLLUP_VERSION = "3";
|
|
59
63
|
const ROLLUP_VERSION_KEY = "rollup_version";
|
|
60
64
|
/** Bump when the dirty-marking triggers change; they are then recreated in place. */
|
|
61
65
|
const TRIGGER_VERSION = "4";
|
|
@@ -81,13 +85,25 @@ const REFRESH_MAX_BATCH = 64;
|
|
|
81
85
|
// the raw read paths so both produce identical columns.
|
|
82
86
|
// ---------------------------------------------------------------------------
|
|
83
87
|
|
|
84
|
-
|
|
88
|
+
/**
|
|
89
|
+
* `purpose` (NULL on assistant messages) and `api` carry the attribution of
|
|
90
|
+
* off-transcript model calls. Both stay raw: the purpose's category and whether
|
|
91
|
+
* the api is a native judgment api are decided in TypeScript at read time, so
|
|
92
|
+
* re-cutting either needs no rebuild.
|
|
93
|
+
*/
|
|
94
|
+
const MESSAGE_DIMENSION_COLUMNS = ["model", "provider", "folder", "agent_type", "purpose", "api"] as const;
|
|
95
|
+
const MESSAGE_DIMENSIONS = MESSAGE_DIMENSION_COLUMNS.join(", ");
|
|
96
|
+
|
|
97
|
+
/** The message dimensions as columns of `messages` qualified by `p`. */
|
|
98
|
+
function messageDimensions(p: string): string {
|
|
99
|
+
return MESSAGE_DIMENSION_COLUMNS.map(column => `${p}${column}`).join(", ");
|
|
100
|
+
}
|
|
85
101
|
|
|
86
102
|
/** Additive per-bucket facts over `messages` (columns qualified by `p`). */
|
|
87
103
|
function messageFacts(bucketExpr: string, p: string): string {
|
|
88
104
|
return `
|
|
89
105
|
${bucketExpr} AS bucket,
|
|
90
|
-
${
|
|
106
|
+
${MESSAGE_DIMENSION_COLUMNS.map(column => `${p}${column} AS ${column}`).join(", ")},
|
|
91
107
|
COUNT(*) AS requests,
|
|
92
108
|
SUM(CASE WHEN ${p}stop_reason = 'error' THEN 1 ELSE 0 END) AS failed,
|
|
93
109
|
SUM(${p}input_tokens) AS input_tokens,
|
|
@@ -228,6 +244,8 @@ export function ensureRollupSchema(database: Database): void {
|
|
|
228
244
|
provider TEXT NOT NULL,
|
|
229
245
|
folder TEXT NOT NULL,
|
|
230
246
|
agent_type TEXT NOT NULL,
|
|
247
|
+
purpose TEXT,
|
|
248
|
+
api TEXT NOT NULL,
|
|
231
249
|
requests INTEGER NOT NULL,
|
|
232
250
|
failed INTEGER NOT NULL,
|
|
233
251
|
input_tokens INTEGER NOT NULL,
|
|
@@ -529,7 +547,7 @@ function messageSource(database: Database, cutoff: number | null, fine: boolean)
|
|
|
529
547
|
`SELECT ${messageFacts("d.bucket", "m.")}
|
|
530
548
|
FROM rollup_dirty d JOIN messages m ON m.timestamp >= d.bucket AND m.timestamp < d.bucket + ${HOUR_MS}
|
|
531
549
|
${hi !== null ? "WHERE d.bucket >= ?" : ""}
|
|
532
|
-
GROUP BY d.bucket, m.
|
|
550
|
+
GROUP BY d.bucket, ${messageDimensions("m.")}`,
|
|
533
551
|
);
|
|
534
552
|
if (hi !== null) params.push(hi);
|
|
535
553
|
}
|
|
@@ -576,8 +594,12 @@ function toolSource(database: Database, cutoff: number | null, fine: boolean): S
|
|
|
576
594
|
}
|
|
577
595
|
|
|
578
596
|
/** Run `select … FROM (<facts>) f <tail>` over the message facts for a window. */
|
|
579
|
-
function queryMessages<T>(
|
|
580
|
-
|
|
597
|
+
function queryMessages<T>(
|
|
598
|
+
window: Pick<RangeWindow, "cutoff"> & { bucketMs?: number },
|
|
599
|
+
select: string,
|
|
600
|
+
tail = "",
|
|
601
|
+
database: Database | null = currentDb(),
|
|
602
|
+
): T[] {
|
|
581
603
|
if (!database) return [];
|
|
582
604
|
const fine = window.bucketMs !== undefined && window.bucketMs < HOUR_MS;
|
|
583
605
|
const source = messageSource(database, normalizeCutoff(window.cutoff), fine);
|
|
@@ -740,10 +762,19 @@ export function getProjectSessionFile(folder: string): string | null {
|
|
|
740
762
|
return row?.session_file ?? null;
|
|
741
763
|
}
|
|
742
764
|
|
|
743
|
-
/**
|
|
744
|
-
|
|
745
|
-
|
|
765
|
+
/**
|
|
766
|
+
* Usage attributed to what spent it: conversation turns per agent type (main,
|
|
767
|
+
* subagent, advisor) and side channels per category, apart for decision models.
|
|
768
|
+
* Rows are grouped by their raw dimensions and classified here (see
|
|
769
|
+
* `side-channels.ts`), so every row lands in exactly one group.
|
|
770
|
+
*/
|
|
771
|
+
export function getUsageAttribution(
|
|
772
|
+
cutoff: number | null = null,
|
|
773
|
+
): Pick<DashboardStats, "byAgentType" | "bySideChannel"> {
|
|
774
|
+
const rows = queryMessages<{
|
|
746
775
|
agent_type: string | null;
|
|
776
|
+
purpose: string | null;
|
|
777
|
+
api: string;
|
|
747
778
|
requests: number;
|
|
748
779
|
input_tokens: number | null;
|
|
749
780
|
output_tokens: number | null;
|
|
@@ -752,19 +783,59 @@ export function getStatsByAgentType(cutoff: number | null = null): AgentTypeStat
|
|
|
752
783
|
cost_total: number | null;
|
|
753
784
|
}>(
|
|
754
785
|
{ cutoff },
|
|
755
|
-
`f.agent_type AS agent_type,
|
|
786
|
+
`f.agent_type AS agent_type, f.purpose AS purpose, f.api AS api,
|
|
787
|
+
SUM(f.requests) AS requests, SUM(f.input_tokens) AS input_tokens,
|
|
756
788
|
SUM(f.output_tokens) AS output_tokens, SUM(f.cache_read_tokens) AS cache_read_tokens,
|
|
757
789
|
SUM(f.cache_write_tokens) AS cache_write_tokens, TOTAL(f.cost_total) AS cost_total`,
|
|
758
|
-
"GROUP BY f.agent_type",
|
|
759
|
-
)
|
|
760
|
-
|
|
761
|
-
totalRequests:
|
|
762
|
-
totalInputTokens:
|
|
763
|
-
totalOutputTokens:
|
|
764
|
-
totalCacheReadTokens:
|
|
765
|
-
totalCacheWriteTokens:
|
|
766
|
-
totalCost:
|
|
767
|
-
})
|
|
790
|
+
"GROUP BY f.agent_type, f.purpose, f.api",
|
|
791
|
+
);
|
|
792
|
+
const emptyTotals = (): UsageAttributionTotals => ({
|
|
793
|
+
totalRequests: 0,
|
|
794
|
+
totalInputTokens: 0,
|
|
795
|
+
totalOutputTokens: 0,
|
|
796
|
+
totalCacheReadTokens: 0,
|
|
797
|
+
totalCacheWriteTokens: 0,
|
|
798
|
+
totalCost: 0,
|
|
799
|
+
});
|
|
800
|
+
const byAgentType = new Map<AgentType, AgentTypeStats>();
|
|
801
|
+
const bySideChannel = new Map<string, SideChannelStats>();
|
|
802
|
+
for (const row of rows) {
|
|
803
|
+
const category = sideChannelCategory(row.purpose);
|
|
804
|
+
let totals: UsageAttributionTotals;
|
|
805
|
+
if (category === null) {
|
|
806
|
+
const agentType = (row.agent_type as AgentType | null) ?? "main";
|
|
807
|
+
let stat = byAgentType.get(agentType);
|
|
808
|
+
if (!stat) {
|
|
809
|
+
stat = { agentType, ...emptyTotals() };
|
|
810
|
+
byAgentType.set(agentType, stat);
|
|
811
|
+
}
|
|
812
|
+
totals = stat;
|
|
813
|
+
} else {
|
|
814
|
+
const decision = isDecisionModelApi(row.api);
|
|
815
|
+
const key = `${decision ? "decision" : "model"}:${category}`;
|
|
816
|
+
let stat = bySideChannel.get(key);
|
|
817
|
+
if (!stat) {
|
|
818
|
+
stat = { category, decision, ...emptyTotals() };
|
|
819
|
+
bySideChannel.set(key, stat);
|
|
820
|
+
}
|
|
821
|
+
totals = stat;
|
|
822
|
+
}
|
|
823
|
+
totals.totalRequests += row.requests;
|
|
824
|
+
totals.totalInputTokens += row.input_tokens ?? 0;
|
|
825
|
+
totals.totalOutputTokens += row.output_tokens ?? 0;
|
|
826
|
+
totals.totalCacheReadTokens += row.cache_read_tokens ?? 0;
|
|
827
|
+
totals.totalCacheWriteTokens += row.cache_write_tokens ?? 0;
|
|
828
|
+
totals.totalCost += row.cost_total ?? 0;
|
|
829
|
+
}
|
|
830
|
+
return {
|
|
831
|
+
byAgentType: [...byAgentType.values()],
|
|
832
|
+
bySideChannel: [...bySideChannel.values()].sort((a, b) => b.totalRequests - a.totalRequests),
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/** Token usage per agent type (main, subagent, advisor). */
|
|
837
|
+
export function getStatsByAgentType(cutoff: number | null = null): AgentTypeStats[] {
|
|
838
|
+
return getUsageAttribution(cutoff).byAgentType;
|
|
768
839
|
}
|
|
769
840
|
|
|
770
841
|
/** Requests, errors, tokens and cost per bucket. */
|
|
@@ -926,22 +997,38 @@ export function getProviderHourlyBurn(cutoff: number | null = null): ProviderHou
|
|
|
926
997
|
}));
|
|
927
998
|
}
|
|
928
999
|
|
|
1000
|
+
/**
|
|
1001
|
+
* Whether the stored rollup was built under this build's {@link ROLLUP_VERSION}.
|
|
1002
|
+
* Only {@link ensureRollupSchema} rebuilds an older one, so a connection that
|
|
1003
|
+
* skips it (the read-only `/usage` paint) must not trust the rollup otherwise.
|
|
1004
|
+
*/
|
|
1005
|
+
function rollupIsCurrent(database: Database): boolean {
|
|
1006
|
+
const row = database
|
|
1007
|
+
.query<{ value: string }, [string]>("SELECT value FROM meta WHERE key = ?")
|
|
1008
|
+
.get(ROLLUP_VERSION_KEY);
|
|
1009
|
+
return row?.value === ROLLUP_VERSION;
|
|
1010
|
+
}
|
|
1011
|
+
|
|
929
1012
|
/**
|
|
930
1013
|
* Per-local-day request/token/cost totals since `cutoff`, oldest first, read
|
|
931
1014
|
* from the hourly rollup. Returns null when the local UTC offset is not a whole
|
|
932
1015
|
* hour (now or at `cutoff`), since hourly buckets then straddle local midnight,
|
|
933
|
-
*
|
|
934
|
-
*
|
|
1016
|
+
* when the stored rollup is missing or was built under another version, or
|
|
1017
|
+
* while the dirty backlog is too large for exact reads; callers then aggregate
|
|
1018
|
+
* the raw rows instead.
|
|
935
1019
|
*/
|
|
936
|
-
export function getDailyActivityFromRollup(
|
|
1020
|
+
export function getDailyActivityFromRollup(
|
|
1021
|
+
cutoff: number,
|
|
1022
|
+
database: Database | null = currentDb(),
|
|
1023
|
+
): DailyActivityPoint[] | null {
|
|
937
1024
|
if (new Date().getTimezoneOffset() % 60 !== 0 || new Date(cutoff).getTimezoneOffset() % 60 !== 0) return null;
|
|
938
|
-
|
|
939
|
-
if (!database || !dirtyIsSmall(database)) return null;
|
|
1025
|
+
if (!database || !rollupIsCurrent(database) || !dirtyIsSmall(database)) return null;
|
|
940
1026
|
return queryMessages<{ day: string; cost: number; requests: number; total_tokens: number | null }>(
|
|
941
1027
|
{ cutoff },
|
|
942
1028
|
`date(f.bucket / 1000, 'unixepoch', 'localtime') AS day, TOTAL(f.cost_total) AS cost,
|
|
943
1029
|
SUM(f.requests) AS requests, SUM(f.total_tokens) AS total_tokens`,
|
|
944
1030
|
"GROUP BY day ORDER BY day",
|
|
1031
|
+
database,
|
|
945
1032
|
).map(row => ({ day: row.day, cost: row.cost, requests: row.requests, totalTokens: row.total_tokens ?? 0 }));
|
|
946
1033
|
}
|
|
947
1034
|
|
package/src/server.ts
CHANGED
|
@@ -488,12 +488,80 @@ export function formatStatsDashboardUrl(hostname: string, port: number): string
|
|
|
488
488
|
return `http://${urlHostname}:${port}`;
|
|
489
489
|
}
|
|
490
490
|
|
|
491
|
+
/** Extra Host names (comma-separated) the dashboard answers to; `*.example.com` allows its subdomains. */
|
|
492
|
+
export const STATS_ALLOWED_HOSTS_ENV = "OMP_STATS_ALLOWED_HOSTS";
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Suffixes no public DNS server can hand out: loopback, mDNS, private-use names, Tailscale MagicDNS, and the
|
|
496
|
+
* undelegated search domains home routers assign (`.lan`, `.home`, `.corp`, `.localdomain`).
|
|
497
|
+
*/
|
|
498
|
+
const PRIVATE_NAME_SUFFIXES = [
|
|
499
|
+
".localhost",
|
|
500
|
+
".local",
|
|
501
|
+
".internal",
|
|
502
|
+
".home.arpa",
|
|
503
|
+
".ts.net",
|
|
504
|
+
".lan",
|
|
505
|
+
".home",
|
|
506
|
+
".corp",
|
|
507
|
+
".localdomain",
|
|
508
|
+
];
|
|
509
|
+
const IPV4_LITERAL = /^\d+\.\d+\.\d+\.\d+$/;
|
|
510
|
+
|
|
511
|
+
/** Host names allowed beyond the built-in rules: exact names and `.suffix`es. */
|
|
512
|
+
interface AllowedHosts {
|
|
513
|
+
exact: Set<string>;
|
|
514
|
+
suffixes: string[];
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function normalizeHostName(name: string): string {
|
|
518
|
+
return name.trim().toLowerCase().replace(/\.$/, "");
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* DNS-rebinding guard. A rebinding page reaches the dashboard under a public name whose DNS the attacker
|
|
523
|
+
* controls, and the browser sends that name as Host; it can never send an IP literal or a name public DNS
|
|
524
|
+
* cannot resolve. So IP literals, `localhost`, single-label names (LAN and MagicDNS short names) and
|
|
525
|
+
* {@link PRIVATE_NAME_SUFFIXES} pass (Tailscale Serve forwards its `*.ts.net` Host unchanged), and any other
|
|
526
|
+
* dotted name must be the bind name or listed in {@link STATS_ALLOWED_HOSTS_ENV}. `hostname` is the parsed
|
|
527
|
+
* request URL's.
|
|
528
|
+
*/
|
|
529
|
+
function isRebindSafeHost(hostname: string, allowed: AllowedHosts): boolean {
|
|
530
|
+
const name = normalizeHostName(hostname);
|
|
531
|
+
if (name.startsWith("[") || IPV4_LITERAL.test(name) || !name.includes(".")) return true;
|
|
532
|
+
if (allowed.exact.has(name)) return true;
|
|
533
|
+
return [...PRIVATE_NAME_SUFFIXES, ...allowed.suffixes].some(suffix => name.endsWith(suffix));
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function readAllowedHosts(bindHostname: string): AllowedHosts {
|
|
537
|
+
// The operator chose the bind name, and the printed URL and the reuse probe both use it.
|
|
538
|
+
const allowed: AllowedHosts = { exact: new Set([normalizeHostName(bindHostname)]), suffixes: [] };
|
|
539
|
+
for (const entry of (process.env[STATS_ALLOWED_HOSTS_ENV] ?? "").split(",")) {
|
|
540
|
+
const name = normalizeHostName(entry);
|
|
541
|
+
if (name.startsWith("*.")) {
|
|
542
|
+
if (name.length > 2) allowed.suffixes.push(name.slice(1));
|
|
543
|
+
} else if (name) {
|
|
544
|
+
allowed.exact.add(name);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
return allowed;
|
|
548
|
+
}
|
|
549
|
+
|
|
491
550
|
function createDashboardServer(port: number, hostname: string): Server<undefined> {
|
|
551
|
+
const allowedHosts = readAllowedHosts(hostname);
|
|
492
552
|
const server = Bun.serve({
|
|
493
553
|
port,
|
|
494
554
|
hostname,
|
|
495
555
|
async fetch(req, server) {
|
|
496
556
|
const url = new URL(req.url);
|
|
557
|
+
if (!isRebindSafeHost(url.hostname, allowedHosts)) {
|
|
558
|
+
return new Response(
|
|
559
|
+
`Host not allowed; add it to ${STATS_ALLOWED_HOSTS_ENV} to serve the dashboard under it`,
|
|
560
|
+
{
|
|
561
|
+
status: 403,
|
|
562
|
+
},
|
|
563
|
+
);
|
|
564
|
+
}
|
|
497
565
|
const path = url.pathname;
|
|
498
566
|
|
|
499
567
|
// The identity header lets another omp session's reuse probe positively
|
package/src/shared-types.ts
CHANGED
|
@@ -184,6 +184,7 @@ export interface DashboardStats {
|
|
|
184
184
|
byModel: ModelStats[];
|
|
185
185
|
byFolder: FolderStats[];
|
|
186
186
|
byAgentType: AgentTypeStats[];
|
|
187
|
+
bySideChannel: SideChannelStats[];
|
|
187
188
|
timeSeries: TimeSeriesPoint[];
|
|
188
189
|
modelSeries: ModelTimeSeriesPoint[];
|
|
189
190
|
modelPerformanceSeries: ModelPerformancePoint[];
|
|
@@ -199,12 +200,12 @@ export interface DashboardStats {
|
|
|
199
200
|
export type AgentType = "main" | "subagent" | "advisor";
|
|
200
201
|
|
|
201
202
|
/**
|
|
202
|
-
*
|
|
203
|
-
* columns are explicit so the dashboard's share
|
|
204
|
-
* counts it renders (input + output + cache read +
|
|
203
|
+
* Request, token and cost totals of one usage-attribution group over the
|
|
204
|
+
* active range. Token columns are explicit so the dashboard's share
|
|
205
|
+
* denominator matches the counts it renders (input + output + cache read +
|
|
206
|
+
* cache write).
|
|
205
207
|
*/
|
|
206
|
-
export interface
|
|
207
|
-
agentType: AgentType;
|
|
208
|
+
export interface UsageAttributionTotals {
|
|
208
209
|
/** Total number of requests */
|
|
209
210
|
totalRequests: number;
|
|
210
211
|
/** Total input tokens */
|
|
@@ -219,6 +220,28 @@ export interface AgentTypeStats {
|
|
|
219
220
|
totalCost: number;
|
|
220
221
|
}
|
|
221
222
|
|
|
223
|
+
/**
|
|
224
|
+
* Usage of conversation turns (assistant messages, discarded ones included)
|
|
225
|
+
* aggregated by {@link AgentType}. Off-transcript model calls are not in here:
|
|
226
|
+
* see {@link SideChannelStats}.
|
|
227
|
+
*/
|
|
228
|
+
export interface AgentTypeStats extends UsageAttributionTotals {
|
|
229
|
+
agentType: AgentType;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Usage of side channels (model calls that are not conversation turns: title
|
|
234
|
+
* generation, job captions, judge queries, …) aggregated per use case, apart
|
|
235
|
+
* for calls served by a decision model and calls served by a language model.
|
|
236
|
+
* Busiest group first.
|
|
237
|
+
*/
|
|
238
|
+
export interface SideChannelStats extends UsageAttributionTotals {
|
|
239
|
+
/** Use case, such as `title` or `progress`; a purpose without a known category is its own. */
|
|
240
|
+
category: string;
|
|
241
|
+
/** Whether the calls ran on a decision model (an api that answers judgments natively). */
|
|
242
|
+
decision: boolean;
|
|
243
|
+
}
|
|
244
|
+
|
|
222
245
|
/**
|
|
223
246
|
* Model-side tallies over assistant turns. Every field except `messages`,
|
|
224
247
|
* `collapse`, `words` and `toolErrors` counts turns carrying the signal, so
|
|
@@ -388,7 +411,7 @@ export interface FrustrationDashboardStats {
|
|
|
388
411
|
byModel: FrustrationModelStats[];
|
|
389
412
|
/** Model-side (AI breakdown) analysis alongside the user-side tallies. */
|
|
390
413
|
modelSide: ModelSideDashboardStats;
|
|
391
|
-
/** Whether this dashboard host can run the judge (standalone `
|
|
414
|
+
/** Whether this dashboard host can run the judge (standalone `pi-stats` cannot). */
|
|
392
415
|
judgeAvailable: boolean;
|
|
393
416
|
job: FrustrationJobStatus;
|
|
394
417
|
}
|
|
@@ -423,13 +446,17 @@ export interface GainSourceTotals {
|
|
|
423
446
|
reductionPercent: number | null;
|
|
424
447
|
}
|
|
425
448
|
|
|
426
|
-
/**
|
|
427
|
-
|
|
449
|
+
/**
|
|
450
|
+
* Per-source breakdown: `snapcompact` is tool results snapcompact sent as images,
|
|
451
|
+
* `compaction` is the context snapcompact compactions freed.
|
|
452
|
+
*/
|
|
453
|
+
export type GainSource = "snapcompact" | "compaction";
|
|
428
454
|
|
|
429
455
|
/** Time-series point for gain (daily bucket). */
|
|
430
456
|
export interface GainTimeSeriesPoint {
|
|
431
457
|
date: string;
|
|
432
458
|
snapcompact: number;
|
|
459
|
+
compaction?: number;
|
|
433
460
|
total: number;
|
|
434
461
|
}
|
|
435
462
|
|
|
@@ -461,7 +488,7 @@ export interface SpotlightToolRow extends SpotlightToolTotals {
|
|
|
461
488
|
|
|
462
489
|
/**
|
|
463
490
|
* How the model got back output a shortened result hid:
|
|
464
|
-
* - `artifact`: a later call read or searched
|
|
491
|
+
* - `artifact`: a later call read or searched a spill the shortened result named (`local://N.log`, or `artifact://N` in older transcripts);
|
|
465
492
|
* - `reread`: a later `read` of the same file whose selection overlaps the hidden lines, or the whole file again;
|
|
466
493
|
* - `rerun`: a later call of the same tool repeating the shortened one: a bash command with a pipe, redirect or
|
|
467
494
|
* changed flags; any other tool with near-identical arguments (same tool, argument tokens' Jaccard ≥ 0.6).
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Classification of the model calls stored in `messages`, for attributing usage.
|
|
3
|
+
*
|
|
4
|
+
* - A **turn** is an assistant message (stored with a NULL purpose), or the
|
|
5
|
+
* billed usage of a discarded assistant turn, which the session journals as
|
|
6
|
+
* a `model_usage` entry with purpose `discarded-turn`.
|
|
7
|
+
* - A **side channel** is every other `model_usage` entry: a model call that
|
|
8
|
+
* is not part of the conversation (title generation, job captions, judge
|
|
9
|
+
* queries, …). Its category groups the purposes of one use case.
|
|
10
|
+
* - A side channel runs on a **decision model** when its api answers
|
|
11
|
+
* judgments natively instead of generating text.
|
|
12
|
+
*
|
|
13
|
+
* The purposes are written by the coding agent, which stats never imports, so
|
|
14
|
+
* the table lives here. Rows and rollups store the raw purpose and api and
|
|
15
|
+
* everything below is derived at read time: the table applies to entries
|
|
16
|
+
* already ingested and can be re-cut without re-ingesting.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { isJudgmentApi } from "@linxiraos/pi-ai";
|
|
20
|
+
|
|
21
|
+
/** Purpose of the `model_usage` entry carrying the billed usage of a discarded assistant turn. */
|
|
22
|
+
const DISCARDED_TURN_PURPOSE = "discarded-turn";
|
|
23
|
+
|
|
24
|
+
/** Side-channel categories and the purposes each covers. A purpose listed nowhere is its own category. */
|
|
25
|
+
const SIDE_CHANNEL_CATEGORIES: Record<string, readonly string[]> = {
|
|
26
|
+
title: ["title", "title-fork", "title-drift"],
|
|
27
|
+
progress: ["job-widget", "job-caption", "task-completion-probe"],
|
|
28
|
+
judge: ["judge", "judge_batch"],
|
|
29
|
+
find: ["find"],
|
|
30
|
+
thinking: ["auto-thinking"],
|
|
31
|
+
visualization: ["auto-graph"],
|
|
32
|
+
workflow: ["auto-prewalk", "auto-parallel", "unexpected-stop"],
|
|
33
|
+
memory: ["memory", "memory-relevance"],
|
|
34
|
+
rules: ["ttsr"],
|
|
35
|
+
composer: ["composer-prediction"],
|
|
36
|
+
cache: ["cache-warm"],
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const CATEGORY_BY_PURPOSE = new Map<string, string>();
|
|
40
|
+
for (const category in SIDE_CHANNEL_CATEGORIES) {
|
|
41
|
+
for (const purpose of SIDE_CHANNEL_CATEGORIES[category]) CATEGORY_BY_PURPOSE.set(purpose, category);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Side-channel category of a row from its stored `purpose`, or `null` when the
|
|
46
|
+
* row is a turn. A `:detail` suffix belongs to its base purpose
|
|
47
|
+
* (`cache-warm:extension-override` is `cache-warm`).
|
|
48
|
+
*/
|
|
49
|
+
export function sideChannelCategory(purpose: string | null): string | null {
|
|
50
|
+
if (purpose === null) return null;
|
|
51
|
+
const detail = purpose.indexOf(":");
|
|
52
|
+
const base = detail > 0 ? purpose.slice(0, detail) : purpose;
|
|
53
|
+
if (base === DISCARDED_TURN_PURPOSE) return null;
|
|
54
|
+
return CATEGORY_BY_PURPOSE.get(base) ?? base;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Whether a side-channel row with this stored `api` ran on a decision model.
|
|
59
|
+
* Decided by the api alone, never by model or provider ids.
|
|
60
|
+
*/
|
|
61
|
+
export function isDecisionModelApi(api: string): boolean {
|
|
62
|
+
return isJudgmentApi(api);
|
|
63
|
+
}
|
package/src/spotlight-ingest.ts
CHANGED
|
@@ -15,7 +15,15 @@
|
|
|
15
15
|
|
|
16
16
|
import * as fs from "node:fs/promises";
|
|
17
17
|
import * as path from "node:path";
|
|
18
|
-
import {
|
|
18
|
+
import {
|
|
19
|
+
getSessionsDir,
|
|
20
|
+
isEnoent,
|
|
21
|
+
isRecord,
|
|
22
|
+
parseSpillUrl,
|
|
23
|
+
spillFileName,
|
|
24
|
+
spillUrl,
|
|
25
|
+
spillUrlIds,
|
|
26
|
+
} from "@linxiraos/pi-utils";
|
|
19
27
|
|
|
20
28
|
/**
|
|
21
29
|
* Whether a custom entry marks its session as a Spotlight experiment session: pi's `spotlight:session` entry, which
|
|
@@ -110,7 +118,10 @@ export interface SpotlightShapeRow {
|
|
|
110
118
|
gated: boolean;
|
|
111
119
|
/** `details.spotlight.original` (present only when shaping changed the text). */
|
|
112
120
|
original: SpotlightOriginalFacts | null;
|
|
113
|
-
/**
|
|
121
|
+
/**
|
|
122
|
+
* Artifact ids the result names (its text's spill URLs, `local://N.log` or legacy `artifact://N`, plus
|
|
123
|
+
* `original.url`); null before the result lands.
|
|
124
|
+
*/
|
|
114
125
|
artifacts: number[] | null;
|
|
115
126
|
/**
|
|
116
127
|
* Spotlight's own usage, from the shape entry; null before it lands. `failureCauses` counts failed calls by cause
|
|
@@ -245,13 +256,16 @@ function finite(value: unknown): number {
|
|
|
245
256
|
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
246
257
|
}
|
|
247
258
|
|
|
248
|
-
|
|
259
|
+
/** Legacy `artifact://N`, the spill URL before spills moved to the `local://` root. */
|
|
260
|
+
const LEGACY_ARTIFACT_RE = /artifact:\/\/(\d+)/g;
|
|
261
|
+
const LEGACY_ARTIFACT_URL_RE = /^artifact:\/\/(\d+)$/;
|
|
249
262
|
|
|
250
|
-
/** Distinct `artifact://N`
|
|
263
|
+
/** Distinct spill ids a text names (`local://N.log`, or `artifact://N` in older transcripts), ascending. */
|
|
251
264
|
export function artifactIds(text: string): number[] {
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
265
|
+
const spills = spillUrlIds(text);
|
|
266
|
+
if (!text.includes("artifact://")) return spills;
|
|
267
|
+
const ids = new Set<number>(spills);
|
|
268
|
+
for (const match of text.matchAll(LEGACY_ARTIFACT_RE)) ids.add(Number(match[1]));
|
|
255
269
|
return [...ids].sort((a, b) => a - b);
|
|
256
270
|
}
|
|
257
271
|
|
|
@@ -352,8 +366,8 @@ function filePaths(values: readonly unknown[]): string[] {
|
|
|
352
366
|
|
|
353
367
|
/**
|
|
354
368
|
* Files a call changes: an `edit`'s patch headers (or its `path`), a `write`'s `path`, an `ast_edit`'s `paths`
|
|
355
|
-
* (globs kept as written)
|
|
356
|
-
*
|
|
369
|
+
* (globs kept as written). Null when the call is no file edit (other tools, or a write to an internal URL such as
|
|
370
|
+
* `proc://…/kill`).
|
|
357
371
|
*/
|
|
358
372
|
export function editedPaths(toolName: string, args: unknown): string[] | null {
|
|
359
373
|
if (!isRecord(args)) return null;
|
|
@@ -367,13 +381,6 @@ export function editedPaths(toolName: string, args: unknown): string[] | null {
|
|
|
367
381
|
} else if (toolName === "ast_edit") {
|
|
368
382
|
paths = filePaths(Array.isArray(args.paths) ? args.paths : [args.path]);
|
|
369
383
|
} else if (toolName === "write") {
|
|
370
|
-
if (args.path === "xd://ast_edit" && typeof args.content === "string") {
|
|
371
|
-
try {
|
|
372
|
-
return editedPaths("ast_edit", JSON.parse(args.content));
|
|
373
|
-
} catch {
|
|
374
|
-
return null;
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
384
|
paths = filePaths([args.path]);
|
|
378
385
|
} else {
|
|
379
386
|
return null;
|
|
@@ -424,10 +431,13 @@ export function selectedLines(selection: ReadSelection): [number, number][] | nu
|
|
|
424
431
|
return selection.ranges.length === 0 && selection.tail === null ? null : selection.ranges;
|
|
425
432
|
}
|
|
426
433
|
|
|
427
|
-
/** A path as written, resolved
|
|
434
|
+
/** A path as written, resolved against the session's working directory (URLs and absolute paths kept). */
|
|
428
435
|
export function resolveReadPath(target: string, cwd: string | null): string {
|
|
429
|
-
if (URL_SCHEME.test(target)
|
|
430
|
-
|
|
436
|
+
if (URL_SCHEME.test(target)) return target;
|
|
437
|
+
// Absolute paths still go through `path.resolve`: on Windows a POSIX-spelled
|
|
438
|
+
// `/repo/src/a.ts` and a relative `src/a.ts` under `/repo` must compare equal.
|
|
439
|
+
if (path.isAbsolute(target)) return path.resolve(target);
|
|
440
|
+
return cwd ? path.resolve(cwd, target) : target;
|
|
431
441
|
}
|
|
432
442
|
|
|
433
443
|
/** One `*** Find` block of an `edit` input and the file its section edits (null: the call's `path`). */
|
|
@@ -717,8 +727,8 @@ export function shapeFromDetails(
|
|
|
717
727
|
}
|
|
718
728
|
|
|
719
729
|
/**
|
|
720
|
-
* Directories a session's artifacts can live in: its own (`<session
|
|
721
|
-
* (`<parent>/<name>.jsonl`), its parent's and further ancestors' up to the project folder.
|
|
730
|
+
* Directories a session's artifacts can live in: its own (`<session>/`, spills under its `local/`), else, for a
|
|
731
|
+
* subagent transcript (`<parent>/<name>.jsonl`), its parent's and further ancestors' up to the project folder.
|
|
722
732
|
*/
|
|
723
733
|
function artifactDirs(sessionFile: string): string[] {
|
|
724
734
|
const dirs = [sessionFile.replace(/\.jsonl$/, "")];
|
|
@@ -732,13 +742,29 @@ function artifactDirs(sessionFile: string): string[] {
|
|
|
732
742
|
return dirs;
|
|
733
743
|
}
|
|
734
744
|
|
|
735
|
-
/**
|
|
745
|
+
/**
|
|
746
|
+
* The lines of spill `url` of a session: `local://N.log` (file `local/N.log`) or, in older transcripts,
|
|
747
|
+
* `artifact://N` (file `N.*`); null when it cannot be found or read.
|
|
748
|
+
*/
|
|
736
749
|
async function readArtifactLines(
|
|
737
750
|
sessionFile: string,
|
|
738
751
|
url: string,
|
|
739
752
|
listings: Map<string, Promise<string[]>>,
|
|
740
753
|
): Promise<string[] | null> {
|
|
741
|
-
const
|
|
754
|
+
const spill = parseSpillUrl(url);
|
|
755
|
+
if (spill !== undefined) {
|
|
756
|
+
// A bare URL only: an original names its whole spill, never a selector into it.
|
|
757
|
+
if (url !== spillUrl(spill)) return null;
|
|
758
|
+
for (const dir of artifactDirs(sessionFile)) {
|
|
759
|
+
try {
|
|
760
|
+
return (await Bun.file(path.join(dir, "local", spillFileName(spill))).text()).split("\n");
|
|
761
|
+
} catch (err) {
|
|
762
|
+
if (!isEnoent(err)) return null;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
return null;
|
|
766
|
+
}
|
|
767
|
+
const id = LEGACY_ARTIFACT_URL_RE.exec(url)?.[1];
|
|
742
768
|
if (id === undefined) return null;
|
|
743
769
|
for (const dir of artifactDirs(sessionFile)) {
|
|
744
770
|
let listing = listings.get(dir);
|
package/src/types.ts
CHANGED
|
@@ -35,6 +35,16 @@ export interface MessageStats {
|
|
|
35
35
|
usage: Usage;
|
|
36
36
|
/** Which agent produced this message (main agent, task subagent, advisor) */
|
|
37
37
|
agentType: AgentType;
|
|
38
|
+
/**
|
|
39
|
+
* Raw `purpose` of the `model_usage` entry this row was journaled from (a
|
|
40
|
+
* model call that is not a conversation turn: title generation, judge
|
|
41
|
+
* queries, …), `:detail` suffix included; `null` for an assistant message.
|
|
42
|
+
* Non-null is what marks a row as off-transcript, so the parser always gives
|
|
43
|
+
* such a row a value. Always written by `rowToMessageStats`; optional because
|
|
44
|
+
* the parser omits it for assistant messages and session fixtures that stand
|
|
45
|
+
* in for ingest input are typed as `MessageStats` too.
|
|
46
|
+
*/
|
|
47
|
+
purpose?: string | null;
|
|
38
48
|
/**
|
|
39
49
|
* Service tier the provider reported serving this turn, or `null` when the
|
|
40
50
|
* provider reported none. Lets consumers separate a fast serving path's
|
|
@@ -71,7 +81,11 @@ export interface MessageStatsInput extends Omit<MessageStats, "usage" | "costUnp
|
|
|
71
81
|
export interface RequestDetails extends MessageStats {
|
|
72
82
|
/** The full conversation history or just the last turn. */
|
|
73
83
|
messages: unknown[];
|
|
74
|
-
/**
|
|
84
|
+
/**
|
|
85
|
+
* The model's response. For a `model_usage` entry, the payload it journaled:
|
|
86
|
+
* the reply text of a completion, else a judgment's answers by question id,
|
|
87
|
+
* else `null`.
|
|
88
|
+
*/
|
|
75
89
|
output: unknown;
|
|
76
90
|
}
|
|
77
91
|
|
|
@@ -116,6 +130,14 @@ export interface SessionModelUsageEntry {
|
|
|
116
130
|
usage: Usage;
|
|
117
131
|
stopReason?: StopReason;
|
|
118
132
|
errorMessage?: string;
|
|
133
|
+
/** Wall time of the request in milliseconds; absent on older entries. */
|
|
134
|
+
duration?: number;
|
|
135
|
+
/** Milliseconds until the first token; absent on older entries. */
|
|
136
|
+
ttft?: number;
|
|
137
|
+
/** What a native judge query answered, by question id; absent on older entries. */
|
|
138
|
+
judgment?: { state: string; answers: Record<string, number | [string | number, number]>; cached?: number };
|
|
139
|
+
/** What a text side channel (title generation) was sent and replied; absent on older entries. */
|
|
140
|
+
completion?: { prompt?: string; reply?: string };
|
|
119
141
|
}
|
|
120
142
|
|
|
121
143
|
/**
|
|
@@ -301,3 +323,16 @@ export interface ToolResultLink {
|
|
|
301
323
|
resultChars: number;
|
|
302
324
|
isError: boolean;
|
|
303
325
|
}
|
|
326
|
+
|
|
327
|
+
/** One snapcompact compaction entry: the context size the session's estimate measured before and after it. */
|
|
328
|
+
export interface SnapcompactCompactionStats {
|
|
329
|
+
sessionFile: string;
|
|
330
|
+
/** Compaction entry ID */
|
|
331
|
+
entryId: string;
|
|
332
|
+
/** Folder/project path (extracted from session filename) */
|
|
333
|
+
folder: string;
|
|
334
|
+
/** Compaction timestamp (Unix ms) */
|
|
335
|
+
timestamp: number;
|
|
336
|
+
tokensBefore: number;
|
|
337
|
+
tokensAfter: number;
|
|
338
|
+
}
|