Aviary
Packages

@dudousxd/nestjs-agent-dashboard

A standalone AI-gateway governance console — bundled React SPA + JSON/SSE API mounted at its own route, no Telescope required — plus a dependency-free client subpath.

pnpm add @dudousxd/nestjs-agent-dashboard

AgentDashboardModule mounts a bundled React SPA and its JSON + SSE API at their own route — spend per model/actor, a usage trend, run reliability, an approvals inbox, tool governance stats, and live tool-call/thread activity — without needing @dudousxd/nestjs-telescope installed at all. The SPA is a single page that routes its sections client-side via URL hash — #/spend (default), #/models, #/actors, #/runs, #/reliability, #/approvals, #/tools, #/pricing, #/live — deep-linkable (a hash may carry a query tail, e.g. #/reliability?threadId=…), no server routing, no extra dependency.

import { Module } from '@nestjs/common';
import { AgentDashboardModule } from '@dudousxd/nestjs-agent-dashboard';

@Module({
  imports: [AgentDashboardModule.forRoot({ basePath: '/ai-gateway' })],
})
export class AppModule {}

AgentDashboardModule.forRoot(options?)

OptionDefaultPurpose
basePath/ai-gatewayWhere the SPA is served — a page route, kept out of any /api prefix.
apiBasePath<basePath>/apiWhere the JSON + SSE API is mounted (what the SPA fetches). Set it under your app's own /api prefix so it inherits your auth/proxy rules while the UI stays at basePath.
authorizeopen outside production, 403 in productionWho reaches the console: a function, an @Injectable() ConsoleAuthorizer class, a lazy import, { policy, ability }, or a gate name. See Protecting the console.
decoratorsnoneClass decorators applied to every controller the module mounts, before authorize, e.g. [UseGuards(AuthenticationGuard)].
routestruefalse mounts none of the console's routes; the services keep running. Extend AgentApiController / AgentUiController under your own path, with UseConsoleAuthorize().
importsnoneExtra module imports so a guard's own dependencies (e.g. your AuthModule) resolve — the dashboard has no application context of its own to pull them from.
approvalActorRefthe configured ActorResolver(req) => string | undefined — override for WHO is recorded as deciding a HITL approval (Decision.executedByRef). Default: the AgentModule-configured actor resolver (AGENT_ACTOR_RESOLVER) is consulted, same identity seam chat uses. Set this only when console auth differs from chat auth.
devToolson when routes is not falseRegister the console's reads as MCP tools on /mcp/aviary
viewerrequest.user, read structurally(request) => ({ label, email?, role? }), sync or async — who the sidebar footer says is signed in. See Signed-in user and sign-out
signOutthe account.signOut an account console announced, else none'/logout' | { href } | { action, csrfToken? } | false — the sidebar footer's sign-out
federationnone{ apps: { [name]: { queries, approvals?, pricing?, label? } }, localLabel? } — also show other apps, each read from its own store, with an app switcher. See Federated console

It requires AGENT_GOVERNANCE_QUERIES to already be bound — import it alongside your AgentModule.forRoot(...) and a store adapter (MikroORM or Drizzle) that provides the read-model.

Set authorize

Without authorize the console is open outside production and answers 403 to every request in production (with a warning at boot). See Protecting the console.

Protecting the console

authorize decides who reaches the console: the SPA and every API and SSE route. It runs after any decorators you pass, so an authentication guard there has already set request.user.

AgentDashboardModule.forRoot({
  decorators: [UseGuards(AuthenticationGuard)],
  authorize: (ctx) => ctx.switchToHttp().getRequest().user?.isAdmin === true,
});

authorize takes any of these forms:

// 1. An inline function.
authorize: (ctx) => ctx.switchToHttp().getRequest().user?.isAdmin === true,

// 2. A class: an @Injectable() ConsoleAuthorizer (constructor injection works).
authorize: ConsoleAccess,

// 3. A lazy import of that class.
authorize: () => import('./console-access.js'),

// 4. A policy from @nestjs/authorization: policy[ability](user).
authorize: { policy: ConsolePolicy, ability: 'view' },

// 5. A gate ability name from @dudousxd/nestjs-authz (needs its AuthzModule).
authorize: 'console.agent',
console-access.ts
import { Injectable, type ExecutionContext } from '@nestjs/common';
import type { ConsoleAuthorizer } from '@dudousxd/nestjs-agent-dashboard';

