by vee

Manifest is a smart model router for AI agents and applications that redirects each query to the most appropriate model, cutting AI costs by up to 70% across 300+ models and 16 providers.
This block is the NestJS backend for Manifest, a smart AI model router that proxies requests to 300+ models across 16 providers and routes each query to the cheapest capable model based on complexity scoring, specificity detection, and custom rules. The typical buyer is a team building an AI-powered product who wants to drop in a self-hostable OpenAI-compatible gateway with cost analytics, fallback chains, and per-request observability.
analytics/ - Controllers and services for cost, token, message, and savings analytics queriesauth/ - BetterAuth integration: session guard, current-user decorator, auth instancecommon/ - Shared constants, DTOs, guards, interceptors, middleware, filters, and utilitiesconfig/ - App configuration factory (appConfig)database/ - TypeORM database module wiringentities/ - TypeORM entity definitions (e.g. ApiKey)free-models/ - Logic for identifying and serving free/local model optionsgithub/ - GitHub integration module (e.g. release checking)health/ - Health-check endpoint modulemodel-discovery/ - Runtime discovery of available models across configured providersmodel-prices/ - Price lookup and caching for modelsnotifications/ - Threshold alerts and notification dispatchotlp/ - OpenTelemetry OTLP ingest endpoint for trace/span ingestionpublic-stats/ - Anonymized public statistics endpointrouting/ - Core proxy routing logic: selects model, forwards request, handles fallbackscoring/ - Complexity and specificity scoring engine (pure TypeScript, no NestJS)setup/ - First-run setup wizard modulesse/ - Server-Sent Events streaming moduletelemetry/ - Internal telemetry and OTLP exportapp.module.ts - Root NestJS module, wires all feature modulesmain.ts - Bootstrap entrypoint: Helmet CSP, compression, auth middleware, SPA fallbacknpm install @nestjs/common @nestjs/core @nestjs/platform-express @nestjs/config \
@nestjs/cache-manager @nestjs/throttler @nestjs/typeorm @nestjs/serve-static \
@nestjs/event-emitter rxjs reflect-metadata \
helmet compression express \
typeorm better-auth \
cache-manager
Spin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 e5b91a44a0b4dc62…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
No native build steps are required. If you add local model support via Ollama, ensure Ollama is running as a sidecar process; no native node bindings are involved.
Copy the source/ directory into your project root, e.g. as packages/backend/src/.
Set rootDir and paths in tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2021",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"rootDir": "packages/backend/src",
"outDir": "dist",
"strict": true
}
}
Set required environment variables (create a .env file):
PORT=3001
NODE_ENV=development
BETTER_AUTH_URL=http://localhost:3001
DATABASE_URL=sqlite://./manifest.db
THROTTLE_TTL=60000
THROTTLE_LIMIT=100
# Optional:
WINGMAN_PORT=3002
FRAME_ANCESTORS=https://your-dashboard.example.com
Add a main.ts entrypoint (or use the one provided):
import { bootstrap } from './main';
bootstrap();
Register app.module.ts as the root module. All feature modules are already imported there; no additional wiring is needed unless you add your own modules.
Build and run:
npx ts-node -r tsconfig-paths/register packages/backend/src/main.ts
# or with NestJS CLI:
nest start
export async function bootstrap(): Promise<void>
The application entrypoint. Creates the NestJS application from AppModule, applies Helmet CSP (with HSTS conditional on HTTPS), enables compression, registers the SpaFallbackFilter, wires BetterAuth middleware, and starts listening. Call this once from your process entrypoint. Override PORT, BETTER_AUTH_URL, and FRAME_ANCESTORS via environment variables to control binding and security headers.
export { detectSpecificity } from './specificity-detector';
export type { SpecificityResult } from './specificity-detector';
Analyzes a prompt or message set and returns a SpecificityResult indicating how specific (vs. general) the request is. Use this directly in non-NestJS code (e.g. an Edge function or a Lambda) to decide whether to route to a cheaper general model or a specialized one, without instantiating the full NestJS app.
export { scanMessages } from './scan-messages';
Scans an array of chat messages and returns structured signal data used by the scoring pipeline. Use it upstream of the full scorer when you only need keyword and structural signals, or when you want to inspect intermediate scoring inputs for debugging or custom routing rules.
export type { ScorerInput, ScoringResult, ScorerConfig, DimensionScore, Tier, ScoringResult } from './types';
export type { MomentumInput } from './momentum';
Core types for the scoring engine. ScorerInput carries the messages and conversation context; ScoringResult contains dimension scores, the final Tier ('low' | 'medium' | 'high'), confidence, and reasons. Wire these types into your own routing middleware to annotate requests before forwarding.
Stand up the complete Manifest backend, including routing proxy, analytics, and auth, using the provided bootstrap function.
// entrypoint.ts
import { bootstrap } from './packages/backend/src/main';
bootstrap().catch((err) => {
console.error('Fatal startup error', err);
process.exit(1);
});
Set PORT=3001 and BETTER_AUTH_URL=http://localhost:3001 in your environment, then run:
npx ts-node entrypoint.ts
The server starts on port 3001, serves the SPA from FRONTEND_DIST if set, and exposes /api/* and /v1/* routes.
Use the scoring engine outside NestJS to score a single user message and decide routing tier before sending to an LLM provider.
import { detectSpecificity, SpecificityResult } from './packages/backend/src/scoring';
import { scanMessages } from './packages/backend/src/scoring';
const messages = [
{ role: 'user', content: 'Write a recursive Fibonacci function in TypeScript with memoization and explain the time complexity.' }
];
const specificity: SpecificityResult = detectSpecificity(messages);
console.log('Specificity:', specificity);
const signals = scanMessages(messages);
console.log('Scan signals:', signals);
// Route to a capable model only when specificity or complexity is high
if (specificity.score > 0.6) {
console.log('Route to high-tier model');
} else {
console.log('Route to low-tier model');
}
Reuse the ApiKeyGuard to protect a custom endpoint you add alongside the existing routes.
// my-custom.controller.ts
import { Controller, Get, UseGuards } from '@nestjs/common';
import { ApiKeyGuard } from './packages/backend/src/common/guards/api-key.guard';
@Controller('api/my-endpoint')
@UseGuards(ApiKeyGuard)
export class MyCustomController {
@Get()
getData() {
return { status: 'ok' };
}
}
Register MyCustomController in a feature module imported by AppModule. The guard reads the x-api-key header and validates it against stored ApiKey entities.
main.ts - Bootstraps NestJS, configures Helmet CSP (HSTS, frame-src, upgrade-insecure-requests), compression, BetterAuth middleware, and the SPA fallback filter.app.module.ts - Root @Module that assembles all feature modules, registers global cache, throttler, TypeORM, and static file serving.analytics/ - Feature module exposing REST endpoints for agent analytics, cost breakdowns, token usage, savings, and message details; backed by TypeORM query services.auth/ - Wraps BetterAuth (better-auth package) into a NestJS module; provides SessionGuard and @CurrentUser() decorator.common/ - Barrel of cross-cutting concerns: ApiKeyGuard, cache interceptors, SPA fallback filter, HTTP error logger middleware, DTOs (create-agent, range-query, savings-query), and shared constants.config/ - Exports appConfig factory consumed by ConfigModule.forRoot.database/ - DatabaseModule configuring TypeORM with environment-driven connection settings.entities/ - TypeORM entities such as ApiKey.free-models/ - Identifies models that are free-tier or locally hosted and exposes them via its module.github/ - Polls GitHub releases for version-check notifications.health/ - Standard /health liveness and readiness endpoint.model-discovery/ - Discovers available models from each configured provider at runtime.model-prices/ - Fetches and caches per-token prices for cost accounting.notifications/ - Sends alerts when spend or error thresholds are crossed.otlp/ - Accepts OTLP HTTP trace data from instrumented clients and stores spans.public-stats/ - Serves aggregated, anonymized statistics for the public dashboard.routing/ - Core proxy: selects model based on scorer output and custom headers, forwards the OpenAI-compatible request, handles retries and fallback.scoring/ - Pure TypeScript complexity/specificity scorer: keyword trie, structural dimensions, sigmoid confidence, momentum, tier assignment.setup/ - First-run wizard that walks the user through provider configuration.sse/ - Server-Sent Events module for streaming router status updates to the dashboard.telemetry/ - Configures OpenTelemetry SDK and exports traces to a collector.emitDecoratorMetadata not set: NestJS DI silently breaks; add "emitDecoratorMetadata": true to tsconfig.json.BETTER_AUTH_URL missing: Auth middleware throws at startup; always set this env var even in development.SpaFallbackFilter only catches non-/api and non-/v1 paths; ensure all your custom routes start with /api/ or /v1/.BETTER_AUTH_URL starting with https://; using an HTTP URL in production will leave HSTS disabled—use a TLS-terminating reverse proxy.upgrade-insecure-requests breaks LAN deploys: The bootstrap explicitly sets this to null; do not re-enable it via Helmet options on HTTP-only LAN deployments.DatabaseModule must explicitly list or glob entities; add any new entity to the module's entities array or its glob pattern.DASHBOARD_CACHE_TTL_MS is in milliseconds; @nestjs/cache-manager v2+ expects milliseconds, but v1 expects seconds—pin cache-manager to the version matching your @nestjs/cache-manager version.I have dropped the Manifest AI Router Backend source into `packages/backend/src/`.
I also have `USAGE.md` in the same directory.
Please help me integrate this into my existing Node.js/TypeScript project step by step:
1. Read `USAGE.md` for the full setup instructions, required dependencies, and environment variables.
2. Read `packages/backend/src/main.ts` to understand the bootstrap flow.
3. Read `packages/backend/src/app.module.ts` to understand which NestJS modules are wired.
4. Read `packages/backend/src/scoring/index.ts` to understand the public scoring API.
Then:
- Install all required npm dependencies listed in USAGE.md.
- Update my `tsconfig.json` to enable `experimentalDecorators` and `emitDecoratorMetadata`.
- Create or update my `.env` file with the required environment variables.
- Wire the `bootstrap()` function from `main.ts` as my process entrypoint.
- Show me how to call `detectSpecificity` and `scanMessages` from the scoring module in a standalone script.
- If I need to add a custom protected endpoint, show me how to use `ApiKeyGuard` from `common/guards/api-key.guard.ts`.
Point out any conflicts with my existing code and suggest how to resolve them.
The upstream project is the Manifest AI Router (manifest-cms backend domain).
The upstream project is licensed under the terms stated in source/LICENSE (see the repository at github.com/mnfst/manifest). The README states the license badge links to LICENSE in the repository root. Review that file before redistributing. The legacy manifest npm package is deprecated; the current distribution is the Docker image manifestdotbuild/manifest.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
SaaS, AI & Subscription Products
Free