@dudousxd/nestjs-agent-dashboard 0.4.1 → 0.5.0
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/dist/client/agent-client.d.ts +54 -0
- package/dist/client/agent-client.d.ts.map +1 -1
- package/dist/client/agent-client.js +9 -0
- package/dist/client/agent-client.js.map +1 -1
- package/dist/client/error-breakdown.d.ts +9 -0
- package/dist/client/error-breakdown.d.ts.map +1 -0
- package/dist/client/error-breakdown.js +20 -0
- package/dist/client/error-breakdown.js.map +1 -0
- package/dist/client/format-usd.d.ts +2 -0
- package/dist/client/format-usd.d.ts.map +1 -1
- package/dist/client/format-usd.js +13 -0
- package/dist/client/format-usd.js.map +1 -1
- package/dist/client/run-trend-path.d.ts +30 -0
- package/dist/client/run-trend-path.d.ts.map +1 -0
- package/dist/client/run-trend-path.js +36 -0
- package/dist/client/run-trend-path.js.map +1 -0
- package/dist/server/index.cjs +47 -0
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +17 -2
- package/dist/server/index.d.ts +17 -2
- package/dist/server/index.js +47 -0
- package/dist/server/index.js.map +1 -1
- package/dist/spa/assets/index-BiQzj2IF.js +49 -0
- package/dist/spa/assets/index-C-8Bnj9D.css +1 -0
- package/dist/spa/assets/index-CHzfsa2R.js +1 -0
- package/dist/spa/assets/preview-Dh9sCp0L.js +1 -0
- package/dist/spa/index.html +3 -3
- package/dist/spa/preview.html +3 -3
- package/package.json +2 -2
- package/dist/spa/assets/index-BHFHKR8b.css +0 -1
- package/dist/spa/assets/index-DPCmjbDB.js +0 -1
- package/dist/spa/assets/index-DXmRzl_c.js +0 -49
- package/dist/spa/assets/preview-BQeQWTP5.js +0 -1
|
@@ -57,6 +57,56 @@ export interface ThreadActivityRow {
|
|
|
57
57
|
/** Human-readable label resolved from `actorRef` (an `ActorDirectory`), when one is bound server-side. */
|
|
58
58
|
actorLabel: string | null;
|
|
59
59
|
}
|
|
60
|
+
/** Aggregated run reliability over a range. */
|
|
61
|
+
export interface RunMetrics {
|
|
62
|
+
runs: number;
|
|
63
|
+
completed: number;
|
|
64
|
+
failed: number;
|
|
65
|
+
/** completed / runs, 0 when runs = 0. */
|
|
66
|
+
successRate: number;
|
|
67
|
+
/** Total llm-step retries across the range's runs. */
|
|
68
|
+
retries: number;
|
|
69
|
+
durationP50Ms: number | null;
|
|
70
|
+
durationP95Ms: number | null;
|
|
71
|
+
}
|
|
72
|
+
/** Run/failure counts for one agent over a range. */
|
|
73
|
+
export interface RunAgentBreakdownRow {
|
|
74
|
+
agentName: string;
|
|
75
|
+
runs: number;
|
|
76
|
+
failed: number;
|
|
77
|
+
retries: number;
|
|
78
|
+
}
|
|
79
|
+
/** Failure count for one error code over a range. */
|
|
80
|
+
export interface RunErrorBreakdownRow {
|
|
81
|
+
errorCode: string;
|
|
82
|
+
count: number;
|
|
83
|
+
}
|
|
84
|
+
/** One point on the daily run/failure trend. */
|
|
85
|
+
export interface RunTrendPoint {
|
|
86
|
+
day: string;
|
|
87
|
+
runs: number;
|
|
88
|
+
failed: number;
|
|
89
|
+
}
|
|
90
|
+
/** A recent run for the Reliability recent-runs table. */
|
|
91
|
+
export interface RecentRunRow {
|
|
92
|
+
runId: string;
|
|
93
|
+
threadId: string;
|
|
94
|
+
actorRef: string;
|
|
95
|
+
agentName: string | null;
|
|
96
|
+
status: string;
|
|
97
|
+
durationMs: number | null;
|
|
98
|
+
errorCode: string | null;
|
|
99
|
+
errorMessage: string | null;
|
|
100
|
+
retries: number;
|
|
101
|
+
startedAt: string;
|
|
102
|
+
}
|
|
103
|
+
/** The `GET <api>/reliability` response. */
|
|
104
|
+
export interface ReliabilityOverview {
|
|
105
|
+
metrics: RunMetrics;
|
|
106
|
+
byAgent: RunAgentBreakdownRow[];
|
|
107
|
+
errors: RunErrorBreakdownRow[];
|
|
108
|
+
trend: RunTrendPoint[];
|
|
109
|
+
}
|
|
60
110
|
/** A model's current per-1M-token price (the pricing tab's row shape). */
|
|
61
111
|
export interface ModelPrice {
|
|
62
112
|
modelId: string;
|
|
@@ -99,6 +149,10 @@ export declare const agentClient: {
|
|
|
99
149
|
spend(range: GovernanceRange): Promise<SpendOverview>;
|
|
100
150
|
/** Top threads by cost for a day range (default 10). */
|
|
101
151
|
topThreads(range: GovernanceRange, limit?: number): Promise<ThreadSpendRow[]>;
|
|
152
|
+
/** Run reliability for a day range: `{ metrics, byAgent, errors, trend }`. */
|
|
153
|
+
reliability(range: GovernanceRange): Promise<ReliabilityOverview>;
|
|
154
|
+
/** Most recent runs (default 50). */
|
|
155
|
+
runs(limit?: number): Promise<RecentRunRow[]>;
|
|
102
156
|
/** Most recent tool calls (default 50). */
|
|
103
157
|
toolCalls(limit?: number): Promise<ToolCallActivityRow[]>;
|
|
104
158
|
/** Most recent threads (default 50). */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-client.d.ts","sourceRoot":"","sources":["../../src/client/agent-client.ts"],"names":[],"mappings":"AAIA,kDAAkD;AAClD,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,uDAAuD;AACvD,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,0EAA0E;AAC1E,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,0GAA0G;IAC1G,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AAED,wDAAwD;AACxD,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAA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AC,cAAc,EAAE,CAAC;IAIzE,8EAA8E;uBAC3D,eAAe,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAIjE,qCAAqC;0BACnB,OAAO,CAAC,YAAY,EAAE,CAAC;IAGzC,2CAA2C;+BACpB,OAAO,CAAC,mBAAmB,EAAE,CAAC;IAGrD,wCAAwC;6BACnB,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAGjD,gFAAgF;eACrE,OAAO,CAAC,UAAU,EAAE,CAAC;IAGhC,gFAAgF;uBACvD,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ9D;;;OAGG;0BACmB,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,GAAG,MAAM,IAAI;CAWnE,CAAC"}
|
|
@@ -24,6 +24,15 @@ export const agentClient = {
|
|
|
24
24
|
const q = new URLSearchParams({ from: range.fromDay, to: range.toDay, limit: `${limit}` });
|
|
25
25
|
return http(`/top-threads?${q.toString()}`);
|
|
26
26
|
},
|
|
27
|
+
/** Run reliability for a day range: `{ metrics, byAgent, errors, trend }`. */
|
|
28
|
+
reliability(range) {
|
|
29
|
+
const q = new URLSearchParams({ from: range.fromDay, to: range.toDay });
|
|
30
|
+
return http(`/reliability?${q.toString()}`);
|
|
31
|
+
},
|
|
32
|
+
/** Most recent runs (default 50). */
|
|
33
|
+
runs(limit = 50) {
|
|
34
|
+
return http(`/runs?limit=${limit}`);
|
|
35
|
+
},
|
|
27
36
|
/** Most recent tool calls (default 50). */
|
|
28
37
|
toolCalls(limit = 50) {
|
|
29
38
|
return http(`/tool-calls?limit=${limit}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-client.js","sourceRoot":"","sources":["../../src/client/agent-client.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,uGAAuG;AACvG,gFAAgF;
|
|
1
|
+
{"version":3,"file":"agent-client.js","sourceRoot":"","sources":["../../src/client/agent-client.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,uGAAuG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CAAC;QACtD,MAAM,CAAC,SAAS,GAAG,CAAC,GAAG,EAAE,EAAE;YACzB,IAAI,CAAC;gBACH,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAmB,CAAC,CAAC;YAClD,CAAC;YAAC,MAAM,CAAC;gBACP,4BAA4B;YAC9B,CAAC;QACH,CAAC,CAAC;QACF,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IAC9B,CAAC;CACF,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { RunErrorBreakdownRow } from './agent-client';
|
|
2
|
+
import type { DonutSegment } from './spend-summary';
|
|
3
|
+
/**
|
|
4
|
+
* Build donut segments from an error-code breakdown, reusing the spend donut's `DonutSegment` shape
|
|
5
|
+
* (its `modelId` field carries the `errorCode` here — the `Donut` component only ever treats it as an
|
|
6
|
+
* opaque segment key/label). Sorted by count descending; zero-count rows are dropped.
|
|
7
|
+
*/
|
|
8
|
+
export declare function errorSegments(rows: RunErrorBreakdownRow[]): DonutSegment[];
|
|
9
|
+
//# sourceMappingURL=error-breakdown.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-breakdown.d.ts","sourceRoot":"","sources":["../../src/client/error-breakdown.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEpD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,oBAAoB,EAAE,GAAG,YAAY,EAAE,CAY1E"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build donut segments from an error-code breakdown, reusing the spend donut's `DonutSegment` shape
|
|
3
|
+
* (its `modelId` field carries the `errorCode` here — the `Donut` component only ever treats it as an
|
|
4
|
+
* opaque segment key/label). Sorted by count descending; zero-count rows are dropped.
|
|
5
|
+
*/
|
|
6
|
+
export function errorSegments(rows) {
|
|
7
|
+
const total = rows.reduce((sum, row) => sum + row.count, 0);
|
|
8
|
+
const sorted = [...rows].sort((a, b) => b.count - a.count);
|
|
9
|
+
const segments = [];
|
|
10
|
+
let offset = 0;
|
|
11
|
+
for (const row of sorted) {
|
|
12
|
+
if (total <= 0 || row.count <= 0)
|
|
13
|
+
continue;
|
|
14
|
+
const fraction = row.count / total;
|
|
15
|
+
segments.push({ modelId: row.errorCode, value: row.count, fraction, offset });
|
|
16
|
+
offset += fraction;
|
|
17
|
+
}
|
|
18
|
+
return segments;
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=error-breakdown.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-breakdown.js","sourceRoot":"","sources":["../../src/client/error-breakdown.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,IAA4B;IACxD,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IAC5D,MAAM,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;IAC3D,MAAM,QAAQ,GAAmB,EAAE,CAAC;IACpC,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;QACzB,IAAI,KAAK,IAAI,CAAC,IAAI,GAAG,CAAC,KAAK,IAAI,CAAC;YAAE,SAAS;QAC3C,MAAM,QAAQ,GAAG,GAAG,CAAC,KAAK,GAAG,KAAK,CAAC;QACnC,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,GAAG,CAAC,SAAS,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;QAC9E,MAAM,IAAI,QAAQ,CAAC;IACrB,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
|
|
@@ -5,4 +5,6 @@ export declare function formatUsd(amount: number): string;
|
|
|
5
5
|
export declare function formatCount(value: number): string;
|
|
6
6
|
/** Format a 0..1 ratio as an integer percent (`0.1234` -> `12%`). */
|
|
7
7
|
export declare function formatPercent(ratio: number): string;
|
|
8
|
+
/** Format a duration in ms (`420ms`, `1.8s`, `2m 5s`); `null`/non-finite reads as `—` (no data). */
|
|
9
|
+
export declare function formatDurationMs(ms: number | null): string;
|
|
8
10
|
//# sourceMappingURL=format-usd.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format-usd.d.ts","sourceRoot":"","sources":["../../src/client/format-usd.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAE/E,oGAAoG;AACpG,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAOhD;AAED,2EAA2E;AAC3E,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOjD;AAED,qEAAqE;AACrE,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAGnD"}
|
|
1
|
+
{"version":3,"file":"format-usd.d.ts","sourceRoot":"","sources":["../../src/client/format-usd.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAE/E,oGAAoG;AACpG,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAOhD;AAED,2EAA2E;AAC3E,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOjD;AAED,qEAAqE;AACrE,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAGnD;AAED,oGAAoG;AACpG,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAQ1D"}
|
|
@@ -31,4 +31,17 @@ export function formatPercent(ratio) {
|
|
|
31
31
|
return '0%';
|
|
32
32
|
return `${Math.round(ratio * 100)}%`;
|
|
33
33
|
}
|
|
34
|
+
/** Format a duration in ms (`420ms`, `1.8s`, `2m 5s`); `null`/non-finite reads as `—` (no data). */
|
|
35
|
+
export function formatDurationMs(ms) {
|
|
36
|
+
if (ms === null || !Number.isFinite(ms))
|
|
37
|
+
return '—';
|
|
38
|
+
const abs = Math.abs(ms);
|
|
39
|
+
if (abs < 1000)
|
|
40
|
+
return `${Math.round(ms)}ms`;
|
|
41
|
+
if (abs < 60_000)
|
|
42
|
+
return `${(ms / 1000).toFixed(1)}s`;
|
|
43
|
+
const minutes = Math.floor(abs / 60_000);
|
|
44
|
+
const seconds = Math.round((abs % 60_000) / 1000);
|
|
45
|
+
return `${minutes}m ${seconds}s`;
|
|
46
|
+
}
|
|
34
47
|
//# sourceMappingURL=format-usd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format-usd.js","sourceRoot":"","sources":["../../src/client/format-usd.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAE/E,oGAAoG;AACpG,MAAM,UAAU,SAAS,CAAC,MAAc;IACtC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,OAAO,CAAC;IAC7C,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC7B,IAAI,GAAG,IAAI,SAAS;QAAE,OAAO,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;IACpE,IAAI,GAAG,IAAI,KAAK;QAAE,OAAO,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;IAC5D,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,I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AK,CAAC,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC;AACvC,CAAC;AAED,oGAAoG;AACpG,MAAM,UAAU,gBAAgB,CAAC,EAAiB;IAChD,IAAI,EAAE,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;QAAE,OAAO,GAAG,CAAC;IACpD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IACzB,IAAI,GAAG,GAAG,IAAI;QAAE,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,CAAC;IAC7C,IAAI,GAAG,GAAG,MAAM;QAAE,OAAO,GAAG,CAAC,EAAE,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;IACtD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,MAAM,CAAC,CAAC;IACzC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;IAClD,OAAO,GAAG,OAAO,KAAK,OAAO,GAAG,CAAC;AACnC,CAAC"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { RunTrendPoint } from './agent-client';
|
|
2
|
+
/** A plotted day, carrying both series' y-coordinates so a chart can draw them overlaid. */
|
|
3
|
+
export interface RunTrendVertex {
|
|
4
|
+
day: string;
|
|
5
|
+
runs: number;
|
|
6
|
+
failed: number;
|
|
7
|
+
x: number;
|
|
8
|
+
runsY: number;
|
|
9
|
+
failedY: number;
|
|
10
|
+
}
|
|
11
|
+
/** Everything an SVG needs to draw the run/failure trend inside `width`x`height`. */
|
|
12
|
+
export interface RunTrendGeometry {
|
|
13
|
+
/** `M..L..` polyline through the `runs` series (empty when there is nothing to plot). */
|
|
14
|
+
runsLine: string;
|
|
15
|
+
/** Closed area path (runs line + baseline) for a filled gradient; empty when nothing to plot. */
|
|
16
|
+
runsArea: string;
|
|
17
|
+
/** `M..L..` polyline through the `failed` series (empty when there is nothing to plot). */
|
|
18
|
+
failedLine: string;
|
|
19
|
+
vertices: RunTrendVertex[];
|
|
20
|
+
/** The shared series max used to normalize the y-axis (never 0 — floored to 1). */
|
|
21
|
+
max: number;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Project the daily run/failure trend into SVG geometry. Mirrors `buildTrendGeometry`'s x-spread/
|
|
25
|
+
* single-point/empty-series rules, but plots TWO series (`runs`, `failed`) against ONE shared y-axis
|
|
26
|
+
* scale — so the failed line reads as a fraction of the runs line, not its own independent scale.
|
|
27
|
+
* Pure — no DOM.
|
|
28
|
+
*/
|
|
29
|
+
export declare function buildRunTrendGeometry(points: RunTrendPoint[], width: number, height: number): RunTrendGeometry;
|
|
30
|
+
//# sourceMappingURL=run-trend-path.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-trend-path.d.ts","sourceRoot":"","sources":["../../src/client/run-trend-path.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD,4FAA4F;AAC5F,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,CAAC,EAAE,MAAM,CAAC;IACV,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,qFAAqF;AACrF,MAAM,WAAW,gBAAgB;IAC/B,yFAAyF;IACzF,QAAQ,EAAE,MAAM,CAAC;IACjB,iGAAiG;IACjG,QAAQ,EAAE,MAAM,CAAC;IACjB,2FAA2F;IAC3F,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,cAAc,EAAE,CAAC;IAC3B,mFAAmF;IACnF,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,aAAa,EAAE,EACvB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,GACb,gBAAgB,CAwClB"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project the daily run/failure trend into SVG geometry. Mirrors `buildTrendGeometry`'s x-spread/
|
|
3
|
+
* single-point/empty-series rules, but plots TWO series (`runs`, `failed`) against ONE shared y-axis
|
|
4
|
+
* scale — so the failed line reads as a fraction of the runs line, not its own independent scale.
|
|
5
|
+
* Pure — no DOM.
|
|
6
|
+
*/
|
|
7
|
+
export function buildRunTrendGeometry(points, width, height) {
|
|
8
|
+
if (points.length === 0) {
|
|
9
|
+
return { runsLine: '', runsArea: '', failedLine: '', vertices: [], max: 1 };
|
|
10
|
+
}
|
|
11
|
+
const max = Math.max(1, ...points.map((point) => point.runs), ...points.map((point) => point.failed));
|
|
12
|
+
const lastIndex = Math.max(1, points.length - 1);
|
|
13
|
+
const vertices = points.map((point, index) => ({
|
|
14
|
+
day: point.day,
|
|
15
|
+
runs: point.runs,
|
|
16
|
+
failed: point.failed,
|
|
17
|
+
x: points.length === 1 ? width / 2 : (index / lastIndex) * width,
|
|
18
|
+
runsY: height - (point.runs / max) * height,
|
|
19
|
+
failedY: height - (point.failed / max) * height,
|
|
20
|
+
}));
|
|
21
|
+
const polyline = (pickY) => vertices
|
|
22
|
+
.map((vertex, index) => `${index === 0 ? 'M' : 'L'}${vertex.x.toFixed(2)},${pickY(vertex).toFixed(2)}`)
|
|
23
|
+
.join(' ');
|
|
24
|
+
const runsLine = polyline((vertex) => vertex.runsY);
|
|
25
|
+
const firstX = vertices[0]?.x ?? 0;
|
|
26
|
+
const lastX = vertices[vertices.length - 1]?.x ?? width;
|
|
27
|
+
const runsArea = `${runsLine} L${lastX.toFixed(2)},${height} L${firstX.toFixed(2)},${height} Z`;
|
|
28
|
+
return {
|
|
29
|
+
runsLine,
|
|
30
|
+
runsArea,
|
|
31
|
+
failedLine: polyline((vertex) => vertex.failedY),
|
|
32
|
+
vertices,
|
|
33
|
+
max,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=run-trend-path.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-trend-path.js","sourceRoot":"","sources":["../../src/client/run-trend-path.ts"],"names":[],"mappings":"AAyBA;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CACnC,MAAuB,EACvB,KAAa,EACb,MAAc;IAEd,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxB,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,UAAU,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC;IAC9E,CAAC;IAED,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAClB,CAAC,EACD,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,EACpC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CACvC,CAAC;IACF,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACjD,MAAM,QAAQ,GAAqB,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;QAC/D,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,CAAC,EAAE,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,SAAS,CAAC,GAAG,KAAK;QAChE,K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ows = await this.queries.spendByThread(range, limit);
|
|
156
156
|
return this.withActorLabels(rows);
|
|
157
157
|
}
|
|
158
|
+
/** Run reliability for a day range: metrics, by-agent/by-error breakdowns and the trend, in parallel. */
|
|
159
|
+
async reliability(range) {
|
|
160
|
+
const [metrics, byAgent, errors, trend] = await Promise.all([
|
|
161
|
+
this.queries.runMetrics(range),
|
|
162
|
+
this.queries.runsByAgent(range),
|
|
163
|
+
this.queries.runErrors(range),
|
|
164
|
+
this.queries.runTrend(range)
|
|
165
|
+
]);
|
|
166
|
+
return {
|
|
167
|
+
metrics,
|
|
168
|
+
byAgent,
|
|
169
|
+
errors,
|
|
170
|
+
trend
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/** Most recent runs (status/agent/duration/error) for the Reliability recent-runs table. */
|
|
174
|
+
recentRuns(limit) {
|
|
175
|
+
return this.queries.recentRuns(limit);
|
|
176
|
+
}
|
|
158
177
|
/** Most recent tool calls (status/type/thread) for the Runs & tools activity feed. */
|
|
159
178
|
recentToolCalls(limit) {
|
|
160
179
|
return this.queries.recentToolCalls(limit);
|
|
@@ -309,6 +328,14 @@ var AgentApiController = class {
|
|
|
309
328
|
topThreads(from, to, limit) {
|
|
310
329
|
return this.dashboard.topThreads(resolveRange(from, to), parseLimit(limit, 10));
|
|
311
330
|
}
|
|
331
|
+
/** `{ metrics, byAgent, errors, trend }` for a day range (defaults to the last 30 days). */
|
|
332
|
+
reliability(from, to) {
|
|
333
|
+
return this.dashboard.reliability(resolveRange(from, to));
|
|
334
|
+
}
|
|
335
|
+
/** Most recent runs (default 50, max 200) for the Reliability recent-runs table. */
|
|
336
|
+
runs(limit) {
|
|
337
|
+
return this.dashboard.recentRuns(parseLimit(limit, 50));
|
|
338
|
+
}
|
|
312
339
|
/** Most recent tool calls (default 50, max 200) for the activity feed. */
|
|
313
340
|
toolCalls(limit) {
|
|
314
341
|
return this.dashboard.recentToolCalls(parseLimit(limit, 50));
|
|
@@ -361,6 +388,26 @@ _ts_decorate2([
|
|
|
361
388
|
]),
|
|
362
389
|
_ts_metadata2("design:returntype", typeof Promise === "undefined" ? Object : Promise)
|
|
363
390
|
], AgentApiController.prototype, "topThreads", null);
|
|
391
|
+
_ts_decorate2([
|
|
392
|
+
(0, import_common3.Get)("reliability"),
|
|
393
|
+
_ts_param2(0, (0, import_common3.Query)("from")),
|
|
394
|
+
_ts_param2(1, (0, import_common3.Query)("to")),
|
|
395
|
+
_ts_metadata2("design:type", Function),
|
|
396
|
+
_ts_metadata2("design:paramtypes", [
|
|
397
|
+
String,
|
|
398
|
+
String
|
|
399
|
+
]),
|
|
400
|
+
_ts_metadata2("design:returntype", typeof Promise === "undefined" ? Object : Promise)
|
|
401
|
+
], AgentApiController.prototype, "reliability", null);
|
|
402
|
+
_ts_decorate2([
|
|
403
|
+
(0, import_common3.Get)("runs"),
|
|
404
|
+
_ts_param2(0, (0, import_common3.Query)("limit")),
|
|
405
|
+
_ts_metadata2("design:type", Function),
|
|
406
|
+
_ts_metadata2("design:paramtypes", [
|
|
407
|
+
String
|
|
408
|
+
]),
|
|
409
|
+
_ts_metadata2("design:returntype", typeof Promise === "undefined" ? Object : Promise)
|
|
410
|
+
], AgentApiController.prototype, "runs", null);
|
|
364
411
|
_ts_decorate2([
|
|
365
412
|
(0, import_common3.Get)("tool-calls"),
|
|
366
413
|
_ts_param2(0, (0, import_common3.Query)("limit")),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/index.ts","../../src/server/agent-api.controller.ts","../../src/server/dashboard.service.ts","../../src/server/parse-price-input.ts","../../src/server/tokens.ts","../../src/server/normalize-path.ts","../../src/server/agent-dashboard-mount-paths.ts","../../src/server/agent-dashboard.module.ts","../../src/server/agent-ui.controller.ts"],"sourcesContent":["export * from './actor-directory.js';\nexport * from './agent-api.controller.js';\nexport * from './agent-dashboard-mount-paths.js';\nexport * from './agent-dashboard.module.js';\nexport * from './agent-ui.controller.js';\nexport * from './dashboard.service.js';\nexport * from './parse-price-input.js';\nexport * from './tokens.js';\n","import type { CurrentModelPrice, ToolCallActivityRow } from '@dudousxd/nestjs-agent-core';\nimport { Body, Controller, Get, Post, Query, Sse } from '@nestjs/common';\nimport type { Observable } from 'rxjs';\nimport {\n DashboardService,\n type LiveAgentEvent,\n type SpendOverview,\n type ThreadActivityRowWithLabel,\n type ThreadSpendRowWithLabel,\n} from './dashboard.service.js';\n\nconst DAY_MS = 86_400_000;\nconst ISO_DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/** A `YYYY-MM-DD` UTC day string `daysAgo` days before now (0 = today). */\nfunction utcDay(daysAgo: number): string {\n return new Date(Date.now() - daysAgo * DAY_MS).toISOString().slice(0, 10);\n}\n\n/** Accept a client-supplied `YYYY-MM-DD`, or fall back to `fallback`; guards against junk input. */\nfunction dayOr(value: string | undefined, fallback: string): string {\n return value !== undefined && ISO_DAY.test(value) ? value : fallback;\n}\n\n/** Resolve the `from`/`to` query params into a validated range, defaulting to the last 30 days. */\nfunction resolveRange(\n from: string | undefined,\n to: string | undefined,\n): {\n fromDay: string;\n toDay: string;\n} {\n return { fromDay: dayOr(from, utcDay(29)), toDay: dayOr(to, utcDay(0)) };\n}\n\n/** Parse a `limit` query param, clamped to a sane window; falls back to `fallback` when absent/junk. */\nfunction parseLimit(value: string | undefined, fallback: number): number {\n const parsed = value === undefined ? Number.NaN : Number.parseInt(value, 10);\n if (!Number.isFinite(parsed)) return fallback;\n return Math.max(1, Math.min(200, parsed));\n}\n\n/**\n * JSON + SSE API consumed by the AI-gateway console SPA. Mounted at `apiBasePath` (set by\n * `RouterModule` in {@link AgentDashboardModule.forRoot}), so the controller routes are relative.\n */\n@Controller()\nexport class AgentApiController {\n constructor(private readonly dashboard: DashboardService) {}\n\n /** `{ byModel, byActor, trend }` for a day range (defaults to the last 30 days). */\n @Get('spend')\n spend(@Query('from') from?: string, @Query('to') to?: string): Promise<SpendOverview> {\n return this.dashboard.spend(resolveRange(from, to));\n }\n\n /** Top threads by cost (default 10, max 200) for a day range (defaults to the last 30 days). */\n @Get('top-threads')\n topThreads(\n @Query('from') from?: string,\n @Query('to') to?: string,\n @Query('limit') limit?: string,\n ): Promise<ThreadSpendRowWithLabel[]> {\n return this.dashboard.topThreads(resolveRange(from, to), parseLimit(limit, 10));\n }\n\n /** Most recent tool calls (default 50, max 200) for the activity feed. */\n @Get('tool-calls')\n toolCalls(@Query('limit') limit?: string): Promise<ToolCallActivityRow[]> {\n return this.dashboard.recentToolCalls(parseLimit(limit, 50));\n }\n\n /** Most recent threads (default 50, max 200) with rolled-up counts. */\n @Get('threads')\n threads(@Query('limit') limit?: string): Promise<ThreadActivityRowWithLabel[]> {\n return this.dashboard.recentThreads(parseLimit(limit, 50));\n }\n\n /**\n * Current price row per model, for the pricing tab. 501s (via `DashboardService.listPrices`) when\n * no `AGENT_PRICING_STORE` is bound.\n */\n @Get('pricing')\n listPrices(): Promise<CurrentModelPrice[]> {\n return this.dashboard.listPrices();\n }\n\n /**\n * Set a model's current price. Body shape mirrors core's `ModelPriceInput`\n * (`{ modelId, inputPricePer1m, outputPricePer1m, cacheWritePricePer1m?, cacheReadPricePer1m? }`).\n * 501s when no `AGENT_PRICING_STORE` is bound; 400s on a malformed body.\n */\n @Post('pricing')\n upsertPrice(@Body() body: unknown): Promise<void> {\n return this.dashboard.upsertPrice(body);\n }\n\n /** Server-Sent Events stream of live `aviary:agent:*` events — the Live feed tails it. */\n @Sse('stream')\n stream(): Observable<{ data: LiveAgentEvent }> {\n return this.dashboard.streamEvents();\n }\n}\n","import { subscribe, unsubscribe } from 'node:diagnostics_channel';\nimport type {\n ActorSpendRow,\n AgentGovernanceQueries,\n AgentPricingStore,\n CurrentModelPrice,\n GovernanceRange,\n ModelSpendRow,\n ThreadActivityRow,\n ThreadSpendRow,\n ToolCallActivityRow,\n UsageTrendPoint,\n} from '@dudousxd/nestjs-agent-core';\nimport { channelName } from '@dudousxd/nestjs-diagnostics';\nimport { Inject, Injectable, NotImplementedException, Optional } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport type { ActorDirectory } from './actor-directory.js';\nimport { parsePriceInput } from './parse-price-input.js';\nimport { AGENT_ACTOR_DIRECTORY, AGENT_GOVERNANCE_QUERIES, AGENT_PRICING_STORE } from './tokens.js';\n\n/** An actor-scoped row decorated with its resolved display label — `null` when unbound or unresolved. */\nexport interface WithActorLabel {\n actorLabel: string | null;\n}\n\nexport type ActorSpendRowWithLabel = ActorSpendRow & WithActorLabel;\nexport type ThreadSpendRowWithLabel = ThreadSpendRow & WithActorLabel;\nexport type ThreadActivityRowWithLabel = ThreadActivityRow & WithActorLabel;\n\n/** The spend/usage overview the SPA renders on its headline section (`GET <api>/spend`). */\nexport interface SpendOverview {\n byModel: ModelSpendRow[];\n byActor: ActorSpendRowWithLabel[];\n trend: UsageTrendPoint[];\n}\n\n/** The message returned as a 501 when no `AGENT_PRICING_STORE` is bound. */\nconst PRICING_STORE_UNBOUND_MESSAGE =\n 'Pricing CRUD is unavailable: no AGENT_PRICING_STORE is bound. Bind a pricing store (e.g. ' +\n 'MikroOrmPricingStore from @dudousxd/nestjs-agent-store-mikro-orm) to enable it.';\n\n/** One live agent event forwarded over SSE, flattened from the `aviary:agent:*` diagnostics envelope. */\nexport interface LiveAgentEvent {\n /** The event name, e.g. `run.started` / `tool-call` / `quota.exceeded`. */\n event: string;\n /** Epoch millis the event was emitted. */\n ts: number;\n /** The library-defined payload (see the `Agent*Event` shapes in core's diagnostics). */\n payload: Record<string, unknown>;\n}\n\n/** The `aviary:agent:*` events the Live feed tails. Mirrors the telescope watcher's subscription. */\nconst AGENT_EVENTS = [\n 'run.started',\n 'message',\n 'tool-call',\n 'quota.exceeded',\n 'run.finished',\n 'delegated',\n] as const;\n\n/** The `node:diagnostics_channel` envelope `emit()` publishes (see `@dudousxd/nestjs-diagnostics`). */\ninterface AgentDiagnosticEnvelope {\n event: string;\n ts?: number;\n payload?: Record<string, unknown>;\n}\n\n/** Narrow the untyped diagnostics-channel message to the envelope we forward. */\nfunction isAgentEnvelope(message: unknown): message is AgentDiagnosticEnvelope {\n return (\n typeof message === 'object' &&\n message !== null &&\n 'event' in message &&\n typeof (message as { event: unknown }).event === 'string'\n );\n}\n\n/**\n * Read-model + live bridge backing the AI-gateway console.\n *\n * - Historical, restart-surviving spend/usage/threads come from the injected\n * {@link AGENT_GOVERNANCE_QUERIES} read-model (backed by a store adapter). The host must provide\n * that token — bind it via your `@dudousxd/nestjs-agent` module (global) alongside this dashboard.\n * - Live activity comes off the `aviary:agent:*` diagnostics channel, subscribed per SSE client and\n * unsubscribed when the client disconnects.\n * - `actorLabel` on actor-scoped rows comes from the OPTIONAL {@link AGENT_ACTOR_DIRECTORY} — `null`\n * on every row when nothing is bound, so the console degrades to raw `actorRef`s instead of failing.\n * - Pricing CRUD (`listPrices`/`upsertPrice`) reads/writes the OPTIONAL {@link AGENT_PRICING_STORE} —\n * a 501 with a clear message when nothing is bound.\n */\n@Injectable()\nexport class DashboardService {\n constructor(\n @Inject(AGENT_GOVERNANCE_QUERIES) private readonly queries: AgentGovernanceQueries,\n @Optional()\n @Inject(AGENT_ACTOR_DIRECTORY)\n private readonly actorDirectory?: ActorDirectory,\n @Optional()\n @Inject(AGENT_PRICING_STORE)\n private readonly pricingStore?: AgentPricingStore,\n ) {}\n\n /** Spend/usage overview for a day range: by-model + by-actor spend and the daily trend, in parallel. */\n async spend(range: GovernanceRange): Promise<SpendOverview> {\n const [byModel, byActorRaw, trend] = await Promise.all([\n this.queries.spendByModel(range),\n this.queries.spendByActor(range),\n this.queries.usageTrend(range),\n ]);\n const byActor = await this.withActorLabels(byActorRaw);\n return { byModel, byActor, trend };\n }\n\n /** Top threads by cost for a day range (default 10, highest cost first). */\n async topThreads(range: GovernanceRange, limit = 10): Promise<ThreadSpendRowWithLabel[]> {\n const rows = await this.queries.spendByThread(range, limit);\n return this.withActorLabels(rows);\n }\n\n /** Most recent tool calls (status/type/thread) for the Runs & tools activity feed. */\n recentToolCalls(limit: number): Promise<ToolCallActivityRow[]> {\n return this.queries.recentToolCalls(limit);\n }\n\n /** Most recent threads with rolled-up message/token counts. */\n async recentThreads(limit: number): Promise<ThreadActivityRowWithLabel[]> {\n const rows = await this.queries.recentThreads(limit);\n return this.withActorLabels(rows);\n }\n\n /**\n * Decorate actor-scoped rows with `actorLabel`, batching the distinct `actorRef`s into ONE\n * {@link ActorDirectory.resolveDisplay} call per response. `null` for every row when no directory\n * is bound, or for a ref the directory didn't resolve.\n */\n private async withActorLabels<Row extends { actorRef: string }>(\n rows: Row[],\n ): Promise<(Row & WithActorLabel)[]> {\n if (rows.length === 0) {\n return [];\n }\n if (this.actorDirectory === undefined) {\n return rows.map((row) => ({ ...row, actorLabel: null }));\n }\n const refs = [...new Set(rows.map((row) => row.actorRef))];\n const resolved = await this.actorDirectory.resolveDisplay(refs);\n return rows.map((row) => ({ ...row, actorLabel: resolved[row.actorRef] ?? null }));\n }\n\n /** Current price row per model, for the pricing tab. 501s when no `AGENT_PRICING_STORE` is bound. */\n async listPrices(): Promise<CurrentModelPrice[]> {\n if (this.pricingStore === undefined) {\n throw new NotImplementedException(PRICING_STORE_UNBOUND_MESSAGE);\n }\n return this.pricingStore.listCurrentPrices();\n }\n\n /**\n * Set a model's current price (`POST <api>/pricing` body). 501s when no `AGENT_PRICING_STORE` is\n * bound (checked BEFORE body validation, so an unbound store always reports as unimplemented rather\n * than as a validation error); otherwise the body is minimally validated via {@link parsePriceInput}.\n */\n async upsertPrice(body: unknown): Promise<void> {\n if (this.pricingStore === undefined) {\n throw new NotImplementedException(PRICING_STORE_UNBOUND_MESSAGE);\n }\n await this.pricingStore.upsertModelPrice(parsePriceInput(body));\n }\n\n /**\n * Live SSE stream of `aviary:agent:*` diagnostics events. One subscription per SSE client:\n * subscribing wires a handler onto each agent channel; the returned teardown removes them all when\n * the client disconnects (or the observable is otherwise unsubscribed).\n */\n streamEvents(): Observable<{ data: LiveAgentEvent }> {\n return new Observable<{ data: LiveAgentEvent }>((subscriber) => {\n const bindings = AGENT_EVENTS.map((event) => {\n const name = channelName('agent', event);\n const handler = (message: unknown): void => {\n if (!isAgentEnvelope(message)) return;\n subscriber.next({\n data: {\n event: message.event,\n ts: message.ts ?? Date.now(),\n payload: message.payload ?? {},\n },\n });\n };\n subscribe(name, handler);\n return { name, handler };\n });\n return () => {\n for (const binding of bindings) unsubscribe(binding.name, binding.handler);\n };\n });\n }\n}\n","import type { ModelPriceInput } from '@dudousxd/nestjs-agent-core';\nimport { BadRequestException } from '@nestjs/common';\n\n/**\n * Minimal shape guard for a `POST <api>/pricing` body — rejects junk before it reaches\n * `AgentPricingStore.upsertModelPrice`. Not a full schema validator (the store adapter owns real\n * constraints, e.g. uniqueness); this only checks the wire shape core's `ModelPriceInput` requires.\n */\nexport function parsePriceInput(body: unknown): ModelPriceInput {\n if (typeof body !== 'object' || body === null) {\n throw new BadRequestException('Expected a JSON object body.');\n }\n const { modelId, inputPricePer1m, outputPricePer1m, cacheWritePricePer1m, cacheReadPricePer1m } =\n body as Record<string, unknown>;\n\n if (typeof modelId !== 'string' || modelId.trim().length === 0) {\n throw new BadRequestException('\"modelId\" must be a non-empty string.');\n }\n if (!isFiniteNonNegative(inputPricePer1m)) {\n throw new BadRequestException('\"inputPricePer1m\" must be a non-negative number.');\n }\n if (!isFiniteNonNegative(outputPricePer1m)) {\n throw new BadRequestException('\"outputPricePer1m\" must be a non-negative number.');\n }\n if (cacheWritePricePer1m !== undefined && !isFiniteNonNegative(cacheWritePricePer1m)) {\n throw new BadRequestException(\n '\"cacheWritePricePer1m\" must be a non-negative number when present.',\n );\n }\n if (cacheReadPricePer1m !== undefined && !isFiniteNonNegative(cacheReadPricePer1m)) {\n throw new BadRequestException(\n '\"cacheReadPricePer1m\" must be a non-negative number when present.',\n );\n }\n\n return {\n modelId,\n inputPricePer1m,\n outputPricePer1m,\n ...(cacheWritePricePer1m !== undefined ? { cacheWritePricePer1m } : {}),\n ...(cacheReadPricePer1m !== undefined ? { cacheReadPricePer1m } : {}),\n };\n}\n\nfunction isFiniteNonNegative(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0;\n}\n","/**\n * DI tokens for the standalone AI-gateway dashboard.\n *\n * All use `Symbol.for(...)` (the global symbol registry) on purpose: pnpm peer multiplexing + dual\n * ESM/CJS can load a package more than once, and a plain `Symbol()` would mint a distinct token per\n * copy and break DI across the ESM/CJS split. A registered symbol collapses every copy onto the same\n * token.\n */\n\n/**\n * The governance read-model, owned by `@dudousxd/nestjs-agent-core`. We re-declare it here BY VALUE\n * (not by import) so DI does not depend on a runtime value-import of core resolving — `Symbol.for`\n * with the identical key resolves to the SAME symbol instance as core's own\n * `packages/core/src/tokens.ts` export. The key MUST stay byte-identical with that export.\n */\nexport const AGENT_GOVERNANCE_QUERIES = Symbol.for('@dudousxd/nestjs-agent:governance-queries');\n\n/**\n * Optional actor→label resolver (see {@link ActorDirectory} in `./actor-directory.js`), owned by\n * `@dudousxd/nestjs-agent-core`. Re-declared here BY VALUE for the same reason as\n * {@link AGENT_GOVERNANCE_QUERIES} above — the key MUST stay byte-identical with core's own\n * `AGENT_ACTOR_DIRECTORY` export so both copies collapse onto the same registered symbol. Optional:\n * the dashboard works with actorRef-only rows when nothing is bound.\n */\nexport const AGENT_ACTOR_DIRECTORY = Symbol.for('@dudousxd/nestjs-agent:actor-directory');\n\n/**\n * The pricing WRITE side (`AgentPricingStore`), owned by `@dudousxd/nestjs-agent-core`. Re-declared\n * here BY VALUE for the same reason as {@link AGENT_GOVERNANCE_QUERIES} above. Optional: the pricing\n * tab/endpoints 501 with a clear message when nothing is bound.\n */\nexport const AGENT_PRICING_STORE = Symbol.for('@dudousxd/nestjs-agent:pricing-store');\n\n/** DI token carrying the UI mount base (e.g. `/ai-gateway`). */\nexport const DASHBOARD_BASE_PATH = Symbol.for('@dudousxd/nestjs-agent-dashboard:base-path');\n\n/** DI token carrying the JSON API base the SPA fetches from (e.g. `/ai-gateway/api`). */\nexport const DASHBOARD_API_PATH = Symbol.for('@dudousxd/nestjs-agent-dashboard:api-path');\n","/**\n * Leading slash, no trailing slash (`'ai-gateway/'` -> `'/ai-gateway'`). Shared by\n * {@link AgentDashboardModule.forRoot} and {@link agentDashboardMountPaths} so the mount-path math\n * behind the module and the pure helper that mirrors it can never drift apart.\n */\nexport function normalizeDashboardPath(path: string): string {\n return `/${path.replace(/^\\/+|\\/+$/g, '')}`;\n}\n","import { normalizeDashboardPath } from './normalize-path.js';\n\n/** Same shape {@link AgentDashboardModule.forRoot} accepts — kept local so this stays a pure, DI-free helper. */\nexport interface AgentDashboardMountPathsOptions {\n basePath?: string;\n apiBasePath?: string;\n}\n\n/** Strip the leading slash `normalizeDashboardPath` adds — `setGlobalPrefix`'s `exclude` roots are unprefixed. */\nfunction unprefixed(path: string): string {\n return path.replace(/^\\/+/, '');\n}\n\n/**\n * Route roots a host must EXCLUDE from a global prefix (`setGlobalPrefix('api', { exclude })`) so\n * the AI-gateway dashboard's SPA and JSON API keep resolving at their configured mount paths instead\n * of being shifted under the prefix.\n *\n * Unlike a single-surface dashboard (e.g. `telescopeMountPaths()`), this one mounts TWO route roots —\n * the UI at `basePath` and its JSON API at `apiBasePath` — so excluding only one leaves the other\n * shadowed. `options` mirrors {@link AgentDashboardOptions} and resolves through the exact same\n * defaulting (`apiBasePath` falls back to `<basePath>/api`) as {@link AgentDashboardModule.forRoot},\n * so the excluded roots always agree with what actually got mounted.\n *\n * @example\n * ```ts\n * // Raw defaults (basePath `/ai-gateway`, apiBasePath `/ai-gateway/api`):\n * app.setGlobalPrefix('api', { exclude: agentDashboardMountPaths() });\n * // -> ['ai-gateway', 'ai-gateway/{*splat}', 'ai-gateway/api', 'ai-gateway/api/{*splat}']\n *\n * // The recommended pattern — apiBasePath nested under the app's own `/api` prefix — MUST pass the\n * // same options given to `forRoot(...)`:\n * const dashboardOptions = { apiBasePath: '/api/ai-gateway' };\n * app.setGlobalPrefix('api', { exclude: agentDashboardMountPaths(dashboardOptions) });\n * // -> ['ai-gateway', 'ai-gateway/{*splat}', 'api/ai-gateway', 'api/ai-gateway/{*splat}']\n * ```\n */\nexport function agentDashboardMountPaths(options?: AgentDashboardMountPathsOptions): string[] {\n const basePath = normalizeDashboardPath(options?.basePath ?? '/ai-gateway');\n const apiBasePath = normalizeDashboardPath(options?.apiBasePath ?? `${basePath}/api`);\n const base = unprefixed(basePath);\n const api = unprefixed(apiBasePath);\n return [base, `${base}/{*splat}`, api, `${api}/{*splat}`];\n}\n","import 'reflect-metadata';\nimport { type CanActivate, type DynamicModule, Module, type Type } from '@nestjs/common';\nimport { RouterModule } from '@nestjs/core';\nimport { AgentApiController } from './agent-api.controller.js';\nimport { AgentUiController } from './agent-ui.controller.js';\nimport { DashboardService } from './dashboard.service.js';\nimport { normalizeDashboardPath } from './normalize-path.js';\nimport { DASHBOARD_API_PATH, DASHBOARD_BASE_PATH } from './tokens.js';\n\n/**\n * `@nestjs/common`'s own `GUARDS_METADATA` key, INLINED rather than deep-imported from\n * '@nestjs/common/constants' — that subpath has no extension and a strict ESM resolver (which the\n * built dual ESM/CJS output of this package is loaded under) 404s on it. A drift spec imports the\n * real constant (via the resolvable `'@nestjs/common/constants.js'` subpath) and asserts this literal\n * stays byte-identical to it.\n */\nconst GUARDS_METADATA = '__guards__';\n\nexport interface AgentDashboardOptions {\n /**\n * Where the SPA (UI) is served. Default `/ai-gateway`. This is a page route — keep it out of an\n * `/api` prefix so it reads as a UI, not an endpoint.\n */\n basePath?: string;\n /**\n * Where the JSON API is mounted (what the SPA fetches). Default `<basePath>/api`. Set it under\n * your app's `/api` prefix — e.g. `/api/ai-gateway` — so the API inherits the app's auth/proxy\n * rules while the UI stays at `basePath`.\n */\n apiBasePath?: string;\n /**\n * Guard classes fronting BOTH dashboard controllers (the SPA at `basePath` and its JSON API at\n * `apiBasePath`). Stamped onto each controller via `@nestjs/common`'s own `@UseGuards` metadata key\n * — REPLACE semantics, so a second `forRoot(...)` call overwrites (not appends to) whatever a prior\n * call stamped, same as re-applying `@UseGuards` by hand. Omit to leave the routes unguarded (the\n * host fronts them another way, e.g. a global guard or reverse-proxy auth).\n *\n * A guard's own DEPENDENCIES resolve from this module's `imports` (see {@link imports}) — the\n * dashboard module has no application context of its own to pull them from otherwise.\n */\n guards?: Type<CanActivate>[];\n /**\n * Extra `imports` merged into the dashboard's dynamic module — the DI resolution path for a class\n * passed to {@link guards} (or any other provider the controllers need reachable). Typically the\n * host's own auth module, e.g. `imports: [AuthModule]` alongside `guards: [JwtAuthGuard]`.\n */\n imports?: DynamicModule['imports'];\n}\n\n/** Leading slash, no trailing slash. */\nfunction normalize(path: string): string {\n return normalizeDashboardPath(path);\n}\n\n/** Stamp (or clear) `@UseGuards`-equivalent metadata on the dashboard controllers — REPLACE, not append. */\nfunction stampGuards(guards: Type<CanActivate>[] | undefined, ...controllers: Type[]): void {\n for (const controller of controllers) {\n Reflect.defineMetadata(GUARDS_METADATA, guards ?? [], controller);\n }\n}\n\n/**\n * Holds the JSON API + SSE controller and its read service, mounted on its own path by `forRoot`.\n * Dynamic: guards are DI-instantiated by the CONTROLLER's host module, so this module — not the\n * outer wrapper — must carry the guard classes as providers plus the host's `imports` that resolve\n * their dependencies. A static module here made `guards: [SomeGuardWithDeps]` fail at boot with\n * \"Nest can't resolve dependencies ... in the AgentApiModule context\" even when the host passed\n * the right `imports` to `forRoot`.\n */\n@Module({})\nexport class AgentApiModule {\n static register(options: {\n imports?: DynamicModule['imports'];\n guards?: Type<CanActivate>[];\n }): DynamicModule {\n return {\n module: AgentApiModule,\n imports: [...(options.imports ?? [])],\n controllers: [AgentApiController],\n providers: [DashboardService, ...(options.guards ?? [])],\n exports: [DashboardService],\n };\n }\n}\n\n/**\n * Mounts the AI-gateway governance console: the bundled React SPA at `basePath` and its JSON + SSE\n * API at `apiBasePath` (default `<basePath>/api`).\n *\n * Import via `AgentDashboardModule.forRoot(...)` alongside your `@dudousxd/nestjs-agent` module\n * (global), which must provide `AGENT_GOVERNANCE_QUERIES` (bound by a store adapter). Front the\n * routes with the first-class `guards` option (plus `imports` for the guards' own dependencies) —\n * see {@link AgentDashboardOptions.guards}.\n */\n@Module({})\nexport class AgentDashboardModule {\n static forRoot(options: AgentDashboardOptions = {}): DynamicModule {\n const basePath = normalize(options.basePath ?? '/ai-gateway');\n const apiBasePath = normalize(options.apiBasePath ?? `${basePath}/api`);\n stampGuards(options.guards, AgentApiController, AgentUiController);\n return {\n module: AgentDashboardModule,\n imports: [\n ...(options.imports ?? []),\n // Guards + host imports must reach the API controller's HOST module — enhancers resolve\n // from their controller's own module, never from a parent (see AgentApiModule.register).\n // Spread-only-when-set: exactOptionalPropertyTypes rejects an explicit `undefined`.\n AgentApiModule.register({\n ...(options.imports ? { imports: options.imports } : {}),\n ...(options.guards ? { guards: options.guards } : {}),\n }),\n RouterModule.register([\n { path: basePath, module: AgentDashboardModule }, // the UI controller below\n { path: apiBasePath, module: AgentApiModule },\n ]),\n ],\n controllers: [AgentUiController],\n providers: [\n { provide: DASHBOARD_BASE_PATH, useValue: basePath },\n { provide: DASHBOARD_API_PATH, useValue: apiBasePath },\n // AgentUiController is hosted HERE, so its guards DI-instantiate from this module.\n ...(options.guards ?? []),\n ],\n // Re-export the API module so its DashboardService reaches importers (e.g. the host's own controllers).\n exports: [AgentApiModule],\n };\n }\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { basename, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n Controller,\n Get,\n Header,\n Inject,\n NotFoundException,\n Param,\n StreamableFile,\n} from '@nestjs/common';\nimport { DASHBOARD_API_PATH, DASHBOARD_BASE_PATH } from './tokens.js';\n\n/** The base the SPA bundle was built with (Vite `base`); rewritten to the configured base at serve time. */\nconst BUILD_BASE = '/ai-gateway';\n\n/** dist/server/agent-ui.controller.js -> ../spa (the Vite build output). */\nfunction spaDir(): string {\n return fileURLToPath(new URL('../spa', import.meta.url));\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.json': 'application/json; charset=utf-8',\n '.woff2': 'font/woff2',\n '.ico': 'image/x-icon',\n};\n\n/**\n * Serves the bundled AI-gateway console SPA at the configured base (+ hashed assets at\n * `<base>/assets`). The path comes from `RouterModule` (set by\n * {@link AgentDashboardModule.forRoot}({ basePath })), so the controller routes are relative.\n */\n@Controller()\nexport class AgentUiController {\n private readonly dir = spaDir();\n\n constructor(\n @Inject(DASHBOARD_BASE_PATH) private readonly basePath: string,\n @Inject(DASHBOARD_API_PATH) private readonly apiBasePath: string,\n ) {}\n\n // index.html references hash-named bundles, so it MUST NOT be cached (stale bundle = the classic\n // \"stuck loading after a deploy\"). The hashed assets below are immutable.\n @Get()\n @Header('Content-Type', 'text/html; charset=utf-8')\n @Header('Cache-Control', 'no-store, must-revalidate')\n index(): string {\n const indexPath = join(this.dir, 'index.html');\n if (!existsSync(indexPath)) {\n throw new NotFoundException('Dashboard is not built. Run the package build.');\n }\n // The bundle was built with Vite base `/ai-gateway/`; rewrite asset URLs to the configured base\n // so the SPA loads from `<base>/assets` wherever it's mounted, and tell the client its API base.\n const html = readFileSync(indexPath, 'utf8').replaceAll(\n `=\"${BUILD_BASE}/`,\n `=\"${this.basePath}/`,\n );\n // __AGENT_BASE__ = where assets load; __AGENT_API__ = where the SPA fetches the JSON API.\n const inject = `<script>window.__AGENT_BASE__='${this.basePath}';window.__AGENT_API__='${this.apiBasePath}';</script>`;\n return html.includes('</head>') ? html.replace('</head>', `${inject}</head>`) : inject + html;\n }\n\n @Get('assets/:file')\n @Header('Cache-Control', 'public, max-age=31536000, immutable')\n asset(@Param('file') file: string): StreamableFile {\n const safe = basename(file);\n if (safe !== file) throw new NotFoundException();\n const root = resolve(this.dir, 'assets');\n const assetPath = resolve(root, safe);\n if (!assetPath.startsWith(root + sep) || !existsSync(assetPath)) {\n throw new NotFoundException();\n }\n const type = CONTENT_TYPES[extname(safe)] ?? 'application/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AMM,iBAAN,MAAMA,gBAAAA;SAAAA;;;EACX,OAAOC,SAASC,SAGE;AAChB,WAAO;MACLC,QAAQH;MACRI,SAAS;WAAKF,QAAQE,WAAW,CAAA;;MACjCR,aAAa;QAACS;;MACdC,WAAW;QAACC;WAAsBL,QAAQP,UAAU,CAAA;;MACpDa,SAAS;QAACD;;IACZ;EACF;AACF;;;;AAYO,IAAME,uBAAN,MAAMA,sBAAAA;SAAAA;;;EACX,OAAOC,QAAQR,UAAiC,CAAC,GAAkB;AACjE,UAAMS,WAAWpB,UAAUW,QAAQS,YAAY,aAAA;AAC/C,UAAMC,cAAcrB,UAAUW,QAAQU,eAAe,GAAGD,QAAAA,MAAc;AACtEjB,gBAAYQ,QAAQP,QAAQU,oBAAoBQ,iBAAAA;AAChD,WAAO;MACLV,QAAQM;MACRL,SAAS;WACHF,QAAQE,WAAW,CAAA;;;;QAIvBJ,eAAeC,SAAS;UACtB,GAAIC,QAAQE,UAAU;YAAEA,SAASF,QAAQE;UAAQ,IAAI,CAAC;UACtD,GAAIF,QAAQP,SAAS;YAAEA,QAAQO,QAAQP;UAAO,IAAI,CAAC;QACrD,CAAA;QACAmB,yBAAab,SAAS;UACpB;YAAET,MAAMmB;YAAUR,QAAQM;UAAqB;UAC/C;YAAEjB,MAAMoB;YAAaT,QAAQH;UAAe;SAC7C;;MAEHJ,aAAa;QAACiB;;MACdP,WAAW;QACT;UAAES,SAASC;UAAqBC,UAAUN;QAAS;QACnD;UAAEI,SAASG;UAAoBD,UAAUL;QAAY;;WAEjDV,QAAQP,UAAU,CAAA;;;MAGxBa,SAAS;QAACR;;IACZ;EACF;AACF;;;;","names":["import_common","import_common","parsePriceInput","body","BadRequestException","modelId","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","trim","length","isFiniteNonNegative","undefined","value","Number","isFinite","AGENT_GOVERNANCE_QUERIES","Symbol","for","AGENT_ACTOR_DIRECTORY","AGENT_PRICING_STORE","DASHBOARD_BASE_PATH","DASHBOARD_API_PATH","PRICING_STORE_UNBOUND_MESSAGE","AGENT_EVENTS","isAgentEnvelope","message","event","DashboardService","queries","actorDirectory","pricingStore","spend","range","byModel","byActorRaw","trend","Promise","all","spendByModel","spendByActor","usageTrend","byActor","withActorLabels","topThreads","limit","rows","spendByThread","recentToolCalls","recentThreads","length","undefined","map","row","actorLabel","refs","Set","actorRef","resolved","resolveDisplay","listPrices","NotImplementedException","listCurrentPrices","upsertPrice","body","upsertModelPrice","parsePriceInput","streamEvents","Observable","subscriber","bindings","name","channelName","handler","next","data","ts","Date","now","payload","subscribe","binding","unsubscribe","DAY_MS","ISO_DAY","utcDay","daysAgo","Date","now","toISOString","slice","dayOr","value","fallback","undefined","test","resolveRange","from","to","fromDay","toDay","parseLimit","parsed","Number","NaN","parseInt","isFinite","Math","max","min","AgentApiController","dashboard","spend","topThreads","limit","toolCalls","recentToolCalls","threads","recentThreads","listPrices","upsertPrice","body","stream","streamEvents","normalizeDashboardPath","path","replace","unprefixed","path","replace","agentDashboardMountPaths","options","basePath","normalizeDashboardPath","apiBasePath","base","api","import_common","import_common","BUILD_BASE","spaDir","fileURLToPath","URL","CONTENT_TYPES","AgentUiController","dir","basePath","apiBasePath","index","indexPath","join","existsSync","NotFoundException","html","readFileSync","replaceAll","inject","includes","replace","asset","file","safe","basename","root","resolve","assetPath","startsWith","sep","type","extname","StreamableFile","GUARDS_METADATA","normalize","path","normalizeDashboardPath","stampGuards","guards","controllers","controller","Reflect","defineMetadata","AgentApiModule","register","options","module","imports","AgentApiController","providers","DashboardService","exports","AgentDashboardModule","forRoot","basePath","apiBasePath","AgentUiController","RouterModule","provide","DASHBOARD_BASE_PATH","useValue","DASHBOARD_API_PATH"]}
|
|
1
|
+
{"version":3,"sources":["../../src/server/index.ts","../../src/server/agent-api.controller.ts","../../src/server/dashboard.service.ts","../../src/server/parse-price-input.ts","../../src/server/tokens.ts","../../src/server/normalize-path.ts","../../src/server/agent-dashboard-mount-paths.ts","../../src/server/agent-dashboard.module.ts","../../src/server/agent-ui.controller.ts"],"sourcesContent":["export * from './actor-directory.js';\nexport * from './agent-api.controller.js';\nexport * from './agent-dashboard-mount-paths.js';\nexport * from './agent-dashboard.module.js';\nexport * from './agent-ui.controller.js';\nexport * from './dashboard.service.js';\nexport * from './parse-price-input.js';\nexport * from './tokens.js';\n","import type {\n CurrentModelPrice,\n RecentRunRow,\n ToolCallActivityRow,\n} from '@dudousxd/nestjs-agent-core';\nimport { Body, Controller, Get, Post, Query, Sse } from '@nestjs/common';\nimport type { Observable } from 'rxjs';\nimport {\n DashboardService,\n type LiveAgentEvent,\n type ReliabilityOverview,\n type SpendOverview,\n type ThreadActivityRowWithLabel,\n type ThreadSpendRowWithLabel,\n} from './dashboard.service.js';\n\nconst DAY_MS = 86_400_000;\nconst ISO_DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/** A `YYYY-MM-DD` UTC day string `daysAgo` days before now (0 = today). */\nfunction utcDay(daysAgo: number): string {\n return new Date(Date.now() - daysAgo * DAY_MS).toISOString().slice(0, 10);\n}\n\n/** Accept a client-supplied `YYYY-MM-DD`, or fall back to `fallback`; guards against junk input. */\nfunction dayOr(value: string | undefined, fallback: string): string {\n return value !== undefined && ISO_DAY.test(value) ? value : fallback;\n}\n\n/** Resolve the `from`/`to` query params into a validated range, defaulting to the last 30 days. */\nfunction resolveRange(\n from: string | undefined,\n to: string | undefined,\n): {\n fromDay: string;\n toDay: string;\n} {\n return { fromDay: dayOr(from, utcDay(29)), toDay: dayOr(to, utcDay(0)) };\n}\n\n/** Parse a `limit` query param, clamped to a sane window; falls back to `fallback` when absent/junk. */\nfunction parseLimit(value: string | undefined, fallback: number): number {\n const parsed = value === undefined ? Number.NaN : Number.parseInt(value, 10);\n if (!Number.isFinite(parsed)) return fallback;\n return Math.max(1, Math.min(200, parsed));\n}\n\n/**\n * JSON + SSE API consumed by the AI-gateway console SPA. Mounted at `apiBasePath` (set by\n * `RouterModule` in {@link AgentDashboardModule.forRoot}), so the controller routes are relative.\n */\n@Controller()\nexport class AgentApiController {\n constructor(private readonly dashboard: DashboardService) {}\n\n /** `{ byModel, byActor, trend }` for a day range (defaults to the last 30 days). */\n @Get('spend')\n spend(@Query('from') from?: string, @Query('to') to?: string): Promise<SpendOverview> {\n return this.dashboard.spend(resolveRange(from, to));\n }\n\n /** Top threads by cost (default 10, max 200) for a day range (defaults to the last 30 days). */\n @Get('top-threads')\n topThreads(\n @Query('from') from?: string,\n @Query('to') to?: string,\n @Query('limit') limit?: string,\n ): Promise<ThreadSpendRowWithLabel[]> {\n return this.dashboard.topThreads(resolveRange(from, to), parseLimit(limit, 10));\n }\n\n /** `{ metrics, byAgent, errors, trend }` for a day range (defaults to the last 30 days). */\n @Get('reliability')\n reliability(\n @Query('from') from?: string,\n @Query('to') to?: string,\n ): Promise<ReliabilityOverview> {\n return this.dashboard.reliability(resolveRange(from, to));\n }\n\n /** Most recent runs (default 50, max 200) for the Reliability recent-runs table. */\n @Get('runs')\n runs(@Query('limit') limit?: string): Promise<RecentRunRow[]> {\n return this.dashboard.recentRuns(parseLimit(limit, 50));\n }\n\n /** Most recent tool calls (default 50, max 200) for the activity feed. */\n @Get('tool-calls')\n toolCalls(@Query('limit') limit?: string): Promise<ToolCallActivityRow[]> {\n return this.dashboard.recentToolCalls(parseLimit(limit, 50));\n }\n\n /** Most recent threads (default 50, max 200) with rolled-up counts. */\n @Get('threads')\n threads(@Query('limit') limit?: string): Promise<ThreadActivityRowWithLabel[]> {\n return this.dashboard.recentThreads(parseLimit(limit, 50));\n }\n\n /**\n * Current price row per model, for the pricing tab. 501s (via `DashboardService.listPrices`) when\n * no `AGENT_PRICING_STORE` is bound.\n */\n @Get('pricing')\n listPrices(): Promise<CurrentModelPrice[]> {\n return this.dashboard.listPrices();\n }\n\n /**\n * Set a model's current price. Body shape mirrors core's `ModelPriceInput`\n * (`{ modelId, inputPricePer1m, outputPricePer1m, cacheWritePricePer1m?, cacheReadPricePer1m? }`).\n * 501s when no `AGENT_PRICING_STORE` is bound; 400s on a malformed body.\n */\n @Post('pricing')\n upsertPrice(@Body() body: unknown): Promise<void> {\n return this.dashboard.upsertPrice(body);\n }\n\n /** Server-Sent Events stream of live `aviary:agent:*` events — the Live feed tails it. */\n @Sse('stream')\n stream(): Observable<{ data: LiveAgentEvent }> {\n return this.dashboard.streamEvents();\n }\n}\n","import { subscribe, unsubscribe } from 'node:diagnostics_channel';\nimport type {\n ActorSpendRow,\n AgentGovernanceQueries,\n AgentPricingStore,\n CurrentModelPrice,\n GovernanceRange,\n ModelSpendRow,\n RecentRunRow,\n RunAgentBreakdownRow,\n RunErrorBreakdownRow,\n RunMetrics,\n RunTrendPoint,\n ThreadActivityRow,\n ThreadSpendRow,\n ToolCallActivityRow,\n UsageTrendPoint,\n} from '@dudousxd/nestjs-agent-core';\nimport { channelName } from '@dudousxd/nestjs-diagnostics';\nimport { Inject, Injectable, NotImplementedException, Optional } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport type { ActorDirectory } from './actor-directory.js';\nimport { parsePriceInput } from './parse-price-input.js';\nimport { AGENT_ACTOR_DIRECTORY, AGENT_GOVERNANCE_QUERIES, AGENT_PRICING_STORE } from './tokens.js';\n\n/** An actor-scoped row decorated with its resolved display label — `null` when unbound or unresolved. */\nexport interface WithActorLabel {\n actorLabel: string | null;\n}\n\nexport type ActorSpendRowWithLabel = ActorSpendRow & WithActorLabel;\nexport type ThreadSpendRowWithLabel = ThreadSpendRow & WithActorLabel;\nexport type ThreadActivityRowWithLabel = ThreadActivityRow & WithActorLabel;\n\n/** The spend/usage overview the SPA renders on its headline section (`GET <api>/spend`). */\nexport interface SpendOverview {\n byModel: ModelSpendRow[];\n byActor: ActorSpendRowWithLabel[];\n trend: UsageTrendPoint[];\n}\n\n/** The run-reliability overview the SPA renders on its Reliability section (`GET <api>/reliability`). */\nexport interface ReliabilityOverview {\n metrics: RunMetrics;\n byAgent: RunAgentBreakdownRow[];\n errors: RunErrorBreakdownRow[];\n trend: RunTrendPoint[];\n}\n\n/** The message returned as a 501 when no `AGENT_PRICING_STORE` is bound. */\nconst PRICING_STORE_UNBOUND_MESSAGE =\n 'Pricing CRUD is unavailable: no AGENT_PRICING_STORE is bound. Bind a pricing store (e.g. ' +\n 'MikroOrmPricingStore from @dudousxd/nestjs-agent-store-mikro-orm) to enable it.';\n\n/** One live agent event forwarded over SSE, flattened from the `aviary:agent:*` diagnostics envelope. */\nexport interface LiveAgentEvent {\n /** The event name, e.g. `run.started` / `tool-call` / `quota.exceeded`. */\n event: string;\n /** Epoch millis the event was emitted. */\n ts: number;\n /** The library-defined payload (see the `Agent*Event` shapes in core's diagnostics). */\n payload: Record<string, unknown>;\n}\n\n/** The `aviary:agent:*` events the Live feed tails. Mirrors the telescope watcher's subscription. */\nconst AGENT_EVENTS = [\n 'run.started',\n 'message',\n 'tool-call',\n 'quota.exceeded',\n 'run.finished',\n 'delegated',\n] as const;\n\n/** The `node:diagnostics_channel` envelope `emit()` publishes (see `@dudousxd/nestjs-diagnostics`). */\ninterface AgentDiagnosticEnvelope {\n event: string;\n ts?: number;\n payload?: Record<string, unknown>;\n}\n\n/** Narrow the untyped diagnostics-channel message to the envelope we forward. */\nfunction isAgentEnvelope(message: unknown): message is AgentDiagnosticEnvelope {\n return (\n typeof message === 'object' &&\n message !== null &&\n 'event' in message &&\n typeof (message as { event: unknown }).event === 'string'\n );\n}\n\n/**\n * Read-model + live bridge backing the AI-gateway console.\n *\n * - Historical, restart-surviving spend/usage/threads come from the injected\n * {@link AGENT_GOVERNANCE_QUERIES} read-model (backed by a store adapter). The host must provide\n * that token — bind it via your `@dudousxd/nestjs-agent` module (global) alongside this dashboard.\n * - Live activity comes off the `aviary:agent:*` diagnostics channel, subscribed per SSE client and\n * unsubscribed when the client disconnects.\n * - `actorLabel` on actor-scoped rows comes from the OPTIONAL {@link AGENT_ACTOR_DIRECTORY} — `null`\n * on every row when nothing is bound, so the console degrades to raw `actorRef`s instead of failing.\n * - Pricing CRUD (`listPrices`/`upsertPrice`) reads/writes the OPTIONAL {@link AGENT_PRICING_STORE} —\n * a 501 with a clear message when nothing is bound.\n */\n@Injectable()\nexport class DashboardService {\n constructor(\n @Inject(AGENT_GOVERNANCE_QUERIES) private readonly queries: AgentGovernanceQueries,\n @Optional()\n @Inject(AGENT_ACTOR_DIRECTORY)\n private readonly actorDirectory?: ActorDirectory,\n @Optional()\n @Inject(AGENT_PRICING_STORE)\n private readonly pricingStore?: AgentPricingStore,\n ) {}\n\n /** Spend/usage overview for a day range: by-model + by-actor spend and the daily trend, in parallel. */\n async spend(range: GovernanceRange): Promise<SpendOverview> {\n const [byModel, byActorRaw, trend] = await Promise.all([\n this.queries.spendByModel(range),\n this.queries.spendByActor(range),\n this.queries.usageTrend(range),\n ]);\n const byActor = await this.withActorLabels(byActorRaw);\n return { byModel, byActor, trend };\n }\n\n /** Top threads by cost for a day range (default 10, highest cost first). */\n async topThreads(range: GovernanceRange, limit = 10): Promise<ThreadSpendRowWithLabel[]> {\n const rows = await this.queries.spendByThread(range, limit);\n return this.withActorLabels(rows);\n }\n\n /** Run reliability for a day range: metrics, by-agent/by-error breakdowns and the trend, in parallel. */\n async reliability(range: GovernanceRange): Promise<ReliabilityOverview> {\n const [metrics, byAgent, errors, trend] = await Promise.all([\n this.queries.runMetrics(range),\n this.queries.runsByAgent(range),\n this.queries.runErrors(range),\n this.queries.runTrend(range),\n ]);\n return { metrics, byAgent, errors, trend };\n }\n\n /** Most recent runs (status/agent/duration/error) for the Reliability recent-runs table. */\n recentRuns(limit: number): Promise<RecentRunRow[]> {\n return this.queries.recentRuns(limit);\n }\n\n /** Most recent tool calls (status/type/thread) for the Runs & tools activity feed. */\n recentToolCalls(limit: number): Promise<ToolCallActivityRow[]> {\n return this.queries.recentToolCalls(limit);\n }\n\n /** Most recent threads with rolled-up message/token counts. */\n async recentThreads(limit: number): Promise<ThreadActivityRowWithLabel[]> {\n const rows = await this.queries.recentThreads(limit);\n return this.withActorLabels(rows);\n }\n\n /**\n * Decorate actor-scoped rows with `actorLabel`, batching the distinct `actorRef`s into ONE\n * {@link ActorDirectory.resolveDisplay} call per response. `null` for every row when no directory\n * is bound, or for a ref the directory didn't resolve.\n */\n private async withActorLabels<Row extends { actorRef: string }>(\n rows: Row[],\n ): Promise<(Row & WithActorLabel)[]> {\n if (rows.length === 0) {\n return [];\n }\n if (this.actorDirectory === undefined) {\n return rows.map((row) => ({ ...row, actorLabel: null }));\n }\n const refs = [...new Set(rows.map((row) => row.actorRef))];\n const resolved = await this.actorDirectory.resolveDisplay(refs);\n return rows.map((row) => ({ ...row, actorLabel: resolved[row.actorRef] ?? null }));\n }\n\n /** Current price row per model, for the pricing tab. 501s when no `AGENT_PRICING_STORE` is bound. */\n async listPrices(): Promise<CurrentModelPrice[]> {\n if (this.pricingStore === undefined) {\n throw new NotImplementedException(PRICING_STORE_UNBOUND_MESSAGE);\n }\n return this.pricingStore.listCurrentPrices();\n }\n\n /**\n * Set a model's current price (`POST <api>/pricing` body). 501s when no `AGENT_PRICING_STORE` is\n * bound (checked BEFORE body validation, so an unbound store always reports as unimplemented rather\n * than as a validation error); otherwise the body is minimally validated via {@link parsePriceInput}.\n */\n async upsertPrice(body: unknown): Promise<void> {\n if (this.pricingStore === undefined) {\n throw new NotImplementedException(PRICING_STORE_UNBOUND_MESSAGE);\n }\n await this.pricingStore.upsertModelPrice(parsePriceInput(body));\n }\n\n /**\n * Live SSE stream of `aviary:agent:*` diagnostics events. One subscription per SSE client:\n * subscribing wires a handler onto each agent channel; the returned teardown removes them all when\n * the client disconnects (or the observable is otherwise unsubscribed).\n */\n streamEvents(): Observable<{ data: LiveAgentEvent }> {\n return new Observable<{ data: LiveAgentEvent }>((subscriber) => {\n const bindings = AGENT_EVENTS.map((event) => {\n const name = channelName('agent', event);\n const handler = (message: unknown): void => {\n if (!isAgentEnvelope(message)) return;\n subscriber.next({\n data: {\n event: message.event,\n ts: message.ts ?? Date.now(),\n payload: message.payload ?? {},\n },\n });\n };\n subscribe(name, handler);\n return { name, handler };\n });\n return () => {\n for (const binding of bindings) unsubscribe(binding.name, binding.handler);\n };\n });\n }\n}\n","import type { ModelPriceInput } from '@dudousxd/nestjs-agent-core';\nimport { BadRequestException } from '@nestjs/common';\n\n/**\n * Minimal shape guard for a `POST <api>/pricing` body — rejects junk before it reaches\n * `AgentPricingStore.upsertModelPrice`. Not a full schema validator (the store adapter owns real\n * constraints, e.g. uniqueness); this only checks the wire shape core's `ModelPriceInput` requires.\n */\nexport function parsePriceInput(body: unknown): ModelPriceInput {\n if (typeof body !== 'object' || body === null) {\n throw new BadRequestException('Expected a JSON object body.');\n }\n const { modelId, inputPricePer1m, outputPricePer1m, cacheWritePricePer1m, cacheReadPricePer1m } =\n body as Record<string, unknown>;\n\n if (typeof modelId !== 'string' || modelId.trim().length === 0) {\n throw new BadRequestException('\"modelId\" must be a non-empty string.');\n }\n if (!isFiniteNonNegative(inputPricePer1m)) {\n throw new BadRequestException('\"inputPricePer1m\" must be a non-negative number.');\n }\n if (!isFiniteNonNegative(outputPricePer1m)) {\n throw new BadRequestException('\"outputPricePer1m\" must be a non-negative number.');\n }\n if (cacheWritePricePer1m !== undefined && !isFiniteNonNegative(cacheWritePricePer1m)) {\n throw new BadRequestException(\n '\"cacheWritePricePer1m\" must be a non-negative number when present.',\n );\n }\n if (cacheReadPricePer1m !== undefined && !isFiniteNonNegative(cacheReadPricePer1m)) {\n throw new BadRequestException(\n '\"cacheReadPricePer1m\" must be a non-negative number when present.',\n );\n }\n\n return {\n modelId,\n inputPricePer1m,\n outputPricePer1m,\n ...(cacheWritePricePer1m !== undefined ? { cacheWritePricePer1m } : {}),\n ...(cacheReadPricePer1m !== undefined ? { cacheReadPricePer1m } : {}),\n };\n}\n\nfunction isFiniteNonNegative(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0;\n}\n","/**\n * DI tokens for the standalone AI-gateway dashboard.\n *\n * All use `Symbol.for(...)` (the global symbol registry) on purpose: pnpm peer multiplexing + dual\n * ESM/CJS can load a package more than once, and a plain `Symbol()` would mint a distinct token per\n * copy and break DI across the ESM/CJS split. A registered symbol collapses every copy onto the same\n * token.\n */\n\n/**\n * The governance read-model, owned by `@dudousxd/nestjs-agent-core`. We re-declare it here BY VALUE\n * (not by import) so DI does not depend on a runtime value-import of core resolving — `Symbol.for`\n * with the identical key resolves to the SAME symbol instance as core's own\n * `packages/core/src/tokens.ts` export. The key MUST stay byte-identical with that export.\n */\nexport const AGENT_GOVERNANCE_QUERIES = Symbol.for('@dudousxd/nestjs-agent:governance-queries');\n\n/**\n * Optional actor→label resolver (see {@link ActorDirectory} in `./actor-directory.js`), owned by\n * `@dudousxd/nestjs-agent-core`. Re-declared here BY VALUE for the same reason as\n * {@link AGENT_GOVERNANCE_QUERIES} above — the key MUST stay byte-identical with core's own\n * `AGENT_ACTOR_DIRECTORY` export so both copies collapse onto the same registered symbol. Optional:\n * the dashboard works with actorRef-only rows when nothing is bound.\n */\nexport const AGENT_ACTOR_DIRECTORY = Symbol.for('@dudousxd/nestjs-agent:actor-directory');\n\n/**\n * The pricing WRITE side (`AgentPricingStore`), owned by `@dudousxd/nestjs-agent-core`. Re-declared\n * here BY VALUE for the same reason as {@link AGENT_GOVERNANCE_QUERIES} above. Optional: the pricing\n * tab/endpoints 501 with a clear message when nothing is bound.\n */\nexport const AGENT_PRICING_STORE = Symbol.for('@dudousxd/nestjs-agent:pricing-store');\n\n/** DI token carrying the UI mount base (e.g. `/ai-gateway`). */\nexport const DASHBOARD_BASE_PATH = Symbol.for('@dudousxd/nestjs-agent-dashboard:base-path');\n\n/** DI token carrying the JSON API base the SPA fetches from (e.g. `/ai-gateway/api`). */\nexport const DASHBOARD_API_PATH = Symbol.for('@dudousxd/nestjs-agent-dashboard:api-path');\n","/**\n * Leading slash, no trailing slash (`'ai-gateway/'` -> `'/ai-gateway'`). Shared by\n * {@link AgentDashboardModule.forRoot} and {@link agentDashboardMountPaths} so the mount-path math\n * behind the module and the pure helper that mirrors it can never drift apart.\n */\nexport function normalizeDashboardPath(path: string): string {\n return `/${path.replace(/^\\/+|\\/+$/g, '')}`;\n}\n","import { normalizeDashboardPath } from './normalize-path.js';\n\n/** Same shape {@link AgentDashboardModule.forRoot} accepts — kept local so this stays a pure, DI-free helper. */\nexport interface AgentDashboardMountPathsOptions {\n basePath?: string;\n apiBasePath?: string;\n}\n\n/** Strip the leading slash `normalizeDashboardPath` adds — `setGlobalPrefix`'s `exclude` roots are unprefixed. */\nfunction unprefixed(path: string): string {\n return path.replace(/^\\/+/, '');\n}\n\n/**\n * Route roots a host must EXCLUDE from a global prefix (`setGlobalPrefix('api', { exclude })`) so\n * the AI-gateway dashboard's SPA and JSON API keep resolving at their configured mount paths instead\n * of being shifted under the prefix.\n *\n * Unlike a single-surface dashboard (e.g. `telescopeMountPaths()`), this one mounts TWO route roots —\n * the UI at `basePath` and its JSON API at `apiBasePath` — so excluding only one leaves the other\n * shadowed. `options` mirrors {@link AgentDashboardOptions} and resolves through the exact same\n * defaulting (`apiBasePath` falls back to `<basePath>/api`) as {@link AgentDashboardModule.forRoot},\n * so the excluded roots always agree with what actually got mounted.\n *\n * @example\n * ```ts\n * // Raw defaults (basePath `/ai-gateway`, apiBasePath `/ai-gateway/api`):\n * app.setGlobalPrefix('api', { exclude: agentDashboardMountPaths() });\n * // -> ['ai-gateway', 'ai-gateway/{*splat}', 'ai-gateway/api', 'ai-gateway/api/{*splat}']\n *\n * // The recommended pattern — apiBasePath nested under the app's own `/api` prefix — MUST pass the\n * // same options given to `forRoot(...)`:\n * const dashboardOptions = { apiBasePath: '/api/ai-gateway' };\n * app.setGlobalPrefix('api', { exclude: agentDashboardMountPaths(dashboardOptions) });\n * // -> ['ai-gateway', 'ai-gateway/{*splat}', 'api/ai-gateway', 'api/ai-gateway/{*splat}']\n * ```\n */\nexport function agentDashboardMountPaths(options?: AgentDashboardMountPathsOptions): string[] {\n const basePath = normalizeDashboardPath(options?.basePath ?? '/ai-gateway');\n const apiBasePath = normalizeDashboardPath(options?.apiBasePath ?? `${basePath}/api`);\n const base = unprefixed(basePath);\n const api = unprefixed(apiBasePath);\n return [base, `${base}/{*splat}`, api, `${api}/{*splat}`];\n}\n","import 'reflect-metadata';\nimport { type CanActivate, type DynamicModule, Module, type Type } from '@nestjs/common';\nimport { RouterModule } from '@nestjs/core';\nimport { AgentApiController } from './agent-api.controller.js';\nimport { AgentUiController } from './agent-ui.controller.js';\nimport { DashboardService } from './dashboard.service.js';\nimport { normalizeDashboardPath } from './normalize-path.js';\nimport { DASHBOARD_API_PATH, DASHBOARD_BASE_PATH } from './tokens.js';\n\n/**\n * `@nestjs/common`'s own `GUARDS_METADATA` key, INLINED rather than deep-imported from\n * '@nestjs/common/constants' — that subpath has no extension and a strict ESM resolver (which the\n * built dual ESM/CJS output of this package is loaded under) 404s on it. A drift spec imports the\n * real constant (via the resolvable `'@nestjs/common/constants.js'` subpath) and asserts this literal\n * stays byte-identical to it.\n */\nconst GUARDS_METADATA = '__guards__';\n\nexport interface AgentDashboardOptions {\n /**\n * Where the SPA (UI) is served. Default `/ai-gateway`. This is a page route — keep it out of an\n * `/api` prefix so it reads as a UI, not an endpoint.\n */\n basePath?: string;\n /**\n * Where the JSON API is mounted (what the SPA fetches). Default `<basePath>/api`. Set it under\n * your app's `/api` prefix — e.g. `/api/ai-gateway` — so the API inherits the app's auth/proxy\n * rules while the UI stays at `basePath`.\n */\n apiBasePath?: string;\n /**\n * Guard classes fronting BOTH dashboard controllers (the SPA at `basePath` and its JSON API at\n * `apiBasePath`). Stamped onto each controller via `@nestjs/common`'s own `@UseGuards` metadata key\n * — REPLACE semantics, so a second `forRoot(...)` call overwrites (not appends to) whatever a prior\n * call stamped, same as re-applying `@UseGuards` by hand. Omit to leave the routes unguarded (the\n * host fronts them another way, e.g. a global guard or reverse-proxy auth).\n *\n * A guard's own DEPENDENCIES resolve from this module's `imports` (see {@link imports}) — the\n * dashboard module has no application context of its own to pull them from otherwise.\n */\n guards?: Type<CanActivate>[];\n /**\n * Extra `imports` merged into the dashboard's dynamic module — the DI resolution path for a class\n * passed to {@link guards} (or any other provider the controllers need reachable). Typically the\n * host's own auth module, e.g. `imports: [AuthModule]` alongside `guards: [JwtAuthGuard]`.\n */\n imports?: DynamicModule['imports'];\n}\n\n/** Leading slash, no trailing slash. */\nfunction normalize(path: string): string {\n return normalizeDashboardPath(path);\n}\n\n/** Stamp (or clear) `@UseGuards`-equivalent metadata on the dashboard controllers — REPLACE, not append. */\nfunction stampGuards(guards: Type<CanActivate>[] | undefined, ...controllers: Type[]): void {\n for (const controller of controllers) {\n Reflect.defineMetadata(GUARDS_METADATA, guards ?? [], controller);\n }\n}\n\n/**\n * Holds the JSON API + SSE controller and its read service, mounted on its own path by `forRoot`.\n * Dynamic: guards are DI-instantiated by the CONTROLLER's host module, so this module — not the\n * outer wrapper — must carry the guard classes as providers plus the host's `imports` that resolve\n * their dependencies. A static module here made `guards: [SomeGuardWithDeps]` fail at boot with\n * \"Nest can't resolve dependencies ... in the AgentApiModule context\" even when the host passed\n * the right `imports` to `forRoot`.\n */\n@Module({})\nexport class AgentApiModule {\n static register(options: {\n imports?: DynamicModule['imports'];\n guards?: Type<CanActivate>[];\n }): DynamicModule {\n return {\n module: AgentApiModule,\n imports: [...(options.imports ?? [])],\n controllers: [AgentApiController],\n providers: [DashboardService, ...(options.guards ?? [])],\n exports: [DashboardService],\n };\n }\n}\n\n/**\n * Mounts the AI-gateway governance console: the bundled React SPA at `basePath` and its JSON + SSE\n * API at `apiBasePath` (default `<basePath>/api`).\n *\n * Import via `AgentDashboardModule.forRoot(...)` alongside your `@dudousxd/nestjs-agent` module\n * (global), which must provide `AGENT_GOVERNANCE_QUERIES` (bound by a store adapter). Front the\n * routes with the first-class `guards` option (plus `imports` for the guards' own dependencies) —\n * see {@link AgentDashboardOptions.guards}.\n */\n@Module({})\nexport class AgentDashboardModule {\n static forRoot(options: AgentDashboardOptions = {}): DynamicModule {\n const basePath = normalize(options.basePath ?? '/ai-gateway');\n const apiBasePath = normalize(options.apiBasePath ?? `${basePath}/api`);\n stampGuards(options.guards, AgentApiController, AgentUiController);\n return {\n module: AgentDashboardModule,\n imports: [\n ...(options.imports ?? []),\n // Guards + host imports must reach the API controller's HOST module — enhancers resolve\n // from their controller's own module, never from a parent (see AgentApiModule.register).\n // Spread-only-when-set: exactOptionalPropertyTypes rejects an explicit `undefined`.\n AgentApiModule.register({\n ...(options.imports ? { imports: options.imports } : {}),\n ...(options.guards ? { guards: options.guards } : {}),\n }),\n RouterModule.register([\n { path: basePath, module: AgentDashboardModule }, // the UI controller below\n { path: apiBasePath, module: AgentApiModule },\n ]),\n ],\n controllers: [AgentUiController],\n providers: [\n { provide: DASHBOARD_BASE_PATH, useValue: basePath },\n { provide: DASHBOARD_API_PATH, useValue: apiBasePath },\n // AgentUiController is hosted HERE, so its guards DI-instantiate from this module.\n ...(options.guards ?? []),\n ],\n // Re-export the API module so its DashboardService reaches importers (e.g. the host's own controllers).\n exports: [AgentApiModule],\n };\n }\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { basename, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n Controller,\n Get,\n Header,\n Inject,\n NotFoundException,\n Param,\n StreamableFile,\n} from '@nestjs/common';\nimport { DASHBOARD_API_PATH, DASHBOARD_BASE_PATH } from './tokens.js';\n\n/** The base the SPA bundle was built with (Vite `base`); rewritten to the configured base at serve time. */\nconst BUILD_BASE = '/ai-gateway';\n\n/** dist/server/agent-ui.controller.js -> ../spa (the Vite build output). */\nfunction spaDir(): string {\n return fileURLToPath(new URL('../spa', import.meta.url));\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.json': 'application/json; charset=utf-8',\n '.woff2': 'font/woff2',\n '.ico': 'image/x-icon',\n};\n\n/**\n * Serves the bundled AI-gateway console SPA at the configured base (+ hashed assets at\n * `<base>/assets`). The path comes from `RouterModule` (set by\n * {@link AgentDashboardModule.forRoot}({ basePath })), so the controller routes are relative.\n */\n@Controller()\nexport class AgentUiController {\n private readonly dir = spaDir();\n\n constructor(\n @Inject(DASHBOARD_BASE_PATH) private readonly basePath: string,\n @Inject(DASHBOARD_API_PATH) private readonly apiBasePath: string,\n ) {}\n\n // index.html references hash-named bundles, so it MUST NOT be cached (stale bundle = the classic\n // \"stuck loading after a deploy\"). The hashed assets below are immutable.\n @Get()\n @Header('Content-Type', 'text/html; charset=utf-8')\n @Header('Cache-Control', 'no-store, must-revalidate')\n index(): string {\n const indexPath = join(this.dir, 'index.html');\n if (!existsSync(indexPath)) {\n throw new NotFoundException('Dashboard is not built. Run the package build.');\n }\n // The bundle was built with Vite base `/ai-gateway/`; rewrite asset URLs to the configured base\n // so the SPA loads from `<base>/assets` wherever it's mounted, and tell the client its API base.\n const html = readFileSync(indexPath, 'utf8').replaceAll(\n `=\"${BUILD_BASE}/`,\n `=\"${this.basePath}/`,\n );\n // __AGENT_BASE__ = where assets load; __AGENT_API__ = where the SPA fetches the JSON API.\n const inject = `<script>window.__AGENT_BASE__='${this.basePath}';window.__AGENT_API__='${this.apiBasePath}';</script>`;\n return html.includes('</head>') ? html.replace('</head>', `${inject}</head>`) : inject + html;\n }\n\n @Get('assets/:file')\n @Header('Cache-Control', 'public, max-age=31536000, immutable')\n asset(@Param('file') file: string): StreamableFile {\n const safe = basename(file);\n if (safe !== file) throw new NotFoundException();\n const root = resolve(this.dir, 'assets');\n const assetPath = resolve(root, safe);\n if (!assetPath.startsWith(root + sep) || !existsSync(assetPath)) {\n throw new NotFoundException();\n }\n const type = CONTENT_TYPES[extname(safe)] ?? 'application/octet-stream';\n return new StreamableFile(readFileSync(assetPath), { type });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;ACKA,IAAAA,iBAAwD;;;ACLxD,sCAAuC;AAkBvC,gCAA4B;AAC5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EjB,MAAMoB;YAAaT,QAAQH;UAAe;SAC7C;;MAEHJ,aAAa;QAACiB;;MACdP,WAAW;QACT;UAAES,SAASC;UAAqBC,UAAUN;QAAS;QACnD;UAAEI,SAASG;UAAoBD,UAAUL;QAAY;;WAEjDV,QAAQP,UAAU,CAAA;;;MAGxBa,SAAS;QAACR;;IACZ;EACF;AACF;;;;","names":["import_common","import_common","parsePriceInput","body","BadRequestException","modelId","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","trim","length","isFiniteNonNegative","undefined","value","Number","isFinite","AGENT_GOVERNANCE_QUERIES","Symbol","for","AGENT_ACTOR_DIRECTORY","AGENT_PRICING_STORE","DASHBOARD_BASE_PATH","DASHBOARD_API_PATH","PRICING_STORE_UNBOUND_MESSAGE","AGENT_EVENTS","isAgentEnvelope","message","event","DashboardService","queries","actorDirectory","pricingStore","spend","range","byModel","byActorRaw","trend","Promise","all","spendByModel","spendByActor","usageTrend","byActor","withActorLabels","topThreads","limit","rows","spendByThread","reliability","metrics","byAgent","errors","runMetrics","runsByAgent","runErrors","runTrend","recentRuns","recentToolCalls","recentThreads","length","undefined","map","row","actorLabel","refs","Set","actorRef","resolved","resolveDisplay","listPrices","NotImplementedException","listCurrentPrices","upsertPrice","body","upsertModelPrice","parsePriceInput","streamEvents","Observable","subscriber","bindings","name","channelName","handler","next","data","ts","Date","now","payload","subscribe","binding","unsubscribe","DAY_MS","ISO_DAY","utcDay","daysAgo","Date","now","toISOString","slice","dayOr","value","fallback","undefined","test","resolveRange","from","to","fromDay","toDay","parseLimit","parsed","Number","NaN","parseInt","isFinite","Math","max","min","AgentApiController","dashboard","spend","topThreads","limit","reliability","runs","recentRuns","toolCalls","recentToolCalls","threads","recentThreads","listPrices","upsertPrice","body","stream","streamEvents","normalizeDashboardPath","path","replace","unprefixed","path","replace","agentDashboardMountPaths","options","basePath","normalizeDashboardPath","apiBasePath","base","api","import_common","import_common","BUILD_BASE","spaDir","fileURLToPath","URL","CONTENT_TYPES","AgentUiController","dir","basePath","apiBasePath","index","indexPath","join","existsSync","NotFoundException","html","readFileSync","replaceAll","inject","includes","replace","asset","file","safe","basename","root","resolve","assetPath","startsWith","sep","type","extname","StreamableFile","GUARDS_METADATA","normalize","path","normalizeDashboardPath","stampGuards","guards","controllers","controller","Reflect","defineMetadata","AgentApiModule","register","options","module","imports","AgentApiController","providers","DashboardService","exports","AgentDashboardModule","forRoot","basePath","apiBasePath","AgentUiController","RouterModule","provide","DASHBOARD_BASE_PATH","useValue","DASHBOARD_API_PATH"]}
|
package/dist/server/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ActorSpendRow, AgentGovernanceQueries, ActorDirectory, AgentPricingStore, GovernanceRange, ModelSpendRow, UsageTrendPoint, ThreadSpendRow, ToolCallActivityRow, ThreadActivityRow, CurrentModelPrice, ModelPriceInput } from '@dudousxd/nestjs-agent-core';
|
|
1
|
+
import { ActorSpendRow, AgentGovernanceQueries, ActorDirectory, AgentPricingStore, GovernanceRange, ModelSpendRow, UsageTrendPoint, ThreadSpendRow, RunMetrics, RunAgentBreakdownRow, RunErrorBreakdownRow, RunTrendPoint, RecentRunRow, ToolCallActivityRow, ThreadActivityRow, CurrentModelPrice, ModelPriceInput } from '@dudousxd/nestjs-agent-core';
|
|
2
2
|
export { ActorDirectory } from '@dudousxd/nestjs-agent-core';
|
|
3
3
|
import { Observable } from 'rxjs';
|
|
4
4
|
import { DynamicModule, Type, CanActivate, StreamableFile } from '@nestjs/common';
|
|
@@ -16,6 +16,13 @@ interface SpendOverview {
|
|
|
16
16
|
byActor: ActorSpendRowWithLabel[];
|
|
17
17
|
trend: UsageTrendPoint[];
|
|
18
18
|
}
|
|
19
|
+
/** The run-reliability overview the SPA renders on its Reliability section (`GET <api>/reliability`). */
|
|
20
|
+
interface ReliabilityOverview {
|
|
21
|
+
metrics: RunMetrics;
|
|
22
|
+
byAgent: RunAgentBreakdownRow[];
|
|
23
|
+
errors: RunErrorBreakdownRow[];
|
|
24
|
+
trend: RunTrendPoint[];
|
|
25
|
+
}
|
|
19
26
|
/** One live agent event forwarded over SSE, flattened from the `aviary:agent:*` diagnostics envelope. */
|
|
20
27
|
interface LiveAgentEvent {
|
|
21
28
|
/** The event name, e.g. `run.started` / `tool-call` / `quota.exceeded`. */
|
|
@@ -47,6 +54,10 @@ declare class DashboardService {
|
|
|
47
54
|
spend(range: GovernanceRange): Promise<SpendOverview>;
|
|
48
55
|
/** Top threads by cost for a day range (default 10, highest cost first). */
|
|
49
56
|
topThreads(range: GovernanceRange, limit?: number): Promise<ThreadSpendRowWithLabel[]>;
|
|
57
|
+
/** Run reliability for a day range: metrics, by-agent/by-error breakdowns and the trend, in parallel. */
|
|
58
|
+
reliability(range: GovernanceRange): Promise<ReliabilityOverview>;
|
|
59
|
+
/** Most recent runs (status/agent/duration/error) for the Reliability recent-runs table. */
|
|
60
|
+
recentRuns(limit: number): Promise<RecentRunRow[]>;
|
|
50
61
|
/** Most recent tool calls (status/type/thread) for the Runs & tools activity feed. */
|
|
51
62
|
recentToolCalls(limit: number): Promise<ToolCallActivityRow[]>;
|
|
52
63
|
/** Most recent threads with rolled-up message/token counts. */
|
|
@@ -86,6 +97,10 @@ declare class AgentApiController {
|
|
|
86
97
|
spend(from?: string, to?: string): Promise<SpendOverview>;
|
|
87
98
|
/** Top threads by cost (default 10, max 200) for a day range (defaults to the last 30 days). */
|
|
88
99
|
topThreads(from?: string, to?: string, limit?: string): Promise<ThreadSpendRowWithLabel[]>;
|
|
100
|
+
/** `{ metrics, byAgent, errors, trend }` for a day range (defaults to the last 30 days). */
|
|
101
|
+
reliability(from?: string, to?: string): Promise<ReliabilityOverview>;
|
|
102
|
+
/** Most recent runs (default 50, max 200) for the Reliability recent-runs table. */
|
|
103
|
+
runs(limit?: string): Promise<RecentRunRow[]>;
|
|
89
104
|
/** Most recent tool calls (default 50, max 200) for the activity feed. */
|
|
90
105
|
toolCalls(limit?: string): Promise<ToolCallActivityRow[]>;
|
|
91
106
|
/** Most recent threads (default 50, max 200) with rolled-up counts. */
|
|
@@ -250,4 +265,4 @@ declare const DASHBOARD_BASE_PATH: unique symbol;
|
|
|
250
265
|
/** DI token carrying the JSON API base the SPA fetches from (e.g. `/ai-gateway/api`). */
|
|
251
266
|
declare const DASHBOARD_API_PATH: unique symbol;
|
|
252
267
|
|
|
253
|
-
export { AGENT_ACTOR_DIRECTORY, AGENT_GOVERNANCE_QUERIES, AGENT_PRICING_STORE, type ActorSpendRowWithLabel, AgentApiController, AgentApiModule, AgentDashboardModule, type AgentDashboardMountPathsOptions, type AgentDashboardOptions, AgentUiController, DASHBOARD_API_PATH, DASHBOARD_BASE_PATH, DashboardService, type LiveAgentEvent, type SpendOverview, type ThreadActivityRowWithLabel, type ThreadSpendRowWithLabel, type WithActorLabel, agentDashboardMountPaths, parsePriceInput };
|
|
268
|
+
export { AGENT_ACTOR_DIRECTORY, AGENT_GOVERNANCE_QUERIES, AGENT_PRICING_STORE, type ActorSpendRowWithLabel, AgentApiController, AgentApiModule, AgentDashboardModule, type AgentDashboardMountPathsOptions, type AgentDashboardOptions, AgentUiController, DASHBOARD_API_PATH, DASHBOARD_BASE_PATH, DashboardService, type LiveAgentEvent, type ReliabilityOverview, type SpendOverview, type ThreadActivityRowWithLabel, type ThreadSpendRowWithLabel, type WithActorLabel, agentDashboardMountPaths, parsePriceInput };
|