@Injectable()
export default class ConsoleAccess implements ConsoleAuthorizer {
  constructor(private readonly audit: AuditService) {}

  async authorize(ctx: ExecutionContext) {
    const user = ctx.switchToHttp().getRequest().user;
    if (!user) return { redirectTo: '/login' };
    return user.roles.includes('ops');
  }
}

What authorize returns:

ResultAPI callPage navigation
true / { allowed: true }allowedallowed
false / { allowed: false }403 { error: 'forbidden' }403 access-denied page
{ allowed: false, reason: 'unauthenticated' }401 { error: 'unauthenticated' }401 sign-in-required page
{ redirectTo: '/login' }401 { error: 'unauthenticated', redirectTo }302 to redirectTo
throws403403

The SPA follows a redirectTo it gets from the API and shows an access-denied screen on a 403.

An allow can also name who it let in: { allowed: true, caller: 'user:42' }. The MCP tools log that name as the caller of each call. Never put a secret in it. authorizeByToken names its caller token:<hash>.

A bearer token

authorizeByToken allows a request whose Authorization: Bearer <token> header matches:

import { authorizeByToken } from '@dudousxd/nestjs-agent-dashboard';

AgentDashboardModule.forRoot({
  authorize: authorizeByToken({ token: process.env.CONSOLE_TOKEN }),
});

Only the header counts (no query string). An empty token throws when the module is configured.

A token is for callers you script, such as the JSON API. The console UI in a browser sends no Authorization header, so a console protected by a token alone answers 401 to its own UI. For browser use, sign in with your app's authentication (in decorators) and use a function, a class, a policy or a gate name.

A token or a session: anyAuthorize

anyAuthorize(...forms) allows a request when any of its forms allows it. If none does, the result is unauthenticated when any form said so, and forbidden otherwise:

import { anyAuthorize, authorizeByToken } from '@dudousxd/nestjs-agent-dashboard';

AgentDashboardModule.forRoot({
  authorize: anyAuthorize(authorizeByToken({ token: process.env.CONSOLE_TOKEN }), AdminAuthorizer),
});

Without authorize

  • Outside production (NODE_ENV !== 'production') the console is open.
  • In production every request answers 403 { error: 'forbidden' }.
  • Either way, one warning is logged at boot telling you to set authorize, also with routes: false (UseConsoleAuthorize() applies the same production 403).

decorators alone do not change this: set authorize.

Mounting it yourself

With routes: false the module mounts nothing; extend the exported controllers under your own path, and apply the module's authorize with UseConsoleAuthorize(). Put it above your authentication decorators: Nest applies class decorators bottom-up, so the one written higher runs later.

AgentDashboardModule.forRoot({
  routes: false,
  basePath: '/ops/ai',
  apiBasePath: '/ops/ai/api',
  authorize: { policy: ConsolePolicy, ability: 'view' },
});

@Controller('ops/ai/api')
@UseConsoleAuthorize() // above the auth guard: class decorators apply bottom-up
@UseGuards(AuthenticationGuard)
export class ConsoleApi extends AgentApiController {}

@Controller('ops/ai')
@UseConsoleAuthorize() // above the auth guard: class decorators apply bottom-up
@UseGuards(AuthenticationGuard)
export class ConsoleUi extends AgentUiController {}

The console has no sign-in of its own: the app's session is what a browser carries when it opens the console, and authorize can send it to your sign-in with { redirectTo }.

Migrating from the production boot refusal

The console no longer refuses to boot in production without decorators; set authorize instead.

// Before
AgentDashboardModule.forRoot({
  decorators: [UseGuards(AuthenticationGuard), Can(ConsolePolicy, 'view')],
});

// After
AgentDashboardModule.forRoot({
  decorators: [UseGuards(AuthenticationGuard)],
  authorize: { policy: ConsolePolicy, ability: 'view' },
});

A decorators list that still decides access (a Can(), a guard that denies) keeps working, but without authorize the console answers 403 to every request in production.

Subpath /client — a dependency-free typed client

@dudousxd/nestjs-agent-dashboard/client re-declares the governance row shapes so it has zero runtime dependencies — safe to use from any frontend that only wants to call the API, without pulling in the server package.

import { agentClient } from '@dudousxd/nestjs-agent-dashboard/client';

const overview = await agentClient.spend({ fromDay: '2026-06-01', toDay: '2026-06-30' });
// overview.byModel / overview.byActor / overview.trend

