@dudousxd/nestjs-agent-dashboard 0.5.0 → 0.7.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../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":["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"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F,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,aAAab,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":["Body","Controller","Get","Post","Query","Sse","subscribe","unsubscribe","channelName","Inject","Injectable","NotImplementedException","Optional","Observable","BadRequestException","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","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","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/agent-api.controller.ts","../../src/server/dashboard.service.ts","../../src/server/parse-approval-decision.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":["import type {\n ActorResolver,\n CurrentModelPrice,\n PendingApprovalRow,\n RecentRunRow,\n ToolCallActivityRow,\n ToolStatRow,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n Body,\n Controller,\n Get,\n HttpCode,\n Inject,\n Optional,\n Param,\n Post,\n Query,\n Req,\n Sse,\n} 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';\nimport { AGENT_ACTOR_RESOLVER, DASHBOARD_APPROVAL_ACTOR_REF } from './tokens.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(\n private readonly dashboard: DashboardService,\n // `useValue` even when the host omitted `approvalActorRef` — no `@Optional()` needed (the token\n // is always bound; see DASHBOARD_APPROVAL_ACTOR_REF's TSDoc).\n @Inject(DASHBOARD_APPROVAL_ACTOR_REF)\n private readonly approvalActorRef: ((req: unknown) => string | undefined) | undefined,\n // The app's identity seam, bound + exported by the (global) AgentModule — the DEFAULT decider\n // attribution when no `approvalActorRef` override is configured. Genuinely `@Optional()`: the\n // dashboard can be mounted without AgentModule (read-model only), where nothing binds it.\n @Optional()\n @Inject(AGENT_ACTOR_RESOLVER)\n private readonly actorResolver?: ActorResolver,\n ) {}\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 /** Tool calls sitting `pending_approval` (default 50, max 200), oldest first — the approvals inbox. */\n @Get('approvals')\n approvals(@Query('limit') limit?: string): Promise<PendingApprovalRow[]> {\n return this.dashboard.pendingApprovals(parseLimit(limit, 50));\n }\n\n /**\n * Decide a pending HITL tool call. Body `{ approved: boolean; reason?: string }`. 501s (via\n * `DashboardService.decideApproval`) when no `AGENT_APPROVAL_PORT` is bound. `executedByRef`\n * comes from {@link deciderRef} run against the live request.\n */\n @Post('approvals/:toolCallId')\n @HttpCode(204)\n async decideApproval(\n @Param('toolCallId') toolCallId: string,\n @Body() body: unknown,\n @Req() req: unknown,\n ): Promise<void> {\n await this.dashboard.decideApproval(toolCallId, body, await this.deciderRef(req));\n }\n\n /**\n * WHO decided, as an opaque ref: an explicit `approvalActorRef` override wins outright (no\n * resolver fallback, even when it returns `undefined`); otherwise the AgentModule-configured\n * actor resolver — the same identity seam chat requests use. A resolver that throws is an\n * unauthenticated/unreadable request, not an error to surface: the decision itself was already\n * authorized by the dashboard's guards, so the ref is simply omitted.\n */\n private async deciderRef(req: unknown): Promise<string | undefined> {\n if (this.approvalActorRef !== undefined) {\n return this.approvalActorRef(req);\n }\n if (this.actorResolver === undefined) {\n return undefined;\n }\n try {\n return (await this.actorResolver.resolve(req)).id;\n } catch {\n return undefined;\n }\n }\n\n /** Per-tool call/failure/rejection/latency rollup for a day range (defaults to the last 30 days). */\n @Get('tools')\n tools(@Query('from') from?: string, @Query('to') to?: string): Promise<ToolStatRow[]> {\n return this.dashboard.toolStats(resolveRange(from, to));\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 AgentApprovalPort,\n AgentGovernanceQueries,\n AgentPricingStore,\n CurrentModelPrice,\n GovernanceRange,\n ModelSpendRow,\n PendingApprovalRow,\n RecentRunRow,\n RunAgentBreakdownRow,\n RunErrorBreakdownRow,\n RunMetrics,\n RunTrendPoint,\n ThreadActivityRow,\n ThreadSpendRow,\n ToolCallActivityRow,\n ToolStatRow,\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 { parseApprovalDecision } from './parse-approval-decision.js';\nimport { parsePriceInput } from './parse-price-input.js';\nimport {\n AGENT_ACTOR_DIRECTORY,\n AGENT_APPROVAL_PORT,\n AGENT_GOVERNANCE_QUERIES,\n AGENT_PRICING_STORE,\n} 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/** The message returned as a 501 when no `AGENT_APPROVAL_PORT` is bound. */\nconst APPROVAL_PORT_UNBOUND_MESSAGE =\n 'Approve/reject is unavailable: no AGENT_APPROVAL_PORT is bound. Import AgentModule from ' +\n '@dudousxd/nestjs-agent alongside this dashboard to enable it — the approvals inbox stays ' +\n 'read-only until then.';\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 @Optional()\n @Inject(AGENT_APPROVAL_PORT)\n private readonly approvalPort?: AgentApprovalPort,\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 /** Tool calls sitting `pending_approval`, oldest first, for the cross-thread approvals inbox. */\n pendingApprovals(limit: number): Promise<PendingApprovalRow[]> {\n return this.queries.pendingApprovals(limit);\n }\n\n /** Per-tool call/failure/rejection/latency rollup for a day range, for the Tools section. */\n toolStats(range: GovernanceRange): Promise<ToolStatRow[]> {\n return this.queries.toolStats(range);\n }\n\n /**\n * Decide a pending HITL tool call from the console. Routes through the OPTIONAL\n * {@link AGENT_APPROVAL_PORT} — bound by `@dudousxd/nestjs-agent` to the SAME signal path chat\n * approvals use — so a 501 here (checked BEFORE body validation, same ordering as\n * {@link upsertPrice}) means \"no approval port bound\", not \"your body was invalid\". `executedByRef`\n * is an OPAQUE decider ref the caller resolved from the live request (see\n * `AgentDashboardOptions.approvalActorRef`); omitted when the host didn't configure one.\n */\n async decideApproval(\n toolCallId: string,\n body: unknown,\n executedByRef: string | undefined,\n ): Promise<void> {\n if (this.approvalPort === undefined) {\n throw new NotImplementedException(APPROVAL_PORT_UNBOUND_MESSAGE);\n }\n const decision = parseApprovalDecision(body);\n const opts = executedByRef !== undefined ? { executedByRef } : {};\n if (decision.approved) {\n await this.approvalPort.approve(toolCallId, opts);\n return;\n }\n await this.approvalPort.reject(toolCallId, {\n ...opts,\n ...(decision.reason !== undefined ? { reason: decision.reason } : {}),\n });\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 { BadRequestException } from '@nestjs/common';\n\n/** The parsed, minimally-validated `POST <api>/approvals/:toolCallId` body. */\nexport interface ApprovalDecisionInput {\n approved: boolean;\n reason?: string;\n}\n\n/**\n * Minimal shape guard for a `POST <api>/approvals/:toolCallId` body — rejects junk before it reaches\n * `AgentApprovalPort.approve`/`reject`. Mirrors `parsePriceInput`'s role for the pricing endpoint.\n */\nexport function parseApprovalDecision(body: unknown): ApprovalDecisionInput {\n if (typeof body !== 'object' || body === null) {\n throw new BadRequestException('Expected a JSON object body.');\n }\n const { approved, reason } = body as Record<string, unknown>;\n\n if (typeof approved !== 'boolean') {\n throw new BadRequestException('\"approved\" must be a boolean.');\n }\n if (reason !== undefined && typeof reason !== 'string') {\n throw new BadRequestException('\"reason\" must be a string when present.');\n }\n\n return { approved, ...(reason !== undefined ? { reason } : {}) };\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/**\n * Console-side HITL decisions (`AgentApprovalPort`), owned by `@dudousxd/nestjs-agent-core`.\n * Re-declared here BY VALUE for the same reason as {@link AGENT_GOVERNANCE_QUERIES} above. Optional:\n * bound by `@dudousxd/nestjs-agent` (which adapts it to the same signal path chat approvals use) —\n * absent, `POST <api>/approvals/:toolCallId` 501s and the approvals inbox renders read-only.\n */\nexport const AGENT_APPROVAL_PORT = Symbol.for('@dudousxd/nestjs-agent:approval-port');\n\n/**\n * The app's request-identity seam (`ActorResolver`), owned by `@dudousxd/nestjs-agent-core` and\n * bound + exported by the (global) `AgentModule` from the host's `actorResolver` option. Re-declared\n * here BY VALUE for the same reason as {@link AGENT_GOVERNANCE_QUERIES} above. Optional: the default\n * decider attribution for `POST <api>/approvals/:toolCallId` — absent (or throwing, i.e.\n * unauthenticated), `executedByRef` is simply omitted.\n */\nexport const AGENT_ACTOR_RESOLVER = Symbol.for('@dudousxd/nestjs-agent:actor-resolver');\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/**\n * DI token carrying the host-provided {@link AgentDashboardOptions.approvalActorRef} extractor (or\n * `undefined` when the host didn't set one — the controller then falls back to\n * {@link AGENT_ACTOR_RESOLVER} for decider attribution). Threaded to `AgentApiModule` (where the API\n * controller actually lives) same as the pattern above — `useValue` even when `undefined`, so\n * injecting it needs no `@Optional()` (mirrors `AGENT_QUOTA_STORE`'s factory in\n * `@dudousxd/nestjs-agent`).\n */\nexport const DASHBOARD_APPROVAL_ACTOR_REF = Symbol.for(\n '@dudousxd/nestjs-agent-dashboard:approval-actor-ref',\n);\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_APPROVAL_ACTOR_REF, 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\n/**\n * `TReq` mirrors core's `ActorResolver<TReq>` convention: the transport request type\n * {@link AgentDashboardOptions.approvalActorRef} receives. Defaults to `unknown` so untyped usage\n * compiles unchanged; a host may narrow it (e.g. `forRoot<Request>({ approvalActorRef: ... })`)\n * instead of writing its own `unknown`-narrowing type guard.\n */\nexport interface AgentDashboardOptions<TReq = unknown> {\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 * OVERRIDE for WHO is deciding a HITL approval — invoked on the incoming\n * `POST <api>/approvals/:toolCallId` request to stamp `AgentApprovalPort`'s `opts.executedByRef`.\n *\n * DEFAULT (option omitted): the AgentModule-configured actor resolver (`AGENT_ACTOR_RESOLVER`) is\n * consulted — the same identity seam chat requests use — and its actor id becomes the decider ref\n * (a throwing resolver, i.e. an unauthenticated request, just omits the ref). Set this only when\n * console auth differs from chat auth (e.g. the console sits behind a separate SSO whose principal\n * the chat resolver can't read); returning `undefined` leaves `executedByRef` unset — the explicit\n * override wins outright, with no resolver fallback.\n */\n approvalActorRef?: (req: TReq) => string | undefined;\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<TReq = unknown>(options: {\n imports?: DynamicModule['imports'];\n guards?: Type<CanActivate>[];\n approvalActorRef?: (req: TReq) => string | undefined;\n }): DynamicModule {\n return {\n module: AgentApiModule,\n imports: [...(options.imports ?? [])],\n controllers: [AgentApiController],\n providers: [\n DashboardService,\n ...(options.guards ?? []),\n // `useValue` even when `options.approvalActorRef` is `undefined` — AgentApiController\n // injects this WITHOUT `@Optional()` (same pattern as `AGENT_QUOTA_STORE`'s factory).\n { provide: DASHBOARD_APPROVAL_ACTOR_REF, useValue: options.approvalActorRef },\n ],\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 * Inertia hosts: the console is a full-page app, not an Inertia page. An in-app `<Link>` visit to\n * `basePath` (an XHR carrying `X-Inertia`) is bounced with the protocol's own external-redirect\n * mechanism — `409 Conflict` + `X-Inertia-Location: <the visited URL>` — so the Inertia client\n * performs a full `window.location` load and the console renders normally. In-app links to the\n * console therefore just work; no host-side special-casing needed.\n */\n@Module({})\nexport class AgentDashboardModule {\n static forRoot<TReq = unknown>(options: AgentDashboardOptions<TReq> = {}): 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 ...(options.approvalActorRef ? { approvalActorRef: options.approvalActorRef } : {}),\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 Req,\n Res,\n StreamableFile,\n} from '@nestjs/common';\nimport { DASHBOARD_API_PATH, DASHBOARD_BASE_PATH } from './tokens.js';\n\n/**\n * The slice of the express request the Inertia bounce below reads — structural, so the package\n * needs no express dependency (the API controller similarly takes `@Req() req: unknown`).\n */\ninterface UiPageRequest {\n headers: Record<string, string | string[] | undefined>;\n /** Path + query as received (express `originalUrl`) — what the full-page visit must reload. */\n originalUrl: string;\n}\n\n/** The slice of the express response the Inertia bounce writes (passthrough mode — Nest still sends). */\ninterface UiPageResponse {\n status(code: number): unknown;\n setHeader(name: string, value: string): unknown;\n}\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(@Req() req: UiPageRequest, @Res({ passthrough: true }) res: UiPageResponse): string {\n // An Inertia <Link> in the host app visits this page route as an XHR expecting an Inertia JSON\n // page object; serving the SPA's HTML instead lands it in the Inertia client's `srcdoc` error\n // modal, where the page's relative asset URLs die on CORS (origin null). The protocol's own\n // escape hatch for \"this URL is not an Inertia page\" is a 409 Conflict carrying\n // `X-Inertia-Location`: the client responds with a full `window.location` visit, which renders\n // the console normally. Only HTML page routes need this — asset binaries are never fetched with\n // the header.\n if (req.headers['x-inertia'] !== undefined) {\n res.status(409);\n res.setHeader('X-Inertia-Location', req.originalUrl);\n return '';\n }\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":";;;;AAQA,SACEA,MACAC,YACAC,KACAC,UACAC,UAAAA,SACAC,YAAAA,WACAC,OACAC,MACAC,OACAC,KACAC,WACK;;;ACpBP,SAASC,WAAWC,mBAAmB;AAqBvC,SAASC,mBAAmB;AAC5B,SAASC,QAAQC,YAAYC,yBAAyBC,gBAAgB;AACtE,SAASC,cAAAA,mBAAkB;;;ACvB3B,SAASC,2BAA2B;AAY7B,SAASC,sBAAsBC,MAAa;AACjD,MAAI,OAAOA,SAAS,YAAYA,SAAS,MAAM;AAC7C,UAAM,IAAIC,oBAAoB,8BAAA;EAChC;AACA,QAAM,EAAEC,UAAUC,OAAM,IAAKH;AAE7B,MAAI,OAAOE,aAAa,WAAW;AACjC,UAAM,IAAID,oBAAoB,+BAAA;EAChC;AACA,MAAIE,WAAWC,UAAa,OAAOD,WAAW,UAAU;AACtD,UAAM,IAAIF,oBAAoB,yCAAA;EAChC;AAEA,SAAO;IAAEC;IAAU,GAAIC,WAAWC,SAAY;MAAED;IAAO,IAAI,CAAC;EAAG;AACjE;AAdgBJ;;;ACXhB,SAASM,uBAAAA,4BAA2B;AAO7B,SAASC,gBAAgBC,MAAa;AAC3C,MAAI,OAAOA,SAAS,YAAYA,SAAS,MAAM;AAC7C,UAAM,IAAIC,qBAAoB,8BAAA;EAChC;AACA,QAAM,EAAEC,SAASC,iBAAiBC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AAA;AAC/C,UAAMC,cAAczB,UAAUW,QAAQc,eAAe,GAAGD,QAAAA,MAAc;AACtErB,gBAAYQ,QAAQP,QAAQU,oBAAoBY,iBAAAA;AAChD,WAAO;MACLd,QAAQU;MACRT,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;UACnD,GAAIO,QAAQS,mBAAmB;YAAEA,kBAAkBT,QAAQS;UAAiB,IAAI,CAAC;QACnF,CAAA;QACAO,aAAajB,SAAS;UACpB;YAAET,MAAMuB;YAAUZ,QAAQU;UAAqB;UAC/C;YAAErB,MAAMwB;YAAab,QAAQH;UAAe;SAC7C;;MAEHJ,aAAa;QAACqB;;MACdX,WAAW;QACT;UAAEE,SAASW;UAAqBT,UAAUK;QAAS;QACnD;UAAEP,SAASY;UAAoBV,UAAUM;QAAY;;WAEjDd,QAAQP,UAAU,CAAA;;;MAGxBiB,SAAS;QAACZ;;IACZ;EACF;AACF;;;;","names":["Body","Controller","Get","HttpCode","Inject","Optional","Param","Post","Query","Req","Sse","subscribe","unsubscribe","channelName","Inject","Injectable","NotImplementedException","Optional","Observable","BadRequestException","parseApprovalDecision","body","BadRequestException","approved","reason","undefined","BadRequestException","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","AGENT_APPROVAL_PORT","AGENT_ACTOR_RESOLVER","DASHBOARD_BASE_PATH","DASHBOARD_API_PATH","DASHBOARD_APPROVAL_ACTOR_REF","PRICING_STORE_UNBOUND_MESSAGE","APPROVAL_PORT_UNBOUND_MESSAGE","AGENT_EVENTS","isAgentEnvelope","message","event","DashboardService","queries","actorDirectory","pricingStore","approvalPort","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","pendingApprovals","toolStats","decideApproval","toolCallId","body","executedByRef","undefined","NotImplementedException","decision","parseApprovalDecision","opts","approved","approve","reject","reason","recentThreads","length","map","row","actorLabel","refs","Set","actorRef","resolved","resolveDisplay","listPrices","listCurrentPrices","upsertPrice","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","approvalActorRef","actorResolver","spend","topThreads","limit","reliability","runs","recentRuns","toolCalls","recentToolCalls","approvals","pendingApprovals","decideApproval","toolCallId","body","req","deciderRef","resolve","id","tools","toolStats","threads","recentThreads","listPrices","upsertPrice","stream","streamEvents","normalizeDashboardPath","path","replace","unprefixed","path","replace","agentDashboardMountPaths","options","basePath","normalizeDashboardPath","apiBasePath","base","api","Module","RouterModule","existsSync","readFileSync","basename","extname","join","resolve","sep","fileURLToPath","Controller","Get","Header","Inject","NotFoundException","Param","Req","Res","StreamableFile","BUILD_BASE","spaDir","fileURLToPath","URL","url","CONTENT_TYPES","AgentUiController","dir","basePath","apiBasePath","index","req","res","headers","undefined","status","setHeader","originalUrl","indexPath","join","existsSync","NotFoundException","html","readFileSync","replaceAll","inject","includes","replace","asset","file","safe","basename","root","resolve","assetPath","startsWith","sep","type","extname","StreamableFile","passthrough","GUARDS_METADATA","normalize","path","normalizeDashboardPath","stampGuards","guards","controllers","controller","Reflect","defineMetadata","AgentApiModule","register","options","module","imports","AgentApiController","providers","DashboardService","provide","DASHBOARD_APPROVAL_ACTOR_REF","useValue","approvalActorRef","exports","AgentDashboardModule","forRoot","basePath","apiBasePath","AgentUiController","RouterModule","DASHBOARD_BASE_PATH","DASHBOARD_API_PATH"]}
@@ -0,0 +1 @@
1
+ var be=e=>{throw TypeError(e)};var Xt=(e,t,s)=>t.has(e)||be("Cannot "+s);var i=(e,t,s)=>(Xt(e,t,"read from private field"),s?s.call(e):t.get(e)),d=(e,t,s)=>t.has(e)?be("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,s),u=(e,t,s,r)=>(Xt(e,t,"write to private field"),r?r.call(e,s):t.set(e,s),s),m=(e,t,s)=>(Xt(e,t,"access private method"),s);var Gt=(e,t,s,r)=>({set _(n){u(e,t,n,s)},get _(){return i(e,t,r)}});import{r as O,j as p,p as rs,L as is,D as ns,C as as,U as os,W as ge,S as us,I as cs,T as hs,A as ls,a as ds,P as fs,b as ps,c as ys,R as ms,d as vs,e as bs,M as gs,f as Ss,g as ws}from"./index-CES4RqI4.js";var Ut=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},gt=typeof window>"u"||"Deno"in globalThis;function K(){}function xs(e,t){return typeof e=="function"?e(t):e}function te(e){return typeof e=="number"&&e>=0&&e!==1/0}function $e(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ct(e,t){return typeof e=="function"?e(t):e}function B(e,t){return typeof e=="function"?e(t):e}function Se(e,t){const{type:s="all",exact:r,fetchStatus:n,predicate:a,queryKey:o,stale:c}=e;if(o){if(r){if(t.queryHash!==pe(o,t.options))return!1}else if(!Lt(t.queryKey,o))return!1}if(s!=="all"){const l=t.isActive();if(s==="active"&&!l||s==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||n&&n!==t.state.fetchStatus||a&&!a(t))}function we(e,t){const{exact:s,status:r,predicate:n,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(s){if(St(t.options.mutationKey)!==St(a))return!1}else if(!Lt(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||n&&!n(t))}function pe(e,t){return((t==null?void 0:t.queryKeyHashFn)||St)(e)}function St(e){return JSON.stringify(e,(t,s)=>ee(s)?Object.keys(s).sort().reduce((r,n)=>(r[n]=s[n],r),{}):s)}function Lt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(s=>!Lt(e[s],t[s])):!1}function He(e,t){if(e===t)return e;const s=xe(e)&&xe(t);if(s||ee(e)&&ee(t)){const r=s?e:Object.keys(e),n=r.length,a=s?t:Object.keys(t),o=a.length,c=s?[]:{};let l=0;for(let g=0;g<o;g++){const y=s?g:a[g];(!s&&r.includes(y)||s)&&e[y]===void 0&&t[y]===void 0?(c[y]=void 0,l++):(c[y]=He(e[y],t[y]),c[y]===e[y]&&e[y]!==void 0&&l++)}return n===o&&l===n?e:c}return t}function Wt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}function xe(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ee(e){if(!Ce(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!Ce(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Ce(e){return Object.prototype.toString.call(e)==="[object Object]"}function Cs(e){return new Promise(t=>{setTimeout(t,e)})}function se(e,t,s){return typeof s.structuralSharing=="function"?s.structuralSharing(e,t):s.structuralSharing!==!1?He(e,t):t}function Ps(e,t,s=0){const r=[...e,t];return s&&r.length>s?r.slice(1):r}function Rs(e,t,s=0){const r=[t,...e];return s&&r.length>s?r.slice(0,-1):r}var ye=Symbol();function Ge(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===ye?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var dt,rt,Pt,Me,Os=(Me=class extends Ut{constructor(){super();d(this,dt);d(this,rt);d(this,Pt);u(this,Pt,t=>{if(!gt&&window.addEventListener){const s=()=>t();return window.addEventListener("visibilitychange",s,!1),()=>{window.removeEventListener("visibilitychange",s)}}})}onSubscribe(){i(this,rt)||this.setEventListener(i(this,Pt))}onUnsubscribe(){var t;this.hasListeners()||((t=i(this,rt))==null||t.call(this),u(this,rt,void 0))}setEventListener(t){var s;u(this,Pt,t),(s=i(this,rt))==null||s.call(this),u(this,rt,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){i(this,dt)!==t&&(u(this,dt,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(s=>{s(t)})}isFocused(){var t;return typeof i(this,dt)=="boolean"?i(this,dt):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},dt=new WeakMap,rt=new WeakMap,Pt=new WeakMap,Me),me=new Os,Rt,it,Ot,Ie,Es=(Ie=class extends Ut{constructor(){super();d(this,Rt,!0);d(this,it);d(this,Ot);u(this,Ot,t=>{if(!gt&&window.addEventListener){const s=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",s,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",s),window.removeEventListener("offline",r)}}})}onSubscribe(){i(this,it)||this.setEventListener(i(this,Ot))}onUnsubscribe(){var t;this.hasListeners()||((t=i(this,it))==null||t.call(this),u(this,it,void 0))}setEventListener(t){var s;u(this,Ot,t),(s=i(this,it))==null||s.call(this),u(this,it,t(this.setOnline.bind(this)))}setOnline(t){i(this,Rt)!==t&&(u(this,Rt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return i(this,Rt)}},Rt=new WeakMap,it=new WeakMap,Ot=new WeakMap,Ie),Vt=new Es;function re(){let e,t;const s=new Promise((n,a)=>{e=n,t=a});s.status="pending",s.catch(()=>{});function r(n){Object.assign(s,n),delete s.resolve,delete s.reject}return s.resolve=n=>{r({status:"fulfilled",value:n}),e(n)},s.reject=n=>{r({status:"rejected",reason:n}),t(n)},s}function Ds(e){return Math.min(1e3*2**e,3e4)}function Be(e){return(e??"online")==="online"?Vt.isOnline():!0}var Ye=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function Zt(e){return e instanceof Ye}function ze(e){let t=!1,s=0,r=!1,n;const a=re(),o=f=>{var b;r||(S(new Ye(f)),(b=e.abort)==null||b.call(e))},c=()=>{t=!0},l=()=>{t=!1},g=()=>me.isFocused()&&(e.networkMode==="always"||Vt.isOnline())&&e.canRun(),y=()=>Be(e.networkMode)&&e.canRun(),h=f=>{var b;r||(r=!0,(b=e.onSuccess)==null||b.call(e,f),n==null||n(),a.resolve(f))},S=f=>{var b;r||(r=!0,(b=e.onError)==null||b.call(e,f),n==null||n(),a.reject(f))},v=()=>new Promise(f=>{var b;n=D=>{(r||g())&&f(D)},(b=e.onPause)==null||b.call(e)}).then(()=>{var f;n=void 0,r||(f=e.onContinue)==null||f.call(e)}),R=()=>{if(r)return;let f;const b=s===0?e.initialPromise:void 0;try{f=b??e.fn()}catch(D){f=Promise.reject(D)}Promise.resolve(f).then(h).catch(D=>{var H;if(r)return;const C=e.retry??(gt?0:3),P=e.retryDelay??Ds,j=typeof P=="function"?P(s,D):P,L=C===!0||typeof C=="number"&&s<C||typeof C=="function"&&C(s,D);if(t||!L){S(D);return}s++,(H=e.onFail)==null||H.call(e,s,D),Cs(j).then(()=>g()?void 0:v()).then(()=>{t?S(D):R()})})};return{promise:a,cancel:o,continue:()=>(n==null||n(),a),cancelRetry:c,continueRetry:l,canStart:y,start:()=>(y()?R():v().then(R),a)}}function Fs(){let e=[],t=0,s=c=>{c()},r=c=>{c()},n=c=>setTimeout(c,0);const a=c=>{t?e.push(c):n(()=>{s(c)})},o=()=>{const c=e;e=[],c.length&&n(()=>{r(()=>{c.forEach(l=>{s(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||o()}return l},batchCalls:c=>(...l)=>{a(()=>{c(...l)})},schedule:a,setNotifyFunction:c=>{s=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{n=c}}}var A=Fs(),ft,Qe,We=(Qe=class{constructor(){d(this,ft)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),te(this.gcTime)&&u(this,ft,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(gt?1/0:5*60*1e3))}clearGcTimeout(){i(this,ft)&&(clearTimeout(i(this,ft)),u(this,ft,void 0))}},ft=new WeakMap,Qe),Et,Dt,N,M,_t,pt,G,X,qe,Ts=(qe=class extends We{constructor(t){super();d(this,G);d(this,Et);d(this,Dt);d(this,N);d(this,M);d(this,_t);d(this,pt);u(this,pt,!1),u(this,_t,t.defaultOptions),this.setOptions(t.options),this.observers=[],u(this,N,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,u(this,Et,As(this.options)),this.state=t.state??i(this,Et),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=i(this,M))==null?void 0:t.promise}setOptions(t){this.options={...i(this,_t),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&i(this,N).remove(this)}setData(t,s){const r=se(this.state.data,t,this.options);return m(this,G,X).call(this,{data:r,type:"success",dataUpdatedAt:s==null?void 0:s.updatedAt,manual:s==null?void 0:s.manual}),r}setState(t,s){m(this,G,X).call(this,{type:"setState",state:t,setStateOptions:s})}cancel(t){var r,n;const s=(r=i(this,M))==null?void 0:r.promise;return(n=i(this,M))==null||n.cancel(t),s?s.then(K).catch(K):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(i(this,Et))}isActive(){return this.observers.some(t=>B(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ye||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(t=0){return this.state.isInvalidated||this.state.data===void 0||!$e(this.state.dataUpdatedAt,t)}onFocus(){var s;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(s=i(this,M))==null||s.continue()}onOnline(){var s;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(s=i(this,M))==null||s.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),i(this,N).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(s=>s!==t),this.observers.length||(i(this,M)&&(i(this,pt)?i(this,M).cancel({revert:!0}):i(this,M).cancelRetry()),this.scheduleGc()),i(this,N).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||m(this,G,X).call(this,{type:"invalidate"})}fetch(t,s){var l,g,y;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(s!=null&&s.cancelRefetch))this.cancel({silent:!0});else if(i(this,M))return i(this,M).continueRetry(),i(this,M).promise}if(t&&this.setOptions(t),!this.options.queryFn){const h=this.observers.find(S=>S.options.queryFn);h&&this.setOptions(h.options)}const r=new AbortController,n=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(u(this,pt,!0),r.signal)})},a=()=>{const h=Ge(this.options,s),S={queryKey:this.queryKey,meta:this.meta};return n(S),u(this,pt,!1),this.options.persister?this.options.persister(h,S,this):h(S)},o={fetchOptions:s,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:a};n(o),(l=this.options.behavior)==null||l.onFetch(o,this),u(this,Dt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((g=o.fetchOptions)==null?void 0:g.meta))&&m(this,G,X).call(this,{type:"fetch",meta:(y=o.fetchOptions)==null?void 0:y.meta});const c=h=>{var S,v,R,f;Zt(h)&&h.silent||m(this,G,X).call(this,{type:"error",error:h}),Zt(h)||((v=(S=i(this,N).config).onError)==null||v.call(S,h,this),(f=(R=i(this,N).config).onSettled)==null||f.call(R,this.state.data,h,this)),this.scheduleGc()};return u(this,M,ze({initialPromise:s==null?void 0:s.initialPromise,fn:o.fetchFn,abort:r.abort.bind(r),onSuccess:h=>{var S,v,R,f;if(h===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(h)}catch(b){c(b);return}(v=(S=i(this,N).config).onSuccess)==null||v.call(S,h,this),(f=(R=i(this,N).config).onSettled)==null||f.call(R,h,this.state.error,this),this.scheduleGc()},onError:c,onFail:(h,S)=>{m(this,G,X).call(this,{type:"failed",failureCount:h,error:S})},onPause:()=>{m(this,G,X).call(this,{type:"pause"})},onContinue:()=>{m(this,G,X).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),i(this,M).start()}},Et=new WeakMap,Dt=new WeakMap,N=new WeakMap,M=new WeakMap,_t=new WeakMap,pt=new WeakMap,G=new WeakSet,X=function(t){const s=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Ve(r.data,this.options),fetchMeta:t.meta??null};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const n=t.error;return Zt(n)&&n.revert&&i(this,Dt)?{...i(this,Dt),fetchStatus:"idle"}:{...r,error:n,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:n,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=s(this.state),A.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),i(this,N).notify({query:this,type:"updated",action:t})})},qe);function Ve(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Be(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function As(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,s=t!==void 0,r=s?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var Y,Ue,js=(Ue=class extends Ut{constructor(t={}){super();d(this,Y);this.config=t,u(this,Y,new Map)}build(t,s,r){const n=s.queryKey,a=s.queryHash??pe(n,s);let o=this.get(a);return o||(o=new Ts({cache:this,queryKey:n,queryHash:a,options:t.defaultQueryOptions(s),state:r,defaultOptions:t.getQueryDefaults(n)}),this.add(o)),o}add(t){i(this,Y).has(t.queryHash)||(i(this,Y).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const s=i(this,Y).get(t.queryHash);s&&(t.destroy(),s===t&&i(this,Y).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){A.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return i(this,Y).get(t)}getAll(){return[...i(this,Y).values()]}find(t){const s={exact:!0,...t};return this.getAll().find(r=>Se(s,r))}findAll(t={}){const s=this.getAll();return Object.keys(t).length>0?s.filter(r=>Se(t,r)):s}notify(t){A.batch(()=>{this.listeners.forEach(s=>{s(t)})})}onFocus(){A.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){A.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Y=new WeakMap,Ue),z,Q,yt,W,st,ke,Ms=(ke=class extends We{constructor(t){super();d(this,W);d(this,z);d(this,Q);d(this,yt);this.mutationId=t.mutationId,u(this,Q,t.mutationCache),u(this,z,[]),this.state=t.state||Je(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){i(this,z).includes(t)||(i(this,z).push(t),this.clearGcTimeout(),i(this,Q).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){u(this,z,i(this,z).filter(s=>s!==t)),this.scheduleGc(),i(this,Q).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){i(this,z).length||(this.state.status==="pending"?this.scheduleGc():i(this,Q).remove(this))}continue(){var t;return((t=i(this,yt))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var n,a,o,c,l,g,y,h,S,v,R,f,b,D,C,P,j,L,H,I;u(this,yt,ze({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(T,E)=>{m(this,W,st).call(this,{type:"failed",failureCount:T,error:E})},onPause:()=>{m(this,W,st).call(this,{type:"pause"})},onContinue:()=>{m(this,W,st).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>i(this,Q).canRun(this)}));const s=this.state.status==="pending",r=!i(this,yt).canStart();try{if(!s){m(this,W,st).call(this,{type:"pending",variables:t,isPaused:r}),await((a=(n=i(this,Q).config).onMutate)==null?void 0:a.call(n,t,this));const E=await((c=(o=this.options).onMutate)==null?void 0:c.call(o,t));E!==this.state.context&&m(this,W,st).call(this,{type:"pending",context:E,variables:t,isPaused:r})}const T=await i(this,yt).start();return await((g=(l=i(this,Q).config).onSuccess)==null?void 0:g.call(l,T,t,this.state.context,this)),await((h=(y=this.options).onSuccess)==null?void 0:h.call(y,T,t,this.state.context)),await((v=(S=i(this,Q).config).onSettled)==null?void 0:v.call(S,T,null,this.state.variables,this.state.context,this)),await((f=(R=this.options).onSettled)==null?void 0:f.call(R,T,null,t,this.state.context)),m(this,W,st).call(this,{type:"success",data:T}),T}catch(T){try{throw await((D=(b=i(this,Q).config).onError)==null?void 0:D.call(b,T,t,this.state.context,this)),await((P=(C=this.options).onError)==null?void 0:P.call(C,T,t,this.state.context)),await((L=(j=i(this,Q).config).onSettled)==null?void 0:L.call(j,void 0,T,this.state.variables,this.state.context,this)),await((I=(H=this.options).onSettled)==null?void 0:I.call(H,void 0,T,t,this.state.context)),T}finally{m(this,W,st).call(this,{type:"error",error:T})}}finally{i(this,Q).runNext(this)}}},z=new WeakMap,Q=new WeakMap,yt=new WeakMap,W=new WeakSet,st=function(t){const s=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=s(this.state),A.batch(()=>{i(this,z).forEach(r=>{r.onMutationUpdate(t)}),i(this,Q).notify({mutation:this,type:"updated",action:t})})},ke);function Je(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var _,Nt,Le,Is=(Le=class extends Ut{constructor(t={}){super();d(this,_);d(this,Nt);this.config=t,u(this,_,new Map),u(this,Nt,Date.now())}build(t,s,r){const n=new Ms({mutationCache:this,mutationId:++Gt(this,Nt)._,options:t.defaultMutationOptions(s),state:r});return this.add(n),n}add(t){const s=Bt(t),r=i(this,_).get(s)??[];r.push(t),i(this,_).set(s,r),this.notify({type:"added",mutation:t})}remove(t){var r;const s=Bt(t);if(i(this,_).has(s)){const n=(r=i(this,_).get(s))==null?void 0:r.filter(a=>a!==t);n&&(n.length===0?i(this,_).delete(s):i(this,_).set(s,n))}this.notify({type:"removed",mutation:t})}canRun(t){var r;const s=(r=i(this,_).get(Bt(t)))==null?void 0:r.find(n=>n.state.status==="pending");return!s||s===t}runNext(t){var r;const s=(r=i(this,_).get(Bt(t)))==null?void 0:r.find(n=>n!==t&&n.state.isPaused);return(s==null?void 0:s.continue())??Promise.resolve()}clear(){A.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}getAll(){return[...i(this,_).values()].flat()}find(t){const s={exact:!0,...t};return this.getAll().find(r=>we(s,r))}findAll(t={}){return this.getAll().filter(s=>we(t,s))}notify(t){A.batch(()=>{this.listeners.forEach(s=>{s(t)})})}resumePausedMutations(){const t=this.getAll().filter(s=>s.state.isPaused);return A.batch(()=>Promise.all(t.map(s=>s.continue().catch(K))))}},_=new WeakMap,Nt=new WeakMap,Le);function Bt(e){var t;return((t=e.options.scope)==null?void 0:t.id)??String(e.mutationId)}function Pe(e){return{onFetch:(t,s)=>{var y,h,S,v,R;const r=t.options,n=(S=(h=(y=t.fetchOptions)==null?void 0:y.meta)==null?void 0:h.fetchMore)==null?void 0:S.direction,a=((v=t.state.data)==null?void 0:v.pages)||[],o=((R=t.state.data)==null?void 0:R.pageParams)||[];let c={pages:[],pageParams:[]},l=0;const g=async()=>{let f=!1;const b=P=>{Object.defineProperty(P,"signal",{enumerable:!0,get:()=>(t.signal.aborted?f=!0:t.signal.addEventListener("abort",()=>{f=!0}),t.signal)})},D=Ge(t.options,t.fetchOptions),C=async(P,j,L)=>{if(f)return Promise.reject();if(j==null&&P.pages.length)return Promise.resolve(P);const H={queryKey:t.queryKey,pageParam:j,direction:L?"backward":"forward",meta:t.options.meta};b(H);const I=await D(H),{maxPages:T}=t.options,E=L?Rs:Ps;return{pages:E(P.pages,I,T),pageParams:E(P.pageParams,j,T)}};if(n&&a.length){const P=n==="backward",j=P?Qs:Re,L={pages:a,pageParams:o},H=j(r,L);c=await C(L,H,P)}else{const P=e??a.length;do{const j=l===0?o[0]??r.initialPageParam:Re(r,c);if(l>0&&j==null)break;c=await C(c,j),l++}while(l<P)}return c};t.options.persister?t.fetchFn=()=>{var f,b;return(b=(f=t.options).persister)==null?void 0:b.call(f,g,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},s)}:t.fetchFn=g}}}function Re(e,{pages:t,pageParams:s}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,s[r],s):void 0}function Qs(e,{pages:t,pageParams:s}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,s[0],s):void 0}var F,nt,at,Ft,Tt,ot,At,jt,_e,qs=(_e=class{constructor(e={}){d(this,F);d(this,nt);d(this,at);d(this,Ft);d(this,Tt);d(this,ot);d(this,At);d(this,jt);u(this,F,e.queryCache||new js),u(this,nt,e.mutationCache||new Is),u(this,at,e.defaultOptions||{}),u(this,Ft,new Map),u(this,Tt,new Map),u(this,ot,0)}mount(){Gt(this,ot)._++,i(this,ot)===1&&(u(this,At,me.subscribe(async e=>{e&&(await this.resumePausedMutations(),i(this,F).onFocus())})),u(this,jt,Vt.subscribe(async e=>{e&&(await this.resumePausedMutations(),i(this,F).onOnline())})))}unmount(){var e,t;Gt(this,ot)._--,i(this,ot)===0&&((e=i(this,At))==null||e.call(this),u(this,At,void 0),(t=i(this,jt))==null||t.call(this),u(this,jt,void 0))}isFetching(e){return i(this,F).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return i(this,nt).findAll({...e,status:"pending"}).length}getQueryData(e){var s;const t=this.defaultQueryOptions({queryKey:e});return(s=i(this,F).get(t.queryHash))==null?void 0:s.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),s=i(this,F).build(this,t),r=s.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&s.isStaleByTime(Ct(t.staleTime,s))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return i(this,F).findAll(e).map(({queryKey:t,state:s})=>{const r=s.data;return[t,r]})}setQueryData(e,t,s){const r=this.defaultQueryOptions({queryKey:e}),n=i(this,F).get(r.queryHash),a=n==null?void 0:n.state.data,o=xs(t,a);if(o!==void 0)return i(this,F).build(this,r).setData(o,{...s,manual:!0})}setQueriesData(e,t,s){return A.batch(()=>i(this,F).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,s)]))}getQueryState(e){var s;const t=this.defaultQueryOptions({queryKey:e});return(s=i(this,F).get(t.queryHash))==null?void 0:s.state}removeQueries(e){const t=i(this,F);A.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=i(this,F),r={type:"active",...e};return A.batch(()=>(s.findAll(e).forEach(n=>{n.reset()}),this.refetchQueries(r,t)))}cancelQueries(e,t={}){const s={revert:!0,...t},r=A.batch(()=>i(this,F).findAll(e).map(n=>n.cancel(s)));return Promise.all(r).then(K).catch(K)}invalidateQueries(e,t={}){return A.batch(()=>{if(i(this,F).findAll(e).forEach(r=>{r.invalidate()}),(e==null?void 0:e.refetchType)==="none")return Promise.resolve();const s={...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"};return this.refetchQueries(s,t)})}refetchQueries(e,t={}){const s={...t,cancelRefetch:t.cancelRefetch??!0},r=A.batch(()=>i(this,F).findAll(e).filter(n=>!n.isDisabled()).map(n=>{let a=n.fetch(void 0,s);return s.throwOnError||(a=a.catch(K)),n.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(K)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=i(this,F).build(this,t);return s.isStaleByTime(Ct(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(K).catch(K)}fetchInfiniteQuery(e){return e.behavior=Pe(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(K).catch(K)}ensureInfiniteQueryData(e){return e.behavior=Pe(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Vt.isOnline()?i(this,nt).resumePausedMutations():Promise.resolve()}getQueryCache(){return i(this,F)}getMutationCache(){return i(this,nt)}getDefaultOptions(){return i(this,at)}setDefaultOptions(e){u(this,at,e)}setQueryDefaults(e,t){i(this,Ft).set(St(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...i(this,Ft).values()],s={};return t.forEach(r=>{Lt(e,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(e,t){i(this,Tt).set(St(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...i(this,Tt).values()];let s={};return t.forEach(r=>{Lt(e,r.mutationKey)&&(s={...s,...r.defaultOptions})}),s}defaultQueryOptions(e){if(e._defaulted)return e;const t={...i(this,at).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=pe(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===ye&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...i(this,at).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){i(this,F).clear(),i(this,nt).clear()}},F=new WeakMap,nt=new WeakMap,at=new WeakMap,Ft=new WeakMap,Tt=new WeakMap,ot=new WeakMap,At=new WeakMap,jt=new WeakMap,_e),U,w,Kt,q,mt,Mt,ut,V,$t,It,Qt,vt,bt,ct,qt,x,kt,ie,ne,ae,oe,ue,ce,he,Xe,Ne,Us=(Ne=class extends Ut{constructor(t,s){super();d(this,x);d(this,U);d(this,w);d(this,Kt);d(this,q);d(this,mt);d(this,Mt);d(this,ut);d(this,V);d(this,$t);d(this,It);d(this,Qt);d(this,vt);d(this,bt);d(this,ct);d(this,qt,new Set);this.options=s,u(this,U,t),u(this,V,null),u(this,ut,re()),this.options.experimental_prefetchInRender||i(this,ut).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(s)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(i(this,w).addObserver(this),Oe(i(this,w),this.options)?m(this,x,kt).call(this):this.updateResult(),m(this,x,oe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return le(i(this,w),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return le(i(this,w),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,m(this,x,ue).call(this),m(this,x,ce).call(this),i(this,w).removeObserver(this)}setOptions(t,s){const r=this.options,n=i(this,w);if(this.options=i(this,U).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof B(this.options.enabled,i(this,w))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");m(this,x,he).call(this),i(this,w).setOptions(this.options),r._defaulted&&!Wt(this.options,r)&&i(this,U).getQueryCache().notify({type:"observerOptionsUpdated",query:i(this,w),observer:this});const a=this.hasListeners();a&&Ee(i(this,w),n,this.options,r)&&m(this,x,kt).call(this),this.updateResult(s),a&&(i(this,w)!==n||B(this.options.enabled,i(this,w))!==B(r.enabled,i(this,w))||Ct(this.options.staleTime,i(this,w))!==Ct(r.staleTime,i(this,w)))&&m(this,x,ie).call(this);const o=m(this,x,ne).call(this);a&&(i(this,w)!==n||B(this.options.enabled,i(this,w))!==B(r.enabled,i(this,w))||o!==i(this,ct))&&m(this,x,ae).call(this,o)}getOptimisticResult(t){const s=i(this,U).getQueryCache().build(i(this,U),t),r=this.createResult(s,t);return Ls(this,r)&&(u(this,q,r),u(this,Mt,this.options),u(this,mt,i(this,w).state)),r}getCurrentResult(){return i(this,q)}trackResult(t,s){const r={};return Object.keys(t).forEach(n=>{Object.defineProperty(r,n,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(n),s==null||s(n),t[n])})}),r}trackProp(t){i(this,qt).add(t)}getCurrentQuery(){return i(this,w)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const s=i(this,U).defaultQueryOptions(t),r=i(this,U).getQueryCache().build(i(this,U),s);return r.fetch().then(()=>this.createResult(r,s))}fetch(t){return m(this,x,kt).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),i(this,q)))}createResult(t,s){var T;const r=i(this,w),n=this.options,a=i(this,q),o=i(this,mt),c=i(this,Mt),g=t!==r?t.state:i(this,Kt),{state:y}=t;let h={...y},S=!1,v;if(s._optimisticResults){const E=this.hasListeners(),wt=!E&&Oe(t,s),xt=E&&Ee(t,r,s,n);(wt||xt)&&(h={...h,...Ve(y.data,t.options)}),s._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:R,errorUpdatedAt:f,status:b}=h;if(s.select&&h.data!==void 0)if(a&&h.data===(o==null?void 0:o.data)&&s.select===i(this,$t))v=i(this,It);else try{u(this,$t,s.select),v=s.select(h.data),v=se(a==null?void 0:a.data,v,s),u(this,It,v),u(this,V,null)}catch(E){u(this,V,E)}else v=h.data;if(s.placeholderData!==void 0&&v===void 0&&b==="pending"){let E;if(a!=null&&a.isPlaceholderData&&s.placeholderData===(c==null?void 0:c.placeholderData))E=a.data;else if(E=typeof s.placeholderData=="function"?s.placeholderData((T=i(this,Qt))==null?void 0:T.state.data,i(this,Qt)):s.placeholderData,s.select&&E!==void 0)try{E=s.select(E),u(this,V,null)}catch(wt){u(this,V,wt)}E!==void 0&&(b="success",v=se(a==null?void 0:a.data,E,s),S=!0)}i(this,V)&&(R=i(this,V),v=i(this,It),f=Date.now(),b="error");const D=h.fetchStatus==="fetching",C=b==="pending",P=b==="error",j=C&&D,L=v!==void 0,I={status:b,fetchStatus:h.fetchStatus,isPending:C,isSuccess:b==="success",isError:P,isInitialLoading:j,isLoading:j,data:v,dataUpdatedAt:h.dataUpdatedAt,error:R,errorUpdatedAt:f,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>g.dataUpdateCount||h.errorUpdateCount>g.errorUpdateCount,isFetching:D,isRefetching:D&&!C,isLoadingError:P&&!L,isPaused:h.fetchStatus==="paused",isPlaceholderData:S,isRefetchError:P&&L,isStale:ve(t,s),refetch:this.refetch,promise:i(this,ut)};if(this.options.experimental_prefetchInRender){const E=Ht=>{I.status==="error"?Ht.reject(I.error):I.data!==void 0&&Ht.resolve(I.data)},wt=()=>{const Ht=u(this,ut,I.promise=re());E(Ht)},xt=i(this,ut);switch(xt.status){case"pending":t.queryHash===r.queryHash&&E(xt);break;case"fulfilled":(I.status==="error"||I.data!==xt.value)&&wt();break;case"rejected":(I.status!=="error"||I.error!==xt.reason)&&wt();break}}return I}updateResult(t){const s=i(this,q),r=this.createResult(i(this,w),this.options);if(u(this,mt,i(this,w).state),u(this,Mt,this.options),i(this,mt).data!==void 0&&u(this,Qt,i(this,w)),Wt(r,s))return;u(this,q,r);const n={},a=()=>{if(!s)return!0;const{notifyOnChangeProps:o}=this.options,c=typeof o=="function"?o():o;if(c==="all"||!c&&!i(this,qt).size)return!0;const l=new Set(c??i(this,qt));return this.options.throwOnError&&l.add("error"),Object.keys(i(this,q)).some(g=>{const y=g;return i(this,q)[y]!==s[y]&&l.has(y)})};(t==null?void 0:t.listeners)!==!1&&a()&&(n.listeners=!0),m(this,x,Xe).call(this,{...n,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&m(this,x,oe).call(this)}},U=new WeakMap,w=new WeakMap,Kt=new WeakMap,q=new WeakMap,mt=new WeakMap,Mt=new WeakMap,ut=new WeakMap,V=new WeakMap,$t=new WeakMap,It=new WeakMap,Qt=new WeakMap,vt=new WeakMap,bt=new WeakMap,ct=new WeakMap,qt=new WeakMap,x=new WeakSet,kt=function(t){m(this,x,he).call(this);let s=i(this,w).fetch(this.options,t);return t!=null&&t.throwOnError||(s=s.catch(K)),s},ie=function(){m(this,x,ue).call(this);const t=Ct(this.options.staleTime,i(this,w));if(gt||i(this,q).isStale||!te(t))return;const r=$e(i(this,q).dataUpdatedAt,t)+1;u(this,vt,setTimeout(()=>{i(this,q).isStale||this.updateResult()},r))},ne=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(i(this,w)):this.options.refetchInterval)??!1},ae=function(t){m(this,x,ce).call(this),u(this,ct,t),!(gt||B(this.options.enabled,i(this,w))===!1||!te(i(this,ct))||i(this,ct)===0)&&u(this,bt,setInterval(()=>{(this.options.refetchIntervalInBackground||me.isFocused())&&m(this,x,kt).call(this)},i(this,ct)))},oe=function(){m(this,x,ie).call(this),m(this,x,ae).call(this,m(this,x,ne).call(this))},ue=function(){i(this,vt)&&(clearTimeout(i(this,vt)),u(this,vt,void 0))},ce=function(){i(this,bt)&&(clearInterval(i(this,bt)),u(this,bt,void 0))},he=function(){const t=i(this,U).getQueryCache().build(i(this,U),this.options);if(t===i(this,w))return;const s=i(this,w);u(this,w,t),u(this,Kt,t.state),this.hasListeners()&&(s==null||s.removeObserver(this),t.addObserver(this))},Xe=function(t){A.batch(()=>{t.listeners&&this.listeners.forEach(s=>{s(i(this,q))}),i(this,U).getQueryCache().notify({query:i(this,w),type:"observerResultsUpdated"})})},Ne);function ks(e,t){return B(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Oe(e,t){return ks(e,t)||e.state.data!==void 0&&le(e,t,t.refetchOnMount)}function le(e,t,s){if(B(t.enabled,e)!==!1){const r=typeof s=="function"?s(e):s;return r==="always"||r!==!1&&ve(e,t)}return!1}function Ee(e,t,s,r){return(e!==t||B(r.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&ve(e,s)}function ve(e,t){return B(t.enabled,e)!==!1&&e.isStaleByTime(Ct(t.staleTime,e))}function Ls(e,t){return!Wt(e.getCurrentResult(),t)}var ht,lt,k,Z,tt,Yt,de,Ke,_s=(Ke=class extends Ut{constructor(t,s){super();d(this,tt);d(this,ht);d(this,lt);d(this,k);d(this,Z);u(this,ht,t),this.setOptions(s),this.bindMethods(),m(this,tt,Yt).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){var r;const s=this.options;this.options=i(this,ht).defaultMutationOptions(t),Wt(this.options,s)||i(this,ht).getMutationCache().notify({type:"observerOptionsUpdated",mutation:i(this,k),observer:this}),s!=null&&s.mutationKey&&this.options.mutationKey&&St(s.mutationKey)!==St(this.options.mutationKey)?this.reset():((r=i(this,k))==null?void 0:r.state.status)==="pending"&&i(this,k).setOptions(this.options)}onUnsubscribe(){var t;this.hasListeners()||(t=i(this,k))==null||t.removeObserver(this)}onMutationUpdate(t){m(this,tt,Yt).call(this),m(this,tt,de).call(this,t)}getCurrentResult(){return i(this,lt)}reset(){var t;(t=i(this,k))==null||t.removeObserver(this),u(this,k,void 0),m(this,tt,Yt).call(this),m(this,tt,de).call(this)}mutate(t,s){var r;return u(this,Z,s),(r=i(this,k))==null||r.removeObserver(this),u(this,k,i(this,ht).getMutationCache().build(i(this,ht),this.options)),i(this,k).addObserver(this),i(this,k).execute(t)}},ht=new WeakMap,lt=new WeakMap,k=new WeakMap,Z=new WeakMap,tt=new WeakSet,Yt=function(){var s;const t=((s=i(this,k))==null?void 0:s.state)??Je();u(this,lt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},de=function(t){A.batch(()=>{var s,r,n,a,o,c,l,g;if(i(this,Z)&&this.hasListeners()){const y=i(this,lt).variables,h=i(this,lt).context;(t==null?void 0:t.type)==="success"?((r=(s=i(this,Z)).onSuccess)==null||r.call(s,t.data,y,h),(a=(n=i(this,Z)).onSettled)==null||a.call(n,t.data,null,y,h)):(t==null?void 0:t.type)==="error"&&((c=(o=i(this,Z)).onError)==null||c.call(o,t.error,y,h),(g=(l=i(this,Z)).onSettled)==null||g.call(l,void 0,t.error,y,h))}this.listeners.forEach(y=>{y(i(this,lt))})})},Ke),Ze=O.createContext(void 0),Jt=e=>{const t=O.useContext(Ze);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Ns=({client:e,children:t})=>(O.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),p.jsx(Ze.Provider,{value:e,children:t})),ts=O.createContext(!1),Ks=()=>O.useContext(ts);ts.Provider;function $s(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Hs=O.createContext($s()),Gs=()=>O.useContext(Hs);function es(e,t){return typeof e=="function"?e(...t):!!e}function fe(){}var Bs=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Ys=e=>{O.useEffect(()=>{e.clearReset()},[e])},zs=({result:e,errorResetBoundary:t,throwOnError:s,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&es(s,[e.error,r]),Ws=e=>{e.suspense&&(e.staleTime===void 0&&(e.staleTime=1e3),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3)))},Vs=(e,t)=>e.isLoading&&e.isFetching&&!t,Js=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,De=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function Xs(e,t,s){var y,h,S,v,R;const r=Jt(),n=Ks(),a=Gs(),o=r.defaultQueryOptions(e);(h=(y=r.getDefaultOptions().queries)==null?void 0:y._experimental_beforeQuery)==null||h.call(y,o),o._optimisticResults=n?"isRestoring":"optimistic",Ws(o),Bs(o,a),Ys(a);const c=!r.getQueryCache().get(o.queryHash),[l]=O.useState(()=>new t(r,o)),g=l.getOptimisticResult(o);if(O.useSyncExternalStore(O.useCallback(f=>{const b=n?fe:l.subscribe(A.batchCalls(f));return l.updateResult(),b},[l,n]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),O.useEffect(()=>{l.setOptions(o,{listeners:!1})},[o,l]),Js(o,g))throw De(o,l,a);if(zs({result:g,errorResetBoundary:a,throwOnError:o.throwOnError,query:r.getQueryCache().get(o.queryHash)}))throw g.error;if((v=(S=r.getDefaultOptions().queries)==null?void 0:S._experimental_afterQuery)==null||v.call(S,o,g),o.experimental_prefetchInRender&&!gt&&Vs(g,n)){const f=c?De(o,l,a):(R=r.getQueryCache().get(o.queryHash))==null?void 0:R.promise;f==null||f.catch(fe).finally(()=>{l.updateResult()})}return o.notifyOnChangeProps?g:l.trackResult(g)}function et(e,t){return Xs(e,Us)}function ss(e,t){const s=Jt(),[r]=O.useState(()=>new _s(s,e));O.useEffect(()=>{r.setOptions(e)},[r,e]);const n=O.useSyncExternalStore(O.useCallback(o=>r.subscribe(A.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=O.useCallback((o,c)=>{r.mutate(o,c).catch(fe)},[r]);if(n.error&&es(r.options.throwOnError,[n.error]))throw n.error;return{...n,mutate:a,mutateAsync:n.mutate}}const Zs=864e5,tr=/^\d{4}-\d{2}-\d{2}$/;function Fe(e,t=Date.now()){return new Date(t-e*Zs).toISOString().slice(0,10)}function er(e=30,t=Date.now()){return{fromDay:Fe(e-1,t),toDay:Fe(0,t)}}function sr(e){return tr.test(e)}function zt(){return typeof window<"u"&&window.__AGENT_API__?window.__AGENT_API__:`${typeof window<"u"&&window.__AGENT_BASE__||"/ai-gateway"}/api`}async function J(e,t){const s=await fetch(zt()+e,t);if(!s.ok)throw new Error(`${s.status} ${s.statusText}`);return await s.json()}const $={spend(e){const t=new URLSearchParams({from:e.fromDay,to:e.toDay});return J(`/spend?${t.toString()}`)},topThreads(e,t=10){const s=new URLSearchParams({from:e.fromDay,to:e.toDay,limit:`${t}`});return J(`/top-threads?${s.toString()}`)},reliability(e){const t=new URLSearchParams({from:e.fromDay,to:e.toDay});return J(`/reliability?${t.toString()}`)},runs(e=50){return J(`/runs?limit=${e}`)},toolCalls(e=50){return J(`/tool-calls?limit=${e}`)},approvals(e=50){return J(`/approvals?limit=${e}`)},async decideApproval(e,t){const s=await fetch(`${zt()}/approvals/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok)throw new Error(`${s.status} ${s.statusText}`)},toolStats(e){const t=new URLSearchParams({from:e.fromDay,to:e.toDay});return J(`/tools?${t.toString()}`)},threads(e=50){return J(`/threads?limit=${e}`)},pricing(){return J("/pricing")},async upsertPrice(e){const t=await fetch(`${zt()}/pricing`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`${t.status} ${t.statusText}`)},streamEvents(e){const t=new EventSource(`${zt()}/stream`);return t.onmessage=s=>{try{e(JSON.parse(s.data))}catch{}},()=>t.close()}};function rr(e){return et({queryKey:["spend",e.fromDay,e.toDay],queryFn:()=>$.spend(e)})}function ir(e,t=10){return et({queryKey:["top-threads",e.fromDay,e.toDay,t],queryFn:()=>$.topThreads(e,t)})}function nr(e){return et({queryKey:["reliability",e.fromDay,e.toDay],queryFn:()=>$.reliability(e)})}function ar(e=50){return et({queryKey:["runs",e],queryFn:()=>$.runs(e)})}function or(e=50){return et({queryKey:["tool-calls",e],queryFn:()=>$.toolCalls(e)})}function ur(e=50){return et({queryKey:["threads",e],queryFn:()=>$.threads(e)})}function cr(e=50){return et({queryKey:["approvals",e],queryFn:()=>$.approvals(e)})}function hr(){const e=Jt();return ss({mutationFn:({toolCallId:t,input:s})=>$.decideApproval(t,s),onSuccess:()=>{e.invalidateQueries({queryKey:["approvals"]})}})}function lr(e){return et({queryKey:["tool-stats",e.fromDay,e.toDay],queryFn:()=>$.toolStats(e)})}function dr(){return et({queryKey:["pricing"],queryFn:()=>$.pricing()})}function fr(){const e=Jt();return ss({mutationFn:t=>$.upsertPrice(t),onSuccess:()=>{e.invalidateQueries({queryKey:["pricing"]})}})}function pr(e=200){const[t,s]=O.useState([]),[r,n]=O.useState(!1),a=O.useRef(0);return O.useEffect(()=>{n(!0);const o=$.streamEvents(c=>{a.current+=1,s(l=>rs(l,c,a.current,e))});return()=>{n(!1),o()}},[e]),{events:t,connected:r}}const yr=[{key:"spend",label:"Spend & usage",icon:p.jsx(ns,{})},{key:"models",label:"Models",icon:p.jsx(as,{})},{key:"actors",label:"Actors & budgets",icon:p.jsx(os,{})},{key:"runs",label:"Runs & tools",icon:p.jsx(ge,{})},{key:"reliability",label:"Reliability",icon:p.jsx(us,{})},{key:"approvals",label:"Approvals",icon:p.jsx(cs,{})},{key:"tools",label:"Tools",icon:p.jsx(ge,{})},{key:"pricing",label:"Pricing",icon:p.jsx(hs,{})},{key:"live",label:"Live",icon:p.jsx(ls,{})}],mr={byModel:[],byActor:[],trend:[]},vr=[],br=[],gr=[],Sr=[],Te=[],wr=[],xr={metrics:{runs:0,completed:0,failed:0,successRate:0,retries:0,durationP50Ms:null,durationP95Ms:null},byAgent:[],errors:[],trend:[]},Cr=[],Pr="501";function Rr(){const[e,t]=O.useState(er()),[s,r]=O.useState("spend"),n=rr(e),a=ir(e),o=or(),c=ur(),l=nr(e),g=ar(),y=cr(),h=hr(),S=lr(e),v=dr(),R=fr(),f=pr(),b=n.data??mr,D=v.isError&&v.error instanceof Error?v.error.message.startsWith(Pr):!1;return p.jsxs("div",{className:"relative min-h-full",children:[p.jsx("div",{className:"app-bg"}),p.jsxs("div",{className:"relative z-10 mx-auto max-w-[1180px] px-5 py-5",children:[p.jsx(Er,{range:e,onRange:t,connected:f.connected,liveCount:f.events.length}),p.jsx("nav",{className:"mb-5 flex flex-wrap gap-1",children:yr.map(C=>{const P=C.key==="live"?f.events.length:C.key==="approvals"?(y.data??Te).length:0;return p.jsxs("button",{type:"button",onClick:()=>r(C.key),className:`flex items-center gap-2 rounded-lg border px-3 py-1.5 text-xs transition-colors ${s===C.key?"border-[var(--accent)]/50 bg-[var(--accent)]/10 text-[var(--text)]":"border-transparent text-[var(--muted)] hover:text-[var(--text)]"}`,children:[C.icon,C.label,P>0&&p.jsx("span",{className:"mono tnum rounded bg-[var(--accent)]/20 px-1 text-[10px] text-[var(--accent)]",children:P})]},C.key)})}),p.jsx(Or,{section:s,overview:b,topThreads:a.data??gr,loadingSpend:n.isLoading,errorSpend:n.isError,toolCalls:o.data??vr,threads:c.data??br,reliability:l.data??xr,runs:g.data??Cr,approvals:y.data??Te,onDecideApproval:(C,P)=>h.mutateAsync({toolCallId:C,input:P}),toolStats:S.data??wr,liveEvents:f.events,connected:f.connected,prices:v.data??Sr,loadingPrices:v.isLoading,pricingUnavailable:D,onUpsertPrice:C=>R.mutateAsync(C),savingPrice:R.isPending})]})]})}function Or({section:e,overview:t,topThreads:s,loadingSpend:r,errorSpend:n,toolCalls:a,threads:o,reliability:c,runs:l,approvals:g,onDecideApproval:y,toolStats:h,liveEvents:S,connected:v,prices:R,loadingPrices:f,pricingUnavailable:b,onUpsertPrice:D,savingPrice:C}){if(n&&(e==="spend"||e==="models"||e==="actors"))return p.jsx("div",{className:"panel p-6 text-sm text-[var(--bad)]",children:"Failed to load the read-model. Is the governance read-model bound and the API reachable?"});if(r&&(e==="spend"||e==="models"||e==="actors"))return p.jsx("div",{className:"panel animate-pulse p-6 text-sm text-[var(--muted)]",children:"Loading…"});switch(e){case"spend":return p.jsx(Ss,{overview:t,topThreads:s});case"models":return p.jsx(gs,{rows:t.byModel});case"actors":return p.jsx(bs,{rows:t.byActor});case"runs":return p.jsx(vs,{toolCalls:a,threads:o});case"reliability":return p.jsx(ms,{overview:c,runs:l});case"approvals":return p.jsx(ys,{approvals:g,onDecide:y});case"tools":return p.jsx(ps,{rows:h});case"pricing":return p.jsx(fs,{prices:R,loading:f,unavailable:b,onUpsert:D,saving:C});case"live":return p.jsx(ds,{events:S,connected:v});default:return null}}function Er({range:e,onRange:t,connected:s,liveCount:r}){return p.jsxs("header",{className:"mb-5 flex flex-wrap items-center gap-4",children:[p.jsxs("div",{className:"flex items-center gap-2.5",children:[p.jsx("div",{className:"grid h-8 w-8 place-items-center rounded-lg border border-[var(--accent)]/40 bg-[var(--accent)]/10",children:p.jsx(is,{className:"h-4 w-4 text-[var(--accent)]"})}),p.jsxs("div",{className:"leading-none",children:[p.jsx("div",{className:"text-sm font-semibold tracking-tight",children:"AI gateway"}),p.jsx("div",{className:"mono text-[10px] uppercase tracking-[0.2em] text-[var(--muted)]",children:"governance console"})]})]}),p.jsxs("div",{className:"ml-auto flex flex-wrap items-center gap-2",children:[p.jsx(Ae,{label:"From",value:e.fromDay,onChange:n=>t({...e,fromDay:n})}),p.jsx(Ae,{label:"To",value:e.toDay,onChange:n=>t({...e,toDay:n})}),p.jsxs("span",{className:"flex items-center gap-1.5 rounded-lg border border-[var(--line)] px-2.5 py-1.5 text-[11px] text-[var(--muted)]",children:[p.jsx("span",{className:`dot ${s?"s-ok pulse":"s-failed"}`,"aria-hidden":!0}),"live ",r>0?`· ${r}`:""]})]})]})}function Ae({label:e,value:t,onChange:s}){return p.jsxs("label",{className:"flex items-center gap-1.5 rounded-lg border border-[var(--line)] bg-[var(--panel)] px-2.5 py-1 text-[11px] text-[var(--muted)]",children:[p.jsx("span",{className:"uppercase tracking-wider",children:e}),p.jsx("input",{type:"date",value:t,onChange:r=>{const n=r.target.value;sr(n)&&s(n)},className:"mono bg-transparent text-[var(--text)] outline-none"})]})}const Dr=new qs({defaultOptions:{queries:{refetchInterval:5e3,refetchOnWindowFocus:!1,retry:1}}}),je=document.getElementById("root");je&&ws.createRoot(je).render(p.jsx(O.StrictMode,{children:p.jsx(Ns,{client:Dr,children:p.jsx(Rr,{})})}));