@dudousxd/nestjs-agent-dashboard 0.2.0 → 0.3.1
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 +11 -0
- package/dist/client/agent-client.d.ts.map +1 -1
- package/dist/client/agent-client.js +5 -0
- package/dist/client/agent-client.js.map +1 -1
- package/dist/server/index.cjs +21 -0
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +5 -1
- package/dist/server/index.d.ts +5 -1
- package/dist/server/index.js +21 -0
- package/dist/server/index.js.map +1 -1
- package/dist/spa/assets/index-iAxp-O4a.js +49 -0
- package/dist/spa/assets/index-qU4prctf.js +1 -0
- package/dist/spa/assets/preview-DsgQ_Xk_.js +1 -0
- package/dist/spa/index.html +2 -2
- package/dist/spa/preview.html +2 -2
- package/package.json +2 -2
- package/dist/spa/assets/index-CVpU-HIB.js +0 -49
- package/dist/spa/assets/index-IlHveh9s.js +0 -1
- package/dist/spa/assets/preview-BsbVArrR.js +0 -1
|
@@ -18,6 +18,15 @@ export interface ActorSpendRow {
|
|
|
18
18
|
totalTokens: number;
|
|
19
19
|
costUsd: number;
|
|
20
20
|
}
|
|
21
|
+
/** Spend + token totals for one thread over a range. */
|
|
22
|
+
export interface ThreadSpendRow {
|
|
23
|
+
threadId: string;
|
|
24
|
+
title: string;
|
|
25
|
+
actorRef: string;
|
|
26
|
+
requests: number;
|
|
27
|
+
totalTokens: number;
|
|
28
|
+
costUsd: number;
|
|
29
|
+
}
|
|
21
30
|
/** One point on the daily usage/cost trend. */
|
|
22
31
|
export interface UsageTrendPoint {
|
|
23
32
|
day: string;
|
|
@@ -65,6 +74,8 @@ declare global {
|
|
|
65
74
|
export declare const agentClient: {
|
|
66
75
|
/** Spend/usage overview for a day range: `{ byModel, byActor, trend }`. */
|
|
67
76
|
spend(range: GovernanceRange): Promise<SpendOverview>;
|
|
77
|
+
/** Top threads by cost for a day range (default 10). */
|
|
78
|
+
topThreads(range: GovernanceRange, limit?: number): Promise<ThreadSpendRow[]>;
|
|
68
79
|
/** Most recent tool calls (default 50). */
|
|
69
80
|
toolCalls(limit?: number): Promise<ToolCallActivityRow[]>;
|
|
70
81
|
/** 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;CACjB;AAED,+CAA+C;AAC/C,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,MAAM,CAAC;IACZ,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,gDAAgD;AAChD,MAAM,WAAW,mBAAmB;IAClC,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,+CAA+C;AAC/C,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB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,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AAED,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,MAAM;QACd,qGAAqG;QACrG,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,wGAAwG;QACxG,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB;CACF;AAcD,eAAO,MAAM,WAAW;IACtB,2EAA2E;iBAC9D,eAAe,GAAG,OAAO,CAAC,aAAa,CAAC;IAIrD,wDAAwD;sBACtC,eAAe,mBAAe,OAAO,CAAC,cAAc,EAAE,CAAC;IAIzE,2CAA2C;+BACpB,OAAO,CAAC,mBAAmB,EAAE,CAAC;IAGrD,wCAAwC;6BACnB,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAGjD;;;OAGG;0BACmB,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,GAAG,MAAM,IAAI;CAWnE,CAAC"}
|
|
@@ -19,6 +19,11 @@ export const agentClient = {
|
|
|
19
19
|
const q = new URLSearchParams({ from: range.fromDay, to: range.toDay });
|
|
20
20
|
return http(`/spend?${q.toString()}`);
|
|
21
21
|
},
|
|
22
|
+
/** Top threads by cost for a day range (default 10). */
|
|
23
|
+
topThreads(range, limit = 10) {
|
|
24
|
+
const q = new URLSearchParams({ from: range.fromDay, to: range.toDay, limit: `${limit}` });
|
|
25
|
+
return http(`/top-threads?${q.toString()}`);
|
|
26
|
+
},
|
|
22
27
|
/** Most recent tool calls (default 50). */
|
|
23
28
|
toolCalls(limit = 50) {
|
|
24
29
|
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,mG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EAAE,CAAC,CAAC;IAChE,CAAC;IACD,2CAA2C;IAC3C,SAAS,CAAC,KAAK,GAAG,EAAE;QAClB,OAAO,IAAI,CAAwB,qBAAqB,KAAK,EAAE,CAAC,CAAC;IACnE,CAAC;IACD,wCAAwC;IACxC,OAAO,CAAC,KAAK,GAAG,EAAE;QAChB,OAAO,IAAI,CAAsB,kBAAkB,KAAK,EAAE,CAAC,CAAC;IAC9D,CAAC;IACD;;;OAGG;IACH,YAAY,CAAC,OAAwC;QACnD,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,GAAG,OAAO,EAAE,SAAS,CAAC,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"}
|
package/dist/server/index.cjs
CHANGED
|
@@ -98,6 +98,10 @@ var DashboardService = class {
|
|
|
98
98
|
trend
|
|
99
99
|
};
|
|
100
100
|
}
|
|
101
|
+
/** Top threads by cost for a day range (default 10, highest cost first). */
|
|
102
|
+
topThreads(range, limit = 10) {
|
|
103
|
+
return this.queries.spendByThread(range, limit);
|
|
104
|
+
}
|
|
101
105
|
/** Most recent tool calls (status/type/thread) for the Runs & tools activity feed. */
|
|
102
106
|
recentToolCalls(limit) {
|
|
103
107
|
return this.queries.recentToolCalls(limit);
|
|
@@ -199,6 +203,10 @@ var AgentApiController = class {
|
|
|
199
203
|
spend(from, to) {
|
|
200
204
|
return this.dashboard.spend(resolveRange(from, to));
|
|
201
205
|
}
|
|
206
|
+
/** Top threads by cost (default 10, max 200) for a day range (defaults to the last 30 days). */
|
|
207
|
+
topThreads(from, to, limit) {
|
|
208
|
+
return this.dashboard.topThreads(resolveRange(from, to), parseLimit(limit, 10));
|
|
209
|
+
}
|
|
202
210
|
/** Most recent tool calls (default 50, max 200) for the activity feed. */
|
|
203
211
|
toolCalls(limit) {
|
|
204
212
|
return this.dashboard.recentToolCalls(parseLimit(limit, 50));
|
|
@@ -223,6 +231,19 @@ _ts_decorate2([
|
|
|
223
231
|
]),
|
|
224
232
|
_ts_metadata2("design:returntype", typeof Promise === "undefined" ? Object : Promise)
|
|
225
233
|
], AgentApiController.prototype, "spend", null);
|
|
234
|
+
_ts_decorate2([
|
|
235
|
+
(0, import_common2.Get)("top-threads"),
|
|
236
|
+
_ts_param2(0, (0, import_common2.Query)("from")),
|
|
237
|
+
_ts_param2(1, (0, import_common2.Query)("to")),
|
|
238
|
+
_ts_param2(2, (0, import_common2.Query)("limit")),
|
|
239
|
+
_ts_metadata2("design:type", Function),
|
|
240
|
+
_ts_metadata2("design:paramtypes", [
|
|
241
|
+
String,
|
|
242
|
+
String,
|
|
243
|
+
String
|
|
244
|
+
]),
|
|
245
|
+
_ts_metadata2("design:returntype", typeof Promise === "undefined" ? Object : Promise)
|
|
246
|
+
], AgentApiController.prototype, "topThreads", null);
|
|
226
247
|
_ts_decorate2([
|
|
227
248
|
(0, import_common2.Get)("tool-calls"),
|
|
228
249
|
_ts_param2(0, (0, import_common2.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/tokens.ts","../../src/server/agent-dashboard.module.ts","../../src/server/agent-ui.controller.ts"],"sourcesContent":["export * from './agent-api.controller.js';\nexport * from './agent-dashboard.module.js';\nexport * from './agent-ui.controller.js';\nexport * from './dashboard.service.js';\nexport * from './tokens.js';\n","import type { ThreadActivityRow, ToolCallActivityRow } from '@dudousxd/nestjs-agent-core';\nimport { Controller, Get, Query, Sse } from '@nestjs/common';\nimport type { Observable } from 'rxjs';\nimport { DashboardService, type LiveAgentEvent, type SpendOverview } 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 /** 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<ThreadActivityRow[]> {\n return this.dashboard.recentThreads(parseLimit(limit, 50));\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 GovernanceRange,\n ModelSpendRow,\n ThreadActivityRow,\n ToolCallActivityRow,\n UsageTrendPoint,\n} from '@dudousxd/nestjs-agent-core';\nimport { channelName } from '@dudousxd/nestjs-diagnostics';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { AGENT_GOVERNANCE_QUERIES } from './tokens.js';\n\n/** The spend/usage overview the SPA renders on its headline section (`GET <api>/spend`). */\nexport interface SpendOverview {\n byModel: ModelSpendRow[];\n byActor: ActorSpendRow[];\n trend: UsageTrendPoint[];\n}\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 */\n@Injectable()\nexport class DashboardService {\n constructor(@Inject(AGENT_GOVERNANCE_QUERIES) private readonly queries: AgentGovernanceQueries) {}\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, byActor, trend] = await Promise.all([\n this.queries.spendByModel(range),\n this.queries.spendByActor(range),\n this.queries.usageTrend(range),\n ]);\n return { byModel, byActor, trend };\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 recentThreads(limit: number): Promise<ThreadActivityRow[]> {\n return this.queries.recentThreads(limit);\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","/**\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/** 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","import { type DynamicModule, Module } 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 { DASHBOARD_API_PATH, DASHBOARD_BASE_PATH } from './tokens.js';\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\n/** Leading slash, no trailing slash. */\nfunction normalize(path: string): string {\n return `/${path.replace(/^\\/+|\\/+$/g, '')}`;\n}\n\n/** Holds the JSON API + SSE controller and its read service, mounted on its own path by `forRoot`. */\n@Module({\n controllers: [AgentApiController],\n providers: [DashboardService],\n exports: [DashboardService],\n})\nexport class AgentApiModule {}\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 your own guard — the controllers are path-relative and guard-frontable.\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 return {\n module: AgentDashboardModule,\n imports: [\n AgentApiModule,\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 ],\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":";;;;;;;;;;;;;;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","DashboardService","queries","spend","range","byModel","byActor","trend","Promise","all","spendByModel","spendByActor","usageTrend","recentToolCalls","limit","recentThreads","streamEvents","Observable","subscriber","bindings","map","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","toolCalls","limit","recentToolCalls","threads","recentThreads","stream","streamEvents","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","normalize","path","replace","AgentApiModule","controllers","AgentApiController","providers","DashboardService","exports","AgentDashboardModule","forRoot","options","basePath","apiBasePath","module","imports","RouterModule","register","AgentUiController","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/tokens.ts","../../src/server/agent-dashboard.module.ts","../../src/server/agent-ui.controller.ts"],"sourcesContent":["export * from './agent-api.controller.js';\nexport * from './agent-dashboard.module.js';\nexport * from './agent-ui.controller.js';\nexport * from './dashboard.service.js';\nexport * from './tokens.js';\n","import type {\n ThreadActivityRow,\n ThreadSpendRow,\n ToolCallActivityRow,\n} from '@dudousxd/nestjs-agent-core';\nimport { Controller, Get, Query, Sse } from '@nestjs/common';\nimport type { Observable } from 'rxjs';\nimport { DashboardService, type LiveAgentEvent, type SpendOverview } 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<ThreadSpendRow[]> {\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<ThreadActivityRow[]> {\n return this.dashboard.recentThreads(parseLimit(limit, 50));\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 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 } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { AGENT_GOVERNANCE_QUERIES } from './tokens.js';\n\n/** The spend/usage overview the SPA renders on its headline section (`GET <api>/spend`). */\nexport interface SpendOverview {\n byModel: ModelSpendRow[];\n byActor: ActorSpendRow[];\n trend: UsageTrendPoint[];\n}\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 */\n@Injectable()\nexport class DashboardService {\n constructor(@Inject(AGENT_GOVERNANCE_QUERIES) private readonly queries: AgentGovernanceQueries) {}\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, byActor, trend] = await Promise.all([\n this.queries.spendByModel(range),\n this.queries.spendByActor(range),\n this.queries.usageTrend(range),\n ]);\n return { byModel, byActor, trend };\n }\n\n /** Top threads by cost for a day range (default 10, highest cost first). */\n topThreads(range: GovernanceRange, limit = 10): Promise<ThreadSpendRow[]> {\n return this.queries.spendByThread(range, 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 recentThreads(limit: number): Promise<ThreadActivityRow[]> {\n return this.queries.recentThreads(limit);\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","/**\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/** 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","import { type DynamicModule, Module } 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 { DASHBOARD_API_PATH, DASHBOARD_BASE_PATH } from './tokens.js';\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\n/** Leading slash, no trailing slash. */\nfunction normalize(path: string): string {\n return `/${path.replace(/^\\/+|\\/+$/g, '')}`;\n}\n\n/** Holds the JSON API + SSE controller and its read service, mounted on its own path by `forRoot`. */\n@Module({\n controllers: [AgentApiController],\n providers: [DashboardService],\n exports: [DashboardService],\n})\nexport class AgentApiModule {}\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 your own guard — the controllers are path-relative and guard-frontable.\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 return {\n module: AgentDashboardModule,\n imports: [\n AgentApiModule,\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 ],\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,iBAA4C;;;ACL5C,sCAAuC;AAWvC,gCAA4B;AAC5B,oBAAmC;AACnC,kBAA2B;;;ACEpB,IAAMC,2BAA2BC,OAAOC,IAAI,2CAAA;AAG5C,IAAMC,sBAAsBF,OAAOC,IAAI,4CAAA;AAGvC,IAAME,qBAAqBH,OAAOC,IAAI,2CAAA;;;;;;;;;;;;;;;;;;;;ADa7C,IAAMG,eAAe;EACnB;EACA;EACA;EACA;EACA;EACA;;AAWF,SAASC,gBAAgBC,SAAgB;AACvC,SACE,OAAOA,YAAY,YACnBA,YAAY,QACZ,WAAWA,WACX,OAAQA,QAA+BC,UAAU;AAErD;AAPSF;AAmBF,IAAMG,mBAAN,MAAMA;SAAAA;;;;EACX,YAA+DC,SAAiC;SAAjCA,UAAAA;EAAkC;;EAGjG,MAAMC,MAAMC,OAAgD;AAC1D,UAAM,CAACC,SAASC,SAASC,KAAAA,IAAS,MAAMC,QAAQC,IAAI;MAClD,KAAKP,QAAQQ,aAAaN,KAAAA;MAC1B,KAAKF,QAAQS,aAAaP,KAAAA;MAC1B,KAAKF,QAAQU,WAAWR,KAAAA;KACzB;AACD,WAAO;MAAEC;MAASC;MAASC;IAAM;EACnC;;EAGAM,WAAWT,OAAwBU,QAAQ,IAA+B;AACxE,WAAO,KAAKZ,QAAQa,cAAcX,OAAOU,KAAAA;EAC3C;;EAGAE,gBAAgBF,OAA+C;AAC7D,WAAO,KAAKZ,QAAQc,gBAAgBF,KAAAA;EACtC;;EAGAG,cAAcH,OAA6C;AACzD,WAAO,KAAKZ,QAAQe,cAAcH,KAAAA;EACpC;;;;;;EAOAI,eAAqD;AACnD,WAAO,IAAIC,uBAAqC,CAACC,eAAAA;AAC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S;QACPZ;QACAa,yBAAaC,SAAS;UACpB;YAAEhB,MAAMW;YAAUE,QAAQL;UAAqB;UAC/C;YAAER,MAAMY;YAAaC,QAAQX;UAAe;SAC7C;;MAEHC,aAAa;QAACc;;MACdZ,WAAW;QACT;UAAEa,SAASC;UAAqBC,UAAUT;QAAS;QACnD;UAAEO,SAASG;UAAoBD,UAAUR;QAAY;;;MAGvDL,SAAS;QAACL;;IACZ;EACF;AACF;;;;","names":["import_common","AGENT_GOVERNANCE_QUERIES","Symbol","for","DASHBOARD_BASE_PATH","DASHBOARD_API_PATH","AGENT_EVENTS","isAgentEnvelope","message","event","DashboardService","queries","spend","range","byModel","byActor","trend","Promise","all","spendByModel","spendByActor","usageTrend","topThreads","limit","spendByThread","recentToolCalls","recentThreads","streamEvents","Observable","subscriber","bindings","map","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","stream","streamEvents","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","normalize","path","replace","AgentApiModule","controllers","AgentApiController","providers","DashboardService","exports","AgentDashboardModule","forRoot","options","basePath","apiBasePath","module","imports","RouterModule","register","AgentUiController","provide","DASHBOARD_BASE_PATH","useValue","DASHBOARD_API_PATH"]}
|
package/dist/server/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AgentGovernanceQueries, GovernanceRange, ModelSpendRow, ActorSpendRow, UsageTrendPoint, ToolCallActivityRow, ThreadActivityRow } from '@dudousxd/nestjs-agent-core';
|
|
1
|
+
import { AgentGovernanceQueries, GovernanceRange, ModelSpendRow, ActorSpendRow, UsageTrendPoint, ThreadSpendRow, ToolCallActivityRow, ThreadActivityRow } from '@dudousxd/nestjs-agent-core';
|
|
2
2
|
import { Observable } from 'rxjs';
|
|
3
3
|
import { DynamicModule, StreamableFile } from '@nestjs/common';
|
|
4
4
|
|
|
@@ -31,6 +31,8 @@ declare class DashboardService {
|
|
|
31
31
|
constructor(queries: AgentGovernanceQueries);
|
|
32
32
|
/** Spend/usage overview for a day range: by-model + by-actor spend and the daily trend, in parallel. */
|
|
33
33
|
spend(range: GovernanceRange): Promise<SpendOverview>;
|
|
34
|
+
/** Top threads by cost for a day range (default 10, highest cost first). */
|
|
35
|
+
topThreads(range: GovernanceRange, limit?: number): Promise<ThreadSpendRow[]>;
|
|
34
36
|
/** Most recent tool calls (status/type/thread) for the Runs & tools activity feed. */
|
|
35
37
|
recentToolCalls(limit: number): Promise<ToolCallActivityRow[]>;
|
|
36
38
|
/** Most recent threads with rolled-up message/token counts. */
|
|
@@ -54,6 +56,8 @@ declare class AgentApiController {
|
|
|
54
56
|
constructor(dashboard: DashboardService);
|
|
55
57
|
/** `{ byModel, byActor, trend }` for a day range (defaults to the last 30 days). */
|
|
56
58
|
spend(from?: string, to?: string): Promise<SpendOverview>;
|
|
59
|
+
/** Top threads by cost (default 10, max 200) for a day range (defaults to the last 30 days). */
|
|
60
|
+
topThreads(from?: string, to?: string, limit?: string): Promise<ThreadSpendRow[]>;
|
|
57
61
|
/** Most recent tool calls (default 50, max 200) for the activity feed. */
|
|
58
62
|
toolCalls(limit?: string): Promise<ToolCallActivityRow[]>;
|
|
59
63
|
/** Most recent threads (default 50, max 200) with rolled-up counts. */
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AgentGovernanceQueries, GovernanceRange, ModelSpendRow, ActorSpendRow, UsageTrendPoint, ToolCallActivityRow, ThreadActivityRow } from '@dudousxd/nestjs-agent-core';
|
|
1
|
+
import { AgentGovernanceQueries, GovernanceRange, ModelSpendRow, ActorSpendRow, UsageTrendPoint, ThreadSpendRow, ToolCallActivityRow, ThreadActivityRow } from '@dudousxd/nestjs-agent-core';
|
|
2
2
|
import { Observable } from 'rxjs';
|
|
3
3
|
import { DynamicModule, StreamableFile } from '@nestjs/common';
|
|
4
4
|
|
|
@@ -31,6 +31,8 @@ declare class DashboardService {
|
|
|
31
31
|
constructor(queries: AgentGovernanceQueries);
|
|
32
32
|
/** Spend/usage overview for a day range: by-model + by-actor spend and the daily trend, in parallel. */
|
|
33
33
|
spend(range: GovernanceRange): Promise<SpendOverview>;
|
|
34
|
+
/** Top threads by cost for a day range (default 10, highest cost first). */
|
|
35
|
+
topThreads(range: GovernanceRange, limit?: number): Promise<ThreadSpendRow[]>;
|
|
34
36
|
/** Most recent tool calls (status/type/thread) for the Runs & tools activity feed. */
|
|
35
37
|
recentToolCalls(limit: number): Promise<ToolCallActivityRow[]>;
|
|
36
38
|
/** Most recent threads with rolled-up message/token counts. */
|
|
@@ -54,6 +56,8 @@ declare class AgentApiController {
|
|
|
54
56
|
constructor(dashboard: DashboardService);
|
|
55
57
|
/** `{ byModel, byActor, trend }` for a day range (defaults to the last 30 days). */
|
|
56
58
|
spend(from?: string, to?: string): Promise<SpendOverview>;
|
|
59
|
+
/** Top threads by cost (default 10, max 200) for a day range (defaults to the last 30 days). */
|
|
60
|
+
topThreads(from?: string, to?: string, limit?: string): Promise<ThreadSpendRow[]>;
|
|
57
61
|
/** Most recent tool calls (default 50, max 200) for the activity feed. */
|
|
58
62
|
toolCalls(limit?: string): Promise<ToolCallActivityRow[]>;
|
|
59
63
|
/** Most recent threads (default 50, max 200) with rolled-up counts. */
|
package/dist/server/index.js
CHANGED
|
@@ -66,6 +66,10 @@ var DashboardService = class {
|
|
|
66
66
|
trend
|
|
67
67
|
};
|
|
68
68
|
}
|
|
69
|
+
/** Top threads by cost for a day range (default 10, highest cost first). */
|
|
70
|
+
topThreads(range, limit = 10) {
|
|
71
|
+
return this.queries.spendByThread(range, limit);
|
|
72
|
+
}
|
|
69
73
|
/** Most recent tool calls (status/type/thread) for the Runs & tools activity feed. */
|
|
70
74
|
recentToolCalls(limit) {
|
|
71
75
|
return this.queries.recentToolCalls(limit);
|
|
@@ -167,6 +171,10 @@ var AgentApiController = class {
|
|
|
167
171
|
spend(from, to) {
|
|
168
172
|
return this.dashboard.spend(resolveRange(from, to));
|
|
169
173
|
}
|
|
174
|
+
/** Top threads by cost (default 10, max 200) for a day range (defaults to the last 30 days). */
|
|
175
|
+
topThreads(from, to, limit) {
|
|
176
|
+
return this.dashboard.topThreads(resolveRange(from, to), parseLimit(limit, 10));
|
|
177
|
+
}
|
|
170
178
|
/** Most recent tool calls (default 50, max 200) for the activity feed. */
|
|
171
179
|
toolCalls(limit) {
|
|
172
180
|
return this.dashboard.recentToolCalls(parseLimit(limit, 50));
|
|
@@ -191,6 +199,19 @@ _ts_decorate2([
|
|
|
191
199
|
]),
|
|
192
200
|
_ts_metadata2("design:returntype", typeof Promise === "undefined" ? Object : Promise)
|
|
193
201
|
], AgentApiController.prototype, "spend", null);
|
|
202
|
+
_ts_decorate2([
|
|
203
|
+
Get("top-threads"),
|
|
204
|
+
_ts_param2(0, Query("from")),
|
|
205
|
+
_ts_param2(1, Query("to")),
|
|
206
|
+
_ts_param2(2, Query("limit")),
|
|
207
|
+
_ts_metadata2("design:type", Function),
|
|
208
|
+
_ts_metadata2("design:paramtypes", [
|
|
209
|
+
String,
|
|
210
|
+
String,
|
|
211
|
+
String
|
|
212
|
+
]),
|
|
213
|
+
_ts_metadata2("design:returntype", typeof Promise === "undefined" ? Object : Promise)
|
|
214
|
+
], AgentApiController.prototype, "topThreads", null);
|
|
194
215
|
_ts_decorate2([
|
|
195
216
|
Get("tool-calls"),
|
|
196
217
|
_ts_param2(0, Query("limit")),
|
package/dist/server/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/agent-api.controller.ts","../../src/server/dashboard.service.ts","../../src/server/tokens.ts","../../src/server/agent-dashboard.module.ts","../../src/server/agent-ui.controller.ts"],"sourcesContent":["import type { ThreadActivityRow, ToolCallActivityRow } from '@dudousxd/nestjs-agent-core';\nimport { Controller, Get, Query, Sse } from '@nestjs/common';\nimport type { Observable } from 'rxjs';\nimport { DashboardService, type LiveAgentEvent, type SpendOverview } 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 /** 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<ThreadActivityRow[]> {\n return this.dashboard.recentThreads(parseLimit(limit, 50));\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 GovernanceRange,\n ModelSpendRow,\n ThreadActivityRow,\n ToolCallActivityRow,\n UsageTrendPoint,\n} from '@dudousxd/nestjs-agent-core';\nimport { channelName } from '@dudousxd/nestjs-diagnostics';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { AGENT_GOVERNANCE_QUERIES } from './tokens.js';\n\n/** The spend/usage overview the SPA renders on its headline section (`GET <api>/spend`). */\nexport interface SpendOverview {\n byModel: ModelSpendRow[];\n byActor: ActorSpendRow[];\n trend: UsageTrendPoint[];\n}\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 */\n@Injectable()\nexport class DashboardService {\n constructor(@Inject(AGENT_GOVERNANCE_QUERIES) private readonly queries: AgentGovernanceQueries) {}\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, byActor, trend] = await Promise.all([\n this.queries.spendByModel(range),\n this.queries.spendByActor(range),\n this.queries.usageTrend(range),\n ]);\n return { byModel, byActor, trend };\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 recentThreads(limit: number): Promise<ThreadActivityRow[]> {\n return this.queries.recentThreads(limit);\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","/**\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/** 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","import { type DynamicModule, Module } 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 { DASHBOARD_API_PATH, DASHBOARD_BASE_PATH } from './tokens.js';\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\n/** Leading slash, no trailing slash. */\nfunction normalize(path: string): string {\n return `/${path.replace(/^\\/+|\\/+$/g, '')}`;\n}\n\n/** Holds the JSON API + SSE controller and its read service, mounted on its own path by `forRoot`. */\n@Module({\n controllers: [AgentApiController],\n providers: [DashboardService],\n exports: [DashboardService],\n})\nexport class AgentApiModule {}\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 your own guard — the controllers are path-relative and guard-frontable.\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 return {\n module: AgentDashboardModule,\n imports: [\n AgentApiModule,\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 ],\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":";;;;AACA,SAASA,YAAYC,KAAKC,OAAOC,WAAW;;;ACD5C,SAASC,WAAWC,mBAAmB;AAUvC,SAASC,mBAAmB;AAC5B,SAASC,QAAQC,kBAAkB;AACnC,SAASC,cAAAA,mBAAkB;;;ACGpB,IAAMC,2BAA2BC,OAAOC,IAAI,2CAAA;AAG5C,IAAMC,sBAAsBF,OAAOC,IAAI,4CAAA;AAGvC,IAAME,qBAAqBH,OAAOC,IAAI,2CAAA;;;;;;;;;;;;;;;;;;;;ADY7C,IAAMG,eAAe;EACnB;EACA;EACA;EACA;EACA;EACA;;AAWF,SAASC,gBAAgBC,SAAgB;AACvC,SACE,OAAOA,YAAY,YACnBA,YAAY,QACZ,WAAWA,WACX,OAAQA,QAA+BC,UAAU;AAErD;AAPSF;AAmBF,IAAMG,mBAAN,MAAMA;SAAAA;;;;EACX,YAA+DC,SAAiC;SAAjCA,UAAAA;EAAkC;;EAGjG,MAAMC,MAAMC,OAAgD;AAC1D,UAAM,CAACC,SAASC,SAASC,KAAAA,IAAS,MAAMC,QAAQC,IAAI;MAClD,KAAKP,QAAQQ,aAAaN,KAAAA;MAC1B,KAAKF,QAAQS,aAAaP,KAAAA;MAC1B,KAAKF,QAAQU,WAAWR,KAAAA;KACzB;AACD,WAAO;MAAEC;MAASC;MAASC;IAAM;EACnC;;EAGAM,gBAAgBC,OAA+C;AAC7D,WAAO,KAAKZ,QAAQW,gBAAgBC,KAAAA;EACtC;;EAGAC,cAAcD,OAA6C;AACzD,WAAO,KAAKZ,QAAQa,cAAcD,KAAAA;EACpC;;;;;;EAOAE,eAAqD;AACnD,WAAO,IAAIC,YAAqC,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pB;YAAEhB,MAAMW;YAAUE,QAAQL;UAAqB;UAC/C;YAAER,MAAMY;YAAaC,QAAQX;UAAe;SAC7C;;MAEHC,aAAa;QAACc;;MACdZ,WAAW;QACT;UAAEa,SAASC;UAAqBC,UAAUT;QAAS;QACnD;UAAEO,SAASG;UAAoBD,UAAUR;QAAY;;;MAGvDL,SAAS;QAACL;;IACZ;EACF;AACF;;;;","names":["Controller","Get","Query","Sse","subscribe","unsubscribe","channelName","Inject","Injectable","Observable","AGENT_GOVERNANCE_QUERIES","Symbol","for","DASHBOARD_BASE_PATH","DASHBOARD_API_PATH","AGENT_EVENTS","isAgentEnvelope","message","event","DashboardService","queries","spend","range","byModel","byActor","trend","Promise","all","spendByModel","spendByActor","usageTrend","recentToolCalls","limit","recentThreads","streamEvents","Observable","subscriber","bindings","map","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","toolCalls","limit","recentToolCalls","threads","recentThreads","stream","streamEvents","Module","RouterModule","existsSync","readFileSync","basename","extname","join","resolve","sep","fileURLToPath","Controller","Get","Header","Inject","NotFoundException","Param","StreamableFile","BUILD_BASE","spaDir","fileURLToPath","URL","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","normalize","path","replace","AgentApiModule","controllers","AgentApiController","providers","DashboardService","exports","AgentDashboardModule","forRoot","options","basePath","apiBasePath","module","imports","RouterModule","register","AgentUiController","provide","DASHBOARD_BASE_PATH","useValue","DASHBOARD_API_PATH"]}
|
|
1
|
+
{"version":3,"sources":["../../src/server/agent-api.controller.ts","../../src/server/dashboard.service.ts","../../src/server/tokens.ts","../../src/server/agent-dashboard.module.ts","../../src/server/agent-ui.controller.ts"],"sourcesContent":["import type {\n ThreadActivityRow,\n ThreadSpendRow,\n ToolCallActivityRow,\n} from '@dudousxd/nestjs-agent-core';\nimport { Controller, Get, Query, Sse } from '@nestjs/common';\nimport type { Observable } from 'rxjs';\nimport { DashboardService, type LiveAgentEvent, type SpendOverview } 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<ThreadSpendRow[]> {\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<ThreadActivityRow[]> {\n return this.dashboard.recentThreads(parseLimit(limit, 50));\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 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 } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { AGENT_GOVERNANCE_QUERIES } from './tokens.js';\n\n/** The spend/usage overview the SPA renders on its headline section (`GET <api>/spend`). */\nexport interface SpendOverview {\n byModel: ModelSpendRow[];\n byActor: ActorSpendRow[];\n trend: UsageTrendPoint[];\n}\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 */\n@Injectable()\nexport class DashboardService {\n constructor(@Inject(AGENT_GOVERNANCE_QUERIES) private readonly queries: AgentGovernanceQueries) {}\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, byActor, trend] = await Promise.all([\n this.queries.spendByModel(range),\n this.queries.spendByActor(range),\n this.queries.usageTrend(range),\n ]);\n return { byModel, byActor, trend };\n }\n\n /** Top threads by cost for a day range (default 10, highest cost first). */\n topThreads(range: GovernanceRange, limit = 10): Promise<ThreadSpendRow[]> {\n return this.queries.spendByThread(range, 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 recentThreads(limit: number): Promise<ThreadActivityRow[]> {\n return this.queries.recentThreads(limit);\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","/**\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/** 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","import { type DynamicModule, Module } 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 { DASHBOARD_API_PATH, DASHBOARD_BASE_PATH } from './tokens.js';\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\n/** Leading slash, no trailing slash. */\nfunction normalize(path: string): string {\n return `/${path.replace(/^\\/+|\\/+$/g, '')}`;\n}\n\n/** Holds the JSON API + SSE controller and its read service, mounted on its own path by `forRoot`. */\n@Module({\n controllers: [AgentApiController],\n providers: [DashboardService],\n exports: [DashboardService],\n})\nexport class AgentApiModule {}\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 your own guard — the controllers are path-relative and guard-frontable.\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 return {\n module: AgentDashboardModule,\n imports: [\n AgentApiModule,\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 ],\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":";;;;AAKA,SAASA,YAAYC,KAAKC,OAAOC,WAAW;;;ACL5C,SAASC,WAAWC,mBAAmB;AAWvC,SAASC,mBAAmB;AAC5B,SAASC,QAAQC,kBAAkB;AACnC,SAASC,cAAAA,mBAAkB;;;ACEpB,IAAMC,2BAA2BC,OAAOC,IAAI,2CAAA;AAG5C,IAAMC,sBAAsBF,OAAOC,IAAI,4CAAA;AAGvC,IAAME,qBAAqBH,OAAOC,IAAI,2CAAA;;;;;;;;;;;;;;;;;;;;ADa7C,IAAMG,eAAe;EACnB;EACA;EACA;EACA;EACA;EACA;;AAWF,SAASC,gBAAgBC,SAAgB;AACvC,SACE,OAAOA,YAAY,YACnBA,YAAY,QACZ,WAAWA,WACX,OAAQA,QAA+BC,UAAU;AAErD;AAPSF;AAmBF,IAAMG,mBAAN,MAAMA;SAAAA;;;;EACX,YAA+DC,SAAiC;SAAjCA,UAAAA;EAAkC;;EAGjG,MAAMC,MAAMC,OAAgD;AAC1D,UAAM,CAACC,SAASC,SAASC,KAAAA,IAAS,MAAMC,QAAQC,IAAI;MAClD,KAAKP,QAAQQ,aAAaN,KAAAA;MAC1B,KAAKF,QAAQS,aAAaP,KAAAA;M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EAC5D;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AD1DA,SAASG,UAAUC,MAAY;AAC7B,SAAO,IAAIA,KAAKC,QAAQ,cAAc,EAAA,CAAA;AACxC;AAFSF;AAUF,IAAMG,iBAAN,MAAMA;SAAAA;;;AAAgB;;;IAJ3BC,aAAa;MAACC;;IACdC,WAAW;MAACC;;IACZC,SAAS;MAACD;;;;AAaL,IAAME,uBAAN,MAAMA,sBAAAA;SAAAA;;;EACX,OAAOC,QAAQC,UAAiC,CAAC,GAAkB;AACjE,UAAMC,WAAWZ,UAAUW,QAAQC,YAAY,aAAA;AAC/C,UAAMC,cAAcb,UAAUW,QAAQE,eAAe,GAAGD,QAAAA,MAAc;AACtE,WAAO;MACLE,QAAQL;MACRM,SAAS;QACPZ;QACAa,aAAaC,SAAS;UACpB;YAAEhB,MAAMW;YAAUE,QAAQL;UAAqB;UAC/C;YAAER,MAAMY;YAAaC,QAAQX;UAAe;SAC7C;;MAEHC,aAAa;QAACc;;MACdZ,WAAW;QACT;UAAEa,SAASC;UAAqBC,UAAUT;QAAS;QACnD;UAAEO,SAASG;UAAoBD,UAAUR;QAAY;;;MAGvDL,SAAS;QAACL;;IACZ;EACF;AACF;;;;","names":["Controller","Get","Query","Sse","subscribe","unsubscribe","channelName","Inject","Injectable","Observable","AGENT_GOVERNANCE_QUERIES","Symbol","for","DASHBOARD_BASE_PATH","DASHBOARD_API_PATH","AGENT_EVENTS","isAgentEnvelope","message","event","DashboardService","queries","spend","range","byModel","byActor","trend","Promise","all","spendByModel","spendByActor","usageTrend","topThreads","limit","spendByThread","recentToolCalls","recentThreads","streamEvents","Observable","subscriber","bindings","map","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","stream","streamEvents","Module","RouterModule","existsSync","readFileSync","basename","extname","join","resolve","sep","fileURLToPath","Controller","Get","Header","Inject","NotFoundException","Param","StreamableFile","BUILD_BASE","spaDir","fileURLToPath","URL","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","normalize","path","replace","AgentApiModule","controllers","AgentApiController","providers","DashboardService","exports","AgentDashboardModule","forRoot","options","basePath","apiBasePath","module","imports","RouterModule","register","AgentUiController","provide","DASHBOARD_BASE_PATH","useValue","DASHBOARD_API_PATH"]}
|