const calls = await agentClient.toolCalls({ size: 50 }); // { data, meta }
const threads = await agentClient.threads({ page: 2, filter: { title: 'refund' } });

const stop = agentClient.streamEvents((event) => console.log(event.event, event.payload));
// stop() closes the SSE connection

Range reads take { fromDay, toDay } (YYYY-MM-DD, inclusive UTC).

MethodReturns
agentClient.spend(range: GovernanceRange){ byModel, byActor, trend } for the day range — byModel/byActor rows carry an actorLabel: string | null when an ActorDirectory (AGENT_ACTOR_DIRECTORY) is bound server-side.
agentClient.toolCalls(query?)A page of tool-call activity, newest first.
agentClient.threads(query?)A page of thread activity, newest activity first.
agentClient.topThreads(range, size = 10)Top threads by cost, as { data }.
agentClient.reliability(range){ metrics, byAgent, errors, trend }.
agentClient.runs(query?)A page of runs, newest first.
agentClient.approvals(query?)A page of pending HITL approvals, oldest first; meta.total is the backlog.
agentClient.runDetail(runId) / threadDetail(threadId, { messages?, runs? })Drill-downs; reject with a 404 … error if unknown.
agentClient.toolStats(range)Per-tool governance rollup.
agentClient.decideApproval(toolCallId, { approved, reason? })Decide a pending approval.
agentClient.pricing() / upsertPrice(input)Read / upsert model prices.
agentClient.streamEvents(onEvent)Live-tails aviary:agent:* over SSE; returns a function that closes the stream.

The list reads take { page?, size?, filter? } and resolve to { data, meta: { total, perPage, currentPage, lastPage, firstPage } }.

Reliability, approvals, and tool governance

