agentleFS
theRizwantheRizwan/FlagshipRouter/CLAUDE.md

FlagshipRouter

CLAUDE.md231 starsChanged 56 days agoMITView on GitHub

FlagshipRouter (flagshiprouter-app) — a local AI routing gateway + Next.js dashboard. It exposes one OpenAI-compatible endpoint (/v1/*) and routes traffic to free upstream providers with format translation, model-combo fallback, multi-account fallback, OAuth/API-key credential management, token refresh and usage tracking. Two published artifacts live in this one repo: - The dashboard + gateway (root package.json, flagshiprouter-app) — the Next.js server that does the actual routing. - The CLI launcher (cli/, npm package flagshiprouter) — a separate package that starts the server,…

  • Reads credentials
  • Installs packages

The file

We split this CLAUDE.md into the rules it gives an agent

4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Never hardcode the product name, slug, data-dir name, CLI-tool provider key or repo URL.

    line 14
  2. Very specific:

    Default runtime port is 20128 (dashboard at /dashboard, API at /v1).

    line 39
  3. Very specific:

    Never hardcode role/block/model strings — use open-sse/translator/schema/ and open-sse/config/ constants.

    line 84
  4. Very specific:

    Add a provider: copy providers/REGISTRY_TEMPLATE.js, add models to config/providerModels.js.

    line 88

≈ “Common” is an estimate: at least 1 in 5 of the 28,633 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

What this is

FlagshipRouter (flagshiprouter-app) — a local AI routing gateway + Next.js dashboard. It exposes one OpenAI-compatible endpoint (/v1/*) and routes traffic to free upstream providers with format translation, model-combo fallback, multi-account fallback, OAuth/API-key credential management, token refresh and usage tracking.

Two published artifacts live in this one repo:

  • The dashboard + gateway (root package.json, flagshiprouter-app) — the Next.js server that does the actual routing.
  • The CLI launcher (cli/, npm package flagshiprouter) — a separate package that starts the server, opens the browser UI and manages the tray. It has its own package.json, version, and build.

Brand, provider policy and model renames — brand.json is the single source

  • Never hardcode the product name, slug, data-dir name, CLI-tool provider key or repo URL. ESM code imports BRAND from open-sse/config/brand.js; CommonJS reads cli/src/brand.js (CLI) or require("…/brand.json") (src/mitm, updater). Locale files use {{brand}} / {{slug}} placeholders filled by src/i18n/runtime.js.
  • npm run brand:sync (scripts/brand-sync.mjs) stamps brand.json into both package.json files; cli/scripts/build-cli.js runs it and ships a copy of brand.json.
  • Free-only policy: open-sse/providers/policy.js (isProviderAllowed, ALLOWED_REGISTRY). Enforced in src/shared/constants/providers.js (dashboard + management APIs), createProviderConnection (connection store), getProviderCredentials and the chat handler (routing). The engine registry itself stays complete.
  • Model renames: open-sse/services/modelRenames.js. getModelInfo resolves public ids to targets; handleSingleModelChat wraps the response with presentResponseAsModel; /v1/models and /api/models/catalog list renames and hide targets.
  • Internal plumbing names: x-fr-* headers (custom-server ↔ app), FLAGSHIPROUTER_* env vars.
  • UI: new shell in src/shared/components/Sidebar.js / Header.js / BrandMark.js, tokens in src/app/globals.css; the Models screen (src/app/(dashboard)/dashboard/models/page.js) replaces the provider list (/dashboard/providers redirects unless custom endpoints are enabled).
  • Tests: tests/setup/providerPolicy.js disables the free-only policy for upstream engine tests; tests/unit/brand-policy.test.js covers the brand layer with the real policy.

The code lives in src/ (Next.js app + dashboard/compat APIs), open-sse/ (the provider-agnostic routing/translation engine), cli/ (the launcher package), and tests/.

Commands

One command from a fresh clone (install → build CLI bundle when stale → start CLI + browser UI):

npm run launch            # scripts/launch.mjs; CLI flags after --, e.g. npm run launch -- -p 20130

Dashboard/gateway (run from repo root):

cp .env.example .env
npm install
PORT=20128 NEXT_PUBLIC_BASE_URL=http://localhost:20128 npm run dev   # dev (webpack, port 20127 by default via next dev)
npm run build && PORT=20128 HOSTNAME=0.0.0.0 npm run start           # production
  • Bun variants: npm run dev:bun / build:bun / start:bun.
  • Default runtime port is 20128 (dashboard at /dashboard, API at /v1).
  • Lint: npx eslint . (config eslint.config.mjs, extends eslint-config-next).

CLI package (cli/):

npm run cli:pack       # build + npm pack from root
cd cli && npm run dev  # nodemon watch

Tests (vitest, in tests/, an independent ESM package — not wired into root npm test):

npm install                             # ROOT deps first — tests import from src/ which needs `open`, `undici`, etc.
cd tests && npm install                 # then tests' own deps (vitest) → tests/node_modules (allowed by tests/.gitignore)
npx vitest run                          # all tests; auto-discovers tests/vitest.config.js
npx vitest run unit/capabilities.test.js   # single file (path relative to tests/)

The committed tests/package.json test script hardcodes Unix paths (NODE_PATH=/tmp/node_modules …) — a shared-install workaround from upstream. On Windows (or anywhere), ignore it and use the npx vitest form above; vitest.config.js resolves the open-sse/@/ aliases from the repo root regardless of where vitest lives.

The suite is NOT expected to be all-green on a plain checkout. ~938 pass, ~64 fail. Judge regressions with tests/__baseline__/verify-no-regression.mjs, not a raw run. Expected red:

  • 26 catalogued in tests/__baseline__/known-fails.txt (rtk, oauth-cursor-auto-import, translator-request-normalization, …).
  • unit/embeddings.cloud.test.js imports cloud/src/handlers/embeddings.js — the cloud/ worker dir is not in this repo, so it always fails here.
  • unit/xai-oauth-service.test.js times out (5s) when the xAI endpoint-discovery fetch isn't reachable/mocked.
  • real/*.real.test.js make live provider calls — need credentials, skip otherwise.
  • *.real.test.js under tests/translator/real/ make live provider calls — skip unless credentials are set.
  • Regression baselines: tests/__baseline__/verify-*.mjs compare against committed snapshots (providers, aliases, OAuth URLs). Run these after touching provider registry / alias logic.

Architecture

Two authoritative docs already exist — read them before working in these areas rather than re-deriving:

  • docs/ARCHITECTURE.md — full system: request lifecycle, combo/account fallback, OAuth + token refresh, cloud sync, data model.
  • open-sse/AGENTS.md — the routing/translation engine's own conventions and "how to add a provider/executor/translator". Read this before editing anything under open-sse/.

Request flow (the thing to understand first)

src/app/api/v1/* route (Next rewrite maps /v1/* → /api/v1/* in next.config.mjs) → src/sse/handlers/chat.js (parse, combo expansion, account-selection loop) → open-sse/handlers/chatCore.js (detect source format, translate request, dispatch to executor, retry/refresh, stream setup) → open-sse/executors/* (per-provider upstream call; default.js handles any OpenAI-compatible provider) → open-sse/translator/* (client format ↔ provider format) → SSE back to client.

src/sse/ is the app-side entry glue; open-sse/ is the provider-agnostic engine (also usable standalone). Cross that boundary consciously.

Translator engine (open-sse/translator/)

  • Pivots through OpenAI as the intermediate format. A translator registered on an exact source:target pair (e.g. claude:kiro) runs as a direct route, skipping the lossy double-hop. Prefer a direct route for fragile pairs (thinking blocks, tool ids, non-base64 images, is_error).
  • Translators self-register via register(from, to, reqFn, resFn) as an import side effect — a new translator file MUST be imported in open-sse/translator/index.js or it never runs.
  • Never hardcode role/block/model strings — use open-sse/translator/schema/ and open-sse/config/ constants. Config-driven and DRY is enforced by convention here.

Provider registry (open-sse/providers/registry/*)

  • One file per provider. providers/registry/index.js is an auto-generated static import list — regenerate it with scripts/migrate-registry.mjs / injectDisplayToRegistry.mjs, don't hand-edit.
  • Add a provider: copy providers/REGISTRY_TEMPLATE.js, add models to config/providerModels.js. Only add an executor for non-OpenAI-compatible upstreams.

Persistence — IMPORTANT (ARCHITECTURE.md is stale here)

State is no longer db.json. It's a SQLite layer under src/lib/db/ with an adapter fallback chain (driver.js): bun:sqlite → better-sqlite3 (optional native dep) → node:sqlite (Node ≥22.5) → sql.js (pure-JS fallback, always works). better-sqlite3 is deliberately in optionalDependencies so install never fails without build tools.

  • src/lib/localDb.js is a backward-compat shim re-exporting src/lib/db/index.js. New code should import from @/lib/db/index.js; per-entity logic lives in src/lib/db/repos/*. Schema/migrations in src/lib/db/migrations/.
  • DB file location resolves via src/lib/db/paths.js (DATA_DIR, else ~/.flagshiprouter/).
  • Usage/logs (src/lib/usageDb.js, usage.json + log.txt) still live under ~/.flagshiprouter and do not follow DATA_DIR.

RTK token saver (open-sse/rtk/)

Pre-translate hooks that compress tool_result content in-place to cut tokens. Fail-open: any error returns null and leaves the body untouched — never throw out of them. Skips is_error/status:"error" results to preserve traces.

Conventions & gotchas

  • Plain JavaScript (ESM), no TypeScript. @/* path alias → src/* (jsconfig.json).
  • custom-server.js wraps the Next standalone server to derive client IP from the TCP socket and strip attacker-controlled X-Forwarded-For — trusting forwarding headers only from a loopback reverse proxy. Preserve this when touching request/IP/rate-limit code.
  • Security-sensitive env: JWT_SECRET (session cookie), INITIAL_PASSWORD (default 123456 — must override), API_KEY_SECRET, MACHINE_ID_SALT. Full env contract in .env.example and ARCHITECTURE.md's env matrix.
  • Binary/protobuf upstreams (kiro EventStream, cursor protobuf, commandcode NDJSON) don't round-trip through OpenAI — they're handled inside their own executor, not the translator.
  • Security-first on PRs: Security is the top priority when reviewing or creating PRs. Audit authentication, credential/token storage & leaks, header manipulation (X-Forwarded-For), and SSRF risks before functional logic. Always include explicit security warnings/notes when reporting PR reviews or changes to the user.
  • Versioning: root and cli/ are versioned independently; changes are logged in CHANGELOG.md. Commit style is Conventional Commits (fix(translator): …, feat(...)).

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.