4569657923
## What & why This is the system behind the Dashboard Agent — an assistant that answers questions about a project's runs, errors, queues, deploys and health, and can investigate failures end to end. The agent runs as a chat.agent task in its own Trigger project. It has no access to the main database or ClickHouse; all platform data is read through the public API using a delegated, read-only user token. Everything here is behind `canAccessDashboardAgent` and inert with the flag off. The UI that mounts the panel lands in #4529. ## Stack `#4418` (this, base) ← `#4529` UI ← `#4525` Watch ← `#4516` storybook gallery. The scenario/contract reference for the whole stack is `internal-packages/dashboard-agent/GUIDEBOOK.md` (it lands on the Watch branch): it states, per feature, what makes each thing happen and where that is decided. ## What's inside **Agent runtime and tools** — `internal-packages/dashboard-agent`: prompt, tool set (API reads, TRQL query, docs, navigation, evidence/investigations, repo source), conversation compaction, a prompt-prefix token budget pinned by snapshot test, and sampled LLM-judged turn evals. The package cannot import webapp server code, which is what makes the "no DB access" claim structural rather than a convention. **Contracts** — `internal-packages/dashboard-agent-contracts`: `trigger://` URIs, intents, and the block envelope every rendered card travels in. **Conversation store** — `internal-packages/dashboard-agent-db`: drizzle over postgres-js in its own `trigger_dashboard_agent` Postgres schema, plus one additive migration. **Auth boundary** — the user-actor token gains an optional environment claim; one guard (`userActorEnvironment.server.ts`) enforces it so routes don't each re-derive the rule. Token minting, cap ceiling, and the RBAC fallback path for self-hosted. **Transport** — webapp resource routes that mint the token and proxy each turn, and SDK-side mid-turn reconnect. **Public API the agent reads through** — orgs, projects, environments, runs, queue metrics, workers, a run's commit metadata, repo snapshot, reports, and `POST /api/v1/query`. **Reports** — the health report's layout is declared once and shared by the card, the markdown surface and the JSON/MCP surface, so the same report reads the same in the dashboard, the terminal and an editor. **Block renderers** — the report and investigation cards the flows above already emit (`app/components/dashboard-agent/`). The panel that hosts them, and the rest of the chat UI, is #4529. **Query safety and CSP** — see below. ## Key decisions - **The agent is a separate Trigger project, not webapp code.** It reads platform data over the public API with a delegated user-actor token whose `cap` ceilings it to read scopes. No Prisma, no ClickHouse, no webapp imports. - **The PAT-only auth helper now refuses user-actor tokens.** This is an intentional behavioral change: its callers consume only a bare userId and do not enforce delegated-token capabilities. Actor-aware routes continue through the scoped route builders instead. - **RBAC fallback builds a delegated token's ability from its own cap**, never the blanket ability a PAT gets (read-only when the token declares none). Without this, the agent's read-only cap would buy a write JWT on self-hosted. - **Org creation checks RBAC only for user-actor tokens, and only after the env gate**, so an install with `ORG_CREATION_API_ENABLED` off returns 404 rather than 403, and an ordinary PAT never consults an ability the route has no org to scope. Both orderings are pinned by test. - **The query path is read-only in depth.** TRQL rejects write statements at the grammar level (they don't parse, rather than being filtered), ClickHouse runs with `readonly=1`, and the org/project/env filters are injected server-side from the credential — the request body cannot widen scope. An unparseable query denies instead of falling through to the permissive resource. - **Document-wide img-src CSP.** Remote images are an outbound-request/exfiltration surface, so the policy permits only own-origin/data/blob, the required SSO avatar hosts, and the favicon endpoint. Operators can add exact origins through CSP_IMG_SRC_ALLOWLIST; wildcard hosts and bare schemes are intentionally not allowed. - **The chat transport reconnects on a mid-turn EOF** (`@trigger.dev/sdk`). A body that ends without a turn-complete is terminal only when the server says `X-Session-Settled: true`; otherwise the transport resubscribes from `lastEventId` with bounded backoff, and any record re-earns the budget. Previously a closed long-poll window or a proxy restart left the reply stuck as if still generating. - **Conversations live in their own datastore**, schema-scoped and foreign-key-free (it references `organizationId`/`userId` by id, because in cloud it is a different database). It is a display read-model for the History tab and transport resume; `chat.agent`'s object-store snapshot remains the model's source of truth. - **Deterministic first.** Reports and health checks contain no LLM — they are computed from the same data the dashboard shows, and the model only narrates and links them. That is what makes a number in an answer auditable. ## Testing - 63 new test files, run with `pnpm run test --filter webapp` and per-package vitest. Heaviest coverage on the auth boundary (`userActorPatOnlyBoundary`, `userActorTokenClaimsAndScopes`, `contextlessPatRoutes`, `rbacFallbackBranch`), TRQL read-only, the report layout, and the SDK reconnect. - The agent package has a separate eval lane (`pnpm run test:evals`, `vitest.eval.config.ts`) that hits the real model, so it never runs in `pnpm test`. - Live-tested against a local stack scenario by scenario; the GUIDEBOOK lists the condition each behaviour is expected under, which is what those runs were checked against. ## Changelog `.server-changes/dashboard-agent.md`, plus changesets for `@trigger.dev/core` (report schemas), `@trigger.dev/sdk` (chat reconnect) and the CLI's `mint-token` help text.
167 lines
6.5 KiB
TypeScript
167 lines
6.5 KiB
TypeScript
import { tryCatch } from "@trigger.dev/core/v3";
|
|
import { env } from "~/env.server";
|
|
import { resolvePrivateApiKeyRateLimitScope } from "~/models/runtimeEnvironment.server";
|
|
import { batchStreamGrants } from "~/runEngine/concerns/batchStreamGrantsInstance.server";
|
|
import { authenticateAuthorizationHeader } from "./apiAuth.server";
|
|
import { authorizationRateLimitMiddleware } from "./authorizationRateLimitMiddleware.server";
|
|
import { deploymentApiPaths } from "./deploymentApiPaths.server";
|
|
import type { Duration } from "./rateLimiter.server";
|
|
|
|
const BATCH_STREAM_ITEMS_PATH = /^\/api\/v3\/batches\/([^/]+)\/items$/;
|
|
|
|
// Rate-limit key for a delegated (agent/PAT-minted) JWT. Its token value rotates every
|
|
// turn, so keying on the token would hand each turn a fresh bucket. Key on env+acting-user
|
|
// so the agent's traffic shares one bucket across turns. The `jwt-actor:` prefix keeps it
|
|
// off PRIVATE-key buckets, which key on the bare environment id.
|
|
export function jwtActorRateLimitIdentifier(environmentId: string, actorSub: string): string {
|
|
return `jwt-actor:${environmentId}:${actorSub}`;
|
|
}
|
|
|
|
// The per-request bucket decision for the API limiter. Exported so the branch below
|
|
// (a delegated JWT keys on env+acting-user, everything else keeps its prior key) is
|
|
// testable without standing up the middleware and its Redis.
|
|
export async function resolveApiRateLimitOverride(
|
|
authorizationValue: string
|
|
): Promise<{ config?: unknown; identifier?: string } | undefined> {
|
|
const rawApiKey = authorizationValue.replace(/^Bearer /, "");
|
|
|
|
if (rawApiKey.startsWith("tr_")) {
|
|
const scope = await resolvePrivateApiKeyRateLimitScope(rawApiKey);
|
|
|
|
if (!scope) {
|
|
return;
|
|
}
|
|
|
|
return {
|
|
config: scope.apiRateLimiterConfig,
|
|
identifier: scope.environmentId,
|
|
};
|
|
}
|
|
|
|
const authenticatedEnv = await authenticateAuthorizationHeader(authorizationValue, {
|
|
allowPublicKey: true,
|
|
allowJWT: true,
|
|
});
|
|
|
|
if (!authenticatedEnv || !authenticatedEnv.ok) {
|
|
return;
|
|
}
|
|
|
|
if (authenticatedEnv.type === "PUBLIC_JWT") {
|
|
const config = {
|
|
type: "fixedWindow",
|
|
window: env.API_RATE_LIMIT_JWT_WINDOW,
|
|
tokens: env.API_RATE_LIMIT_JWT_TOKENS,
|
|
} as const;
|
|
|
|
// A delegated JWT (agent/PAT-minted) shares one bucket per env+acting-user across turns.
|
|
// A browser realtime JWT carries no `act`, so it keeps the hashed-token fallback.
|
|
if (authenticatedEnv.actor?.sub) {
|
|
return {
|
|
config,
|
|
identifier: jwtActorRateLimitIdentifier(
|
|
authenticatedEnv.environment.id,
|
|
authenticatedEnv.actor.sub
|
|
),
|
|
};
|
|
}
|
|
|
|
return { config };
|
|
}
|
|
|
|
return {
|
|
config: authenticatedEnv.environment.organization.apiRateLimiterConfig,
|
|
// Public keys are browser-distributed, so keep them on per-key buckets.
|
|
identifier: authenticatedEnv.type === "PRIVATE" ? authenticatedEnv.environment.id : undefined,
|
|
};
|
|
}
|
|
|
|
export const apiRateLimiter = authorizationRateLimitMiddleware({
|
|
redis: {
|
|
port: env.RATE_LIMIT_REDIS_PORT,
|
|
host: env.RATE_LIMIT_REDIS_HOST,
|
|
username: env.RATE_LIMIT_REDIS_USERNAME,
|
|
password: env.RATE_LIMIT_REDIS_PASSWORD,
|
|
tlsDisabled: env.RATE_LIMIT_REDIS_TLS_DISABLED === "true",
|
|
clusterMode: env.RATE_LIMIT_REDIS_CLUSTER_MODE_ENABLED === "1",
|
|
},
|
|
keyPrefix: "api",
|
|
defaultLimiter: {
|
|
type: "tokenBucket",
|
|
refillRate: env.API_RATE_LIMIT_REFILL_RATE,
|
|
interval: env.API_RATE_LIMIT_REFILL_INTERVAL as Duration,
|
|
maxTokens: env.API_RATE_LIMIT_MAX,
|
|
},
|
|
limiterCache: {
|
|
fresh: 60_000 * 10, // Data is fresh for 10 minutes
|
|
stale: 60_000 * 20, // Date is stale after 20 minutes
|
|
maxItems: 1000,
|
|
},
|
|
limiterConfigOverride: resolveApiRateLimitOverride,
|
|
pathMatchers: [/^\/api/],
|
|
// Allow /api/v1/tasks/:id/callback/:secret
|
|
pathWhiteList: [
|
|
"/api/internal/stripe_webhooks",
|
|
// Keep allowlisted: these CLI endpoints are intentionally unauthenticated,
|
|
// so this Authorization-header-keyed limiter would 401 them. They are
|
|
// throttled separately by authCodeRateLimiter.server.ts.
|
|
"/api/v1/authorization-code",
|
|
"/api/v1/token",
|
|
"/api/v1/usage/ingest",
|
|
"/api/v1/plain/customer-cards",
|
|
/^\/api\/v1\/tasks\/[^/]+\/callback\/[^/]+$/, // /api/v1/tasks/$id/callback/$secret
|
|
/^\/api\/v1\/runs\/[^/]+\/tasks\/[^/]+\/callback\/[^/]+$/, // /api/v1/runs/$runId/tasks/$id/callback/$secret
|
|
/^\/api\/v1\/http-endpoints\/[^/]+\/env\/[^/]+\/[^/]+$/, // /api/v1/http-endpoints/$httpEndpointId/env/$envType/$shortcode
|
|
/^\/api\/v1\/sources\/http\/[^/]+$/, // /api/v1/sources/http/$id
|
|
/^\/api\/v1\/endpoints\/[^/]+\/[^/]+\/index\/[^/]+$/, // /api/v1/endpoints/$environmentId/$endpointSlug/index/$indexHookIdentifier
|
|
"/api/v1/timezones",
|
|
"/api/v1/usage/ingest",
|
|
"/api/v1/auth/jwt/claims",
|
|
/^\/api\/v1\/runs\/[^/]+\/attempts$/, // /api/v1/runs/$runFriendlyId/attempts
|
|
/^\/api\/v1\/waitpoints\/tokens\/[^/]+\/callback\/[^/]+$/, // /api/v1/waitpoints/tokens/$waitpointFriendlyId/callback/$hash
|
|
...deploymentApiPaths, // rate limited separately by deploymentRateLimiter
|
|
/^\/api\/v\d+\/deployments\/current$/, // runtime SDK surface, exempt as before the deploy budget split
|
|
// Internal SDK plumbing — packets are presigned-URL handshakes for
|
|
// payload uploads (v2 PUT) and downloads (v1 GET), authenticated via
|
|
// run-scoped JWT, called once per task/turn boundary by the runtime.
|
|
// Same shape as `/api/v1/runs/$runFriendlyId/attempts` above; not a
|
|
// customer-facing surface so customer rate limits shouldn't apply.
|
|
/^\/api\/v1\/packets\//,
|
|
/^\/api\/v2\/packets\//,
|
|
/^\/api\/v1\/sessions\/[^/]+\/snapshot-url$/,
|
|
],
|
|
bypass: async (req) => {
|
|
const match = BATCH_STREAM_ITEMS_PATH.exec(req.path);
|
|
|
|
if (!match) {
|
|
return false;
|
|
}
|
|
|
|
const batchFriendlyId = match[1];
|
|
const authorizationValue = req.headers.authorization;
|
|
|
|
if (!batchFriendlyId || !authorizationValue) {
|
|
return false;
|
|
}
|
|
|
|
const [authError, authenticated] = await tryCatch(
|
|
authenticateAuthorizationHeader(authorizationValue, {
|
|
allowPublicKey: true,
|
|
})
|
|
);
|
|
|
|
if (authError || !authenticated || !authenticated.ok) {
|
|
return false;
|
|
}
|
|
|
|
return batchStreamGrants.spend(authenticated.environment.id, batchFriendlyId);
|
|
},
|
|
log: {
|
|
rejections: env.API_RATE_LIMIT_REJECTION_LOGS_ENABLED === "1",
|
|
requests: env.API_RATE_LIMIT_REQUEST_LOGS_ENABLED === "1",
|
|
limiter: env.API_RATE_LIMIT_LIMITER_LOGS_ENABLED === "1",
|
|
},
|
|
});
|
|
|
|
export type RateLimitMiddleware = ReturnType<typeof authorizationRateLimitMiddleware>;
|