Beyond spend/usage, the console has three more sections, all fed by the same AGENT_GOVERNANCE_QUERIES read-model documented in -core:

  • Reliability (#/reliability) — success/error rate, retries, p50/p95 run duration, a run/failure trend, failure breakdown by error code, and a recent-runs table with promptHash chips (correlate an error-rate shift with a prompt change) and a 500-char-capped error message. The status filter covers every terminal a run settles on, cancelled included — a user pressing Stop is not a failure, and a terminal the dropdown omits is one a server-side filter cannot be asked for. A run's drill-down names its parentRunId when it has one, which for a detached child is the only link back to the turn that started it. Backed by GET <api>/reliability?from&to and the paged GET <api>/runs.
  • Approvals (#/approvals) — the cross-thread HITL inbox: every tool call sitting pending_approval, oldest first, paged over GET <api>/approvals with the backlog total, and a nav badge showing the pending count. Approve/reject posts POST <api>/approvals/:toolCallId ({ approved, reason? }), which routes through the same decision path chat approvals use — without re-running chat's own thread-ownership check, since a console caller is already authorized by the console's decorators (or your own controllers).
  • Tools (#/tools) — per-tool governance rollup (GET <api>/tools): calls, failures, rejections, and p95 execution time.

501 read-only mode

Mutating endpoints 501 (and the corresponding SPA section renders read-only) when their backing port isn't bound:

  • POST <api>/approvals/:toolCallId 501s with no AGENT_APPROVAL_PORT bound. In practice this is bound automatically the moment AgentModule is imported anywhere in the app (see -nestjs) — it only 501s if the dashboard is mounted in a process that never imports AgentModule at all (e.g. a read-replica/reporting app wired only against AGENT_GOVERNANCE_QUERIES).
  • GET/POST <api>/pricing 501 with no AGENT_PRICING_STORE bound.

Both cases are logged 501s, not crashes — the rest of the console keeps working.

Paginated, filterable tables

Tool calls, threads, runs, and pending approvals are each backed by a paged read (toolCallsPage / threadsPage / runsPage / approvalsPage on AgentGovernanceQueries) exposed over HTTP as GET <api>/tool-calls, GET <api>/threads, GET <api>/runs, GET <api>/approvals. They speak the Aviary list wire: page (1-based), size (default 25, clamped to 200), filter[field]=value (filter[title][contains]=… for the thread title search), and a sort that accepts only the list's fixed order (newest first; approvals oldest first). Responses are { data, meta: { total, perPage, currentPage, lastPage, firstPage } }. An unknown filter field, an unsupported operator or another sort is a 400. The SPA's list sections use these for prev/next pagination with per-column filters; the latest-N recentToolCalls/recentThreads/recentRuns SPI reads remain for the Telescope bridge, which only needs the tail.

MCP tools

When AgentMcpServerModule is imported, the console's reads are also served as developer tools on /mcp/aviary, gated by this console's authorize. The tools are agent_list_runs, agent_get_run, agent_get_spend, agent_get_tool_stats, agent_get_reliability, agent_list_pending_approvals and agent_list_recent_tool_calls. They are registered while the console's routes are mounted. devTools: true keeps them with routes: false, and devTools: false turns them off. See Developer tools over MCP.

Several apps in one console

federation turns the console into a federated one: it also shows the threads, runs, tool calls and approvals of other apps, read from each app's own store, with an app switcher in the header (?app=<name>). Approvals of a federated app are executed by that app, sent over its Redis. See Federated console.

Switching between consoles

When the app mounts other Aviary consoles too (durable's Workflows, Telescope, Media), the console's brand becomes a menu that lists the ones the viewer may open, and links to them. Each is listed only when its own authorize allows the viewer. That authorize then also runs once each time the page loads. With no other console, or none the viewer may open, the brand stays as it is. There is nothing to configure. The agent console is listed in the other consoles' menus while its routes are mounted.

Searching every console

Press Ctrl/⌘+K, use the Search button in the topbar, or pick Search all consoles in the brand menu. The console's own pages are listed first. One query searches:

  • this console: a run by its exact id, a thread by its exact id, threads whose title contains the text, and the newest runs of an agent with that name;
  • every other Aviary console the viewer may open, for what each one searches (durable runs, Telescope entries, Media files).

Each console answers with up to 5 hits, grouped under its name, and gets 300 ms. A console that does not answer in time is left out, and the palette says some results are missing. Hits respect tenancy like the rest of the console. A hit opens the run or thread drill-down directly; the same links work by hand: /ai-gateway#/runs?run=<runId> and /ai-gateway#/runs?thread=<threadId>.

The endpoint is GET <apiBasePath>/consoles/search?q=, behind the console's own authorize. &console=<id> answers for that one console only (still behind its own authorize): the palette asks this console and each console in the switcher on its own, and shows each group as it answers.

Signed-in user and sign-out

The console's sidebar footer shows who is signed in, a light/dark toggle and a sign-out. Both come from the server, in the page's config block; neither is required.

AgentDashboardModule.forRoot({
  authorize: ConsoleAccess,
  decorators: [UseGuards(AuthenticationGuard)],
  // Default: request.user, read structurally (fullName → name → email; role or the first of roles).
  viewer: (req) => ({ label: req.user.displayName, email: req.user.email, role: 'admin' }),
  // A POST form to /logout, with the token as `_csrf`:
  signOut: { action: '/logout', csrfToken: (req) => req.csrfToken() },
});
  • viewer — (request) => ({ label, email?, role? }), sync or async. null, undefined or a throw shows no user row. Omitted, request.user is read structurally: whatever your guards (decorators) already put there. Reading it never triggers an authentication.
  • signOut — '/logout' (a POST form, with _csrf when the request has req.csrfToken()), { href: '/logout' } (a link), { action, csrfToken: (request) => token } (a POST form with your token), or false (none). Omitted, the console uses the sign-out an account console announced on the Aviary consoles registry (account.signOut), else shows none.

Only same-origin paths (/x) are sent to the page.

Telling a probe from a visit

To list or search the other consoles, the switcher runs their authorize on the viewer's request. While it does, the request carries aviaryProbe = true. An authorize that writes an audit line for every visit can skip those:

authorize: (ctx) => {
  const req = ctx.switchToHttp().getRequest();
  if (req.aviaryProbe !== true) audit.log('console.open', req.user?.id);
  return req.user?.isAdmin === true;
},

The Organization

With the agent's tenancy on, every read is scoped to the viewer's tenant, and the header shows that Organization with its labels (Clinic One › Unit One), "All organizations" inside Context.allTenants(), or "No organization". The labels come from the context's tenancy.label, else the tenant's slug, else its id. See The Organization in the console.

With a tenant required, a viewer without one gets a 403 on the console's reads, and the search finds nothing here.

When to use it

Reach for -dashboard when you want a governance console but aren't running Telescope, or want the AI-gateway surface independently addressable at its own route. Already running Telescope? The -telescope extension adds the same governance sections as an "Agent" tab instead — both read the same AGENT_GOVERNANCE_QUERIES read-model, so you can run either or both.

See Cost & Governance for the ledger and read-model this console surfaces, and Reference → Endpoints for the API routes directly.

On this page