Merge release/v3.8.0 into refactor/pages

Resolves conflicts in 9 files to bring 181 commits from release/v3.8.0 into
the dashboard refactor branch ahead of merging back to release.

Layout strategy: our pages overhaul (tabs→pages, restructured sidebar,
removed redundant headers, OpenCode Free no-auth card) is the source of
truth. Release's functional additions are adapted into our layout.

Conflict resolution:

- package.json/package-lock.json: take release's deps (axios bump, CLI v4
  deps, tls-client-node/wreq-js move to optionalDependencies); re-add our
  @xyflow/react addition; regenerate lockfile.
- src/shared/constants/sidebarVisibility.ts: keep our 9-section restructure
  — release's new IDs (limits, media, cli-tools, agents, cloud-agents,
  memory, skills, agent-skills, context-*) are all already present in our
  groups.
- src/i18n/messages/en.json: auto-merge picked up all release's new keys
  (autoCatalog*, quotaCutoffs*, systemTransforms*, schema-coercion, vision);
  only naming conflict was OmniSkills/AgentSkills — kept ours (no space).
- src/app/(dashboard)/dashboard/HomePageClient.tsx: kept our Provider
  Topology card; ported release's TierCoverageWidget (placed before
  topology).
- src/app/(dashboard)/dashboard/settings/page.tsx: kept our redirect to
  /settings/general (we moved tabs to separate pages); release's sticky
  tab CSS change is moot in our structure.
- src/app/(dashboard)/dashboard/skills/page.tsx: rerere applied — release
  hardcoded "OmniSkills" h1 was already removed by our header-cleanup
  refactor.
- src/app/(dashboard)/dashboard/agent-skills/page.tsx: both branches
  created this file independently with identical data source; kept our
  Tailwind-themed 2-column grid (release's version used inline styles).
- src/app/(dashboard)/dashboard/batch/page.tsx: kept our single-tab
  structure (FilesListTab moved to /batch/files page); ported release's
  onRefresh prop addition.
- src/app/(dashboard)/dashboard/batch/files/page.tsx (not in conflict but
  updated): added batches fetch + batches prop to preserve release's
  feature of showing related batches in the file detail modal.

Pre-existing typecheck errors in open-sse/services/contextManager.ts
(lines 141, 154, 167) come from release/v3.8.0 and are not introduced by
this merge.
This commit is contained in:
diegosouzapw
2026-05-17 01:14:21 -03:00
761 changed files with 78183 additions and 9093 deletions

View File

@@ -0,0 +1 @@
{"sessionId":"76a3e58d-d4b6-4002-bdb6-160ea48c702b","pid":1528501,"procStart":"16318804","acquiredAt":1778795671252}

View File

@@ -92,7 +92,7 @@ OMNIROUTE_USE_TURBOPACK=1
# OMNIROUTE_PORT=20128
# Hostname/bind address for the Next.js server.
# Used by: scripts/run-next.mjs (HOST), Playwright runner (HOSTNAME).
# Used by: scripts/dev/run-next.mjs (HOST), Playwright runner (HOSTNAME).
# Default: 0.0.0.0 (HOST) / 127.0.0.1 (HOSTNAME inside tests).
#HOST=0.0.0.0
#HOSTNAME=127.0.0.1
@@ -111,6 +111,12 @@ NODE_ENV=production
# Default: endpoint-proxy-salt | Change per-deployment for isolation.
MACHINE_ID_SALT=endpoint-proxy-salt
# Salt for deriving CLI machine-ID auth tokens (HMAC-SHA256).
# Used by: src/lib/machineToken.ts — rotates the local CLI auth token without
# touching code. Set to a new value to invalidate existing CLI tokens.
# Default: omniroute-cli-auth-v1
# OMNIROUTE_CLI_SALT=omniroute-cli-auth-v1
# Set true when running behind HTTPS (reverse proxy with TLS termination).
# Used by: src/lib/auth — sets the Secure flag on session cookies.
# Default: false | MUST be true in any non-localhost deployment.
@@ -137,6 +143,15 @@ ALLOW_API_KEY_REVEAL=false
# Used by: src/lib/compliance/index.ts — suppresses logs for specific keys.
# NO_LOG_API_KEY_IDS=key_abc123,key_def456
# Fallback per-day request budget applied to API keys whose `rate_limits`
# column is null. Default (unset/empty/malformed) preserves the legacy
# 1000/day, 5000/week, 20000/month windows so existing deployments do not
# silently lose rate limiting on upgrade.
# Set explicitly to "0" to opt out entirely (unlimited fallback). Any
# positive integer N enables N/day, 5N/week, 20N/month.
# Used by: src/shared/utils/apiKeyPolicy.ts — checkRateLimit() fallback.
# DEFAULT_RATE_LIMIT_PER_DAY=1000
# Maximum request body size in bytes (rejects larger payloads).
# Used by: src/shared/middleware/bodySizeGuard.ts — prevents oversized uploads.
# Default: 10485760 (10 MB)
@@ -412,6 +427,10 @@ PROVIDER_LIMITS_SYNC_INTERVAL_MINUTES=70
# Used by: open-sse/services/compression/engines/rtk/filterLoader.ts. Default: 0.
#OMNIROUTE_RTK_TRUST_PROJECT_FILTERS=0
# Skip the postinstall native-runtime warm-up (useful in CI / headless installs). Default: 0.
# Used by: scripts/postinstall.mjs.
#OMNIROUTE_SKIP_POSTINSTALL=0
# Force a DB healthcheck regardless of cadence. Default: 0.
# Used by: src/lib/db/core.ts::shouldRunDbHealthCheck().
#OMNIROUTE_FORCE_DB_HEALTHCHECK=0
@@ -527,6 +546,30 @@ GITHUB_OAUTH_CLIENT_ID=Iv1.b507a08c87ecfe98
# QODER_CLI_WORKSPACE=
# OMNIROUTE_QODER_WORKSPACE=
# ── Blackbox Web validated-token override (issue #2252) ──
# Used by: open-sse/executors/blackbox-web.ts. Blackbox `/api/chat` rejects
# requests whose `validated` field doesn't match the frontend `tk` token,
# returning HTTP 403 even with a valid session cookie + active subscription.
# Set this to the `tk` value exported from app.blackbox.ai's Next.js bundle
# to bypass the random-UUID fallback. Leave empty to keep the legacy behavior.
# BLACKBOX_WEB_VALIDATED_TOKEN=
# ── Vision Bridge OpenAI-compatible endpoint override (issue #2232) ──
# Used by: src/lib/guardrails/visionBridgeHelpers.ts. By default the
# vision-bridge guardrail sends non-Anthropic image-description calls to
# `https://api.openai.com/v1`, which fails with 401 if your operator doesn't
# have an OpenAI key or wants to use a different vision model
# (e.g., `google/gemini-2.0-flash` via the Gemini OpenAI-compat endpoint, or
# any model registered in OmniRoute via the self-loop endpoint).
#
# Set these two env vars to point the bridge at any OpenAI-compatible URL:
# - VISION_BRIDGE_BASE_URL=http://localhost:20128/v1 (OmniRoute self-loop)
# - VISION_BRIDGE_BASE_URL=https://generativelanguage.googleapis.com/v1beta/openai
# - VISION_BRIDGE_BASE_URL=https://openrouter.ai/api/v1
# Anthropic models (anthropic/*) keep their dedicated path and are unaffected.
# VISION_BRIDGE_BASE_URL=
# VISION_BRIDGE_API_KEY=
# ─────────────────────────────────────────────────────────────────────────────
# ⚠️ GOOGLE OAUTH (Antigravity, Gemini CLI) & OTHER PROVIDERS — REMOTE SERVERS
# ─────────────────────────────────────────────────────────────────────────────
@@ -656,6 +699,13 @@ GEMINI_CLI_USER_AGENT="google-api-nodejs-client/10.3.0"
# OMNIROUTE_CHATGPT_TLS_TIMEOUT_MS=60000
# OMNIROUTE_CHATGPT_TLS_GRACE_MS=10000
# ── Claude TLS sidecar (Chromium-fingerprinted client) ──
# Used by: open-sse/services/claudeTlsClient.ts — wire-level timeout for
# the bogdanfinn/tls-client koffi binding and the JS-side grace window
# layered on top of it when the native library is wedged.
# OMNIROUTE_CLAUDE_TLS_TIMEOUT_MS=60000
# OMNIROUTE_CLAUDE_TLS_GRACE_MS=10000
# ── Circuit breaker thresholds and reset windows ──
# Used by: open-sse/config/constants.ts → src/lib/resilience/settings.ts.
# Defaults match historical PROVIDER_PROFILES values (post-scaling for
@@ -772,6 +822,30 @@ APP_LOG_TO_FILE=true
# Default: 256 (Docker) | system default (npm)
# OMNIROUTE_MEMORY_MB=256
# ── CLI helpers (bin/cli/) ──
# Override UI language for CLI output. Accepts BCP-47 locale (e.g. en, pt-BR).
# Falls back to LC_ALL / LC_MESSAGES / LANG / en if unset.
# OMNIROUTE_LANG=en
# Show server logs inline when running in supervised mode (omniroute serve).
# Set to "1" to forward server stdout/stderr to the terminal.
# Equivalent to the --log flag on `omniroute serve`.
# OMNIROUTE_SHOW_LOG=1
# Bearer token injected as x-omniroute-cli-token header for machine-auth (task 8.12).
# Auto-generated on first run if machine-id is available; set manually to override.
# OMNIROUTE_CLI_TOKEN=
# Per-attempt HTTP timeout for CLI → server calls (milliseconds). Default: 30000.
# OMNIROUTE_HTTP_TIMEOUT_MS=30000
# Set to 1 to print retry/backoff details to stderr during CLI commands.
# OMNIROUTE_VERBOSE=0
# Custom directory for CLI plugin discovery (omniroute-cmd-* packages).
# Default: ~/.omniroute/plugins/ Override in dev/CI to point at a local plugin tree.
# OMNIROUTE_PLUGIN_PATH=
# ── Prompt cache (system prompt deduplication) ──
# Used by: open-sse/services — caches identical system prompts across requests.
# PROMPT_CACHE_MAX_SIZE=50 # Max cached entries (default: 50)
@@ -938,7 +1012,7 @@ APP_LOG_TO_FILE=true
# Used by: open-sse/utils/cursorVersionDetector.ts. Default: probed automatically.
# CURSOR_STATE_DB_PATH=
# Direct Cursor bearer token used by scripts/cursor-tap.cjs (developer tooling).
# Direct Cursor bearer token used by scripts/ad-hoc/cursor-tap.cjs (developer tooling).
# CURSOR_TOKEN=
# Log Responses API SSE-to-JSON translation details.
@@ -1056,8 +1130,8 @@ APP_LOG_TO_FILE=true
# ═══════════════════════════════════════════════════════════════════════════════
# 25. TEST & E2E
# ═══════════════════════════════════════════════════════════════════════════════
# Used by scripts/run-next-playwright.mjs, scripts/smoke-electron-packaged.mjs,
# scripts/run-ecosystem-tests.mjs and scripts/uninstall.mjs.
# Used by scripts/dev/run-next-playwright.mjs, scripts/dev/smoke-electron-packaged.mjs,
# scripts/dev/run-ecosystem-tests.mjs and scripts/build/uninstall.mjs.
# Production deployments should leave every value below unset.
# E2E bootstrap mode for the Playwright runner. Accepted: auth | fresh | reuse.
@@ -1099,7 +1173,7 @@ APP_LOG_TO_FILE=true
# Number of parallel translation requests (default 4).
# OMNIROUTE_TRANSLATION_CONCURRENCY=4
# Electron smoke harness (used by scripts/smoke-electron-packaged.mjs).
# Electron smoke harness (used by scripts/dev/smoke-electron-packaged.mjs).
# ELECTRON_SMOKE_URL=http://127.0.0.1:20128/login
# ELECTRON_SMOKE_TIMEOUT_MS=45000
# ELECTRON_SMOKE_SETTLE_MS=2000

View File

@@ -165,7 +165,7 @@ body:
description: "Which commands or tests should prove this bug is fixed?"
placeholder: |
Example:
- node --import tsx/esm --test tests/unit/my-file.test.ts
- node --import tsx --test tests/unit/my-file.test.ts
- npm run test:coverage
validations:
required: false

View File

@@ -59,7 +59,7 @@ body:
description: "List the commands that must pass before this issue can be closed."
placeholder: |
Example:
- node --import tsx/esm --test tests/unit/my-suite.test.ts
- node --import tsx --test tests/unit/my-suite.test.ts
- npm run test:coverage
validations:
required: true

View File

@@ -207,7 +207,7 @@ jobs:
cache: npm
- run: npm ci
- run: npm run check:node-runtime
- run: node --import tsx/esm --test --test-concurrency=1 --test-shard=${{ matrix.shard }}/2 tests/unit/*.test.ts
- run: node --import tsx --test --test-concurrency=1 --test-shard=${{ matrix.shard }}/2 tests/unit/*.test.ts
node-24-compat:
name: Node 24 Compatibility (${{ matrix.shard }}/2)
@@ -231,7 +231,7 @@ jobs:
- run: npm ci
- run: npm run check:node-runtime
- run: npm run build
- run: node --import tsx/esm --test --test-concurrency=1 --test-shard=${{ matrix.shard }}/2 tests/unit/*.test.ts
- run: node --import tsx --test --test-concurrency=1 --test-shard=${{ matrix.shard }}/2 tests/unit/*.test.ts
node-26-compat:
name: Node 26 Compatibility (${{ matrix.shard }}/2)
@@ -255,7 +255,7 @@ jobs:
- run: npm ci
- run: npm run check:node-runtime
- run: npm run build
- run: node --import tsx/esm --test --test-concurrency=1 --test-shard=${{ matrix.shard }}/2 tests/unit/*.test.ts
- run: node --import tsx --test --test-concurrency=1 --test-shard=${{ matrix.shard }}/2 tests/unit/*.test.ts
test-coverage:
name: Coverage
@@ -462,7 +462,7 @@ jobs:
cache: npm
- run: npm ci
- run: npm run check:node-runtime
- run: node --import tsx/esm --test --test-force-exit --test-concurrency=1 --test-shard=${{ matrix.shard }}/2 tests/integration/*.test.ts
- run: node --import tsx --test --test-force-exit --test-concurrency=1 --test-shard=${{ matrix.shard }}/2 tests/integration/*.test.ts
test-security:
name: Security Tests

View File

@@ -27,7 +27,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 1

View File

@@ -26,7 +26,7 @@ jobs:
actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 1

1
.gitignore vendored
View File

@@ -76,6 +76,7 @@ open-sse/test/*
.github/instructions/codacy.instructions.md
# Playwright
.playwright-mcp/
test-results/
playwright-report/
blob-report/

View File

@@ -12,6 +12,9 @@ npm run check:any-budget:t11
# Strict env-doc sync (FASE 2)
node scripts/check/check-env-doc-sync.mjs
# CLI i18n consistency check — all t() keys must exist in en.json (FASE 8.3)
node scripts/check/check-cli-i18n.mjs
# i18n docs drift advisory (FASE 5) — warn-only on pre-commit; CI enforces strict.
node scripts/i18n/check-translation-drift.mjs --warn || \
echo "⚠️ i18n drift detected. Run 'npm run i18n:run' to update locale mirrors."

View File

@@ -100,3 +100,4 @@ test-results/
playwright-report/
blob-report/
coverage/
@omniroute/

View File

@@ -1,2 +0,0 @@
[ 556ms] [ERROR] Loading the script 'https://static.cloudflareinsights.com/beacon.min.js/v8c78df7c7c0f484497ecbca7046644da1771523124516' violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. The action has been blocked. @ https://ai.aitradepulse.com/login:0
[ 987ms] [VERBOSE] [DOM] Input elements should have autocomplete attributes (suggested: "new-password"): (More info: https://goo.gl/9p2vKq) %o @ https://ai.aitradepulse.com/login:0

View File

@@ -1,2 +0,0 @@
[ 310ms] [ERROR] Loading the script 'https://static.cloudflareinsights.com/beacon.min.js/v8c78df7c7c0f484497ecbca7046644da1771523124516' violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. The action has been blocked. @ https://ai.aitradepulse.com/login:0
[ 458ms] [VERBOSE] [DOM] Input elements should have autocomplete attributes (suggested: "new-password"): (More info: https://goo.gl/9p2vKq) %o @ https://ai.aitradepulse.com/login:0

View File

@@ -1,2 +0,0 @@
[ 300ms] [ERROR] Loading the script 'https://static.cloudflareinsights.com/beacon.min.js/v8c78df7c7c0f484497ecbca7046644da1771523124516' violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. The action has been blocked. @ https://ai.aitradepulse.com/login:0
[ 382ms] [VERBOSE] [DOM] Input elements should have autocomplete attributes (suggested: "new-password"): (More info: https://goo.gl/9p2vKq) %o @ https://ai.aitradepulse.com/login:0

View File

@@ -1,2 +0,0 @@
[ 283ms] [ERROR] Loading the script 'https://static.cloudflareinsights.com/beacon.min.js/v8c78df7c7c0f484497ecbca7046644da1771523124516' violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. The action has been blocked. @ https://ai.aitradepulse.com/login:0
[ 373ms] [VERBOSE] [DOM] Input elements should have autocomplete attributes (suggested: "new-password"): (More info: https://goo.gl/9p2vKq) %o @ https://ai.aitradepulse.com/login:0

View File

@@ -1,2 +0,0 @@
[ 160ms] [ERROR] Loading the script 'https://static.cloudflareinsights.com/beacon.min.js/v8c78df7c7c0f484497ecbca7046644da1771523124516' violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. The action has been blocked. @ https://ai.aitradepulse.com/login:0
[ 268ms] [VERBOSE] [DOM] Input elements should have autocomplete attributes (suggested: "new-password"): (More info: https://goo.gl/9p2vKq) %o @ https://ai.aitradepulse.com/login:0

View File

@@ -1 +0,0 @@
[ 282ms] [ERROR] Loading the script 'https://static.cloudflareinsights.com/beacon.min.js/v8c78df7c7c0f484497ecbca7046644da1771523124516' violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. The action has been blocked. @ https://ai.aitradepulse.com/dashboard/providers:0

View File

@@ -1 +0,0 @@
[ 155ms] [ERROR] Loading the script 'https://static.cloudflareinsights.com/beacon.min.js/v8c78df7c7c0f484497ecbca7046644da1771523124516' violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. The action has been blocked. @ https://ai.aitradepulse.com/dashboard/combos:0

View File

@@ -1,5 +0,0 @@
- generic [active] [ref=e1]:
- link "Skip to content" [ref=e2] [cursor=pointer]:
- /url: "#main-content"
- generic [ref=e8]: Loading...
- alert [ref=e9]

View File

@@ -1,5 +0,0 @@
- generic [active] [ref=e1]:
- link "Skip to content" [ref=e2] [cursor=pointer]:
- /url: "#main-content"
- generic [ref=e8]: Loading...
- alert [ref=e9]

View File

@@ -1,19 +0,0 @@
- generic [ref=e1]:
- link "Skip to content" [ref=e2] [cursor=pointer]:
- /url: "#main-content"
- generic [ref=e6]:
- generic [ref=e10]:
- generic [ref=e11]:
- generic [ref=e13]: hub
- generic [ref=e14]: OmniRoute
- heading "Sign in" [level=1] [ref=e15]
- paragraph [ref=e16]: Enter your password to continue
- generic [ref=e17]:
- generic [ref=e18]:
- text: Password
- textbox "Enter your password to continue" [active] [ref=e21]
- paragraph [ref=e22]: "Default password: CHANGEME (unless INITIAL_PASSWORD was set)"
- button "Continue" [ref=e23] [cursor=pointer]
- link "Forgot password?" [ref=e25] [cursor=pointer]:
- /url: /forgot-password
- alert [ref=e9]

View File

@@ -1,5 +0,0 @@
- generic [active] [ref=e1]:
- link "Skip to content" [ref=e2] [cursor=pointer]:
- /url: "#main-content"
- generic [ref=e8]: Loading...
- alert [ref=e9]

View File

@@ -1,5 +0,0 @@
- generic [active] [ref=e1]:
- link "Skip to content" [ref=e2] [cursor=pointer]:
- /url: "#main-content"
- generic [ref=e8]: Loading...
- alert [ref=e9]

View File

@@ -1,5 +0,0 @@
- generic [active] [ref=e1]:
- link "Skip to content" [ref=e2] [cursor=pointer]:
- /url: "#main-content"
- generic [ref=e8]: Loading...
- alert [ref=e9]

File diff suppressed because it is too large Load Diff

View File

@@ -1,158 +0,0 @@
- generic [active] [ref=e1]:
- link "Skip to content" [ref=e2] [cursor=pointer]:
- /url: "#main-content"
- generic [ref=e3]:
- complementary [ref=e5]:
- link "Skip to content" [ref=e6] [cursor=pointer]:
- /url: "#main-content"
- link "OmniRoute v3.7.9" [ref=e12] [cursor=pointer]:
- /url: /dashboard
- img [ref=e14]
- generic [ref=e26]:
- heading "OmniRoute" [level=1] [ref=e27]
- generic [ref=e28]: v3.7.9
- navigation "Main navigation" [ref=e29]:
- generic [ref=e30]:
- link "home Home" [ref=e31] [cursor=pointer]:
- /url: /dashboard
- generic [ref=e32]: home
- generic [ref=e33]: Home
- link "api Endpoints" [ref=e34] [cursor=pointer]:
- /url: /dashboard/endpoint
- generic [ref=e35]: api
- generic [ref=e36]: Endpoints
- link "vpn_key API Manager" [ref=e37] [cursor=pointer]:
- /url: /dashboard/api-manager
- generic [ref=e38]: vpn_key
- generic [ref=e39]: API Manager
- link "dns Providers" [ref=e40] [cursor=pointer]:
- /url: /dashboard/providers
- generic [ref=e41]: dns
- generic [ref=e42]: Providers
- link "layers Combos" [ref=e43] [cursor=pointer]:
- /url: /dashboard/combos
- generic [ref=e44]: layers
- generic [ref=e45]: Combos
- link "view_list Batch Testing" [ref=e46] [cursor=pointer]:
- /url: /dashboard/batch
- generic [ref=e47]: view_list
- generic [ref=e48]: Batch Testing
- link "account_balance_wallet Costs" [ref=e49] [cursor=pointer]:
- /url: /dashboard/costs
- generic [ref=e50]: account_balance_wallet
- generic [ref=e51]: Costs
- link "analytics Analytics" [ref=e52] [cursor=pointer]:
- /url: /dashboard/analytics
- generic [ref=e53]: analytics
- generic [ref=e54]: Analytics
- link "cached Cache" [ref=e55] [cursor=pointer]:
- /url: /dashboard/cache
- generic [ref=e56]: cached
- generic [ref=e57]: Cache
- link "tune Limits & Quotas" [ref=e58] [cursor=pointer]:
- /url: /dashboard/limits
- generic [ref=e59]: tune
- generic [ref=e60]: Limits & Quotas
- link "perm_media Media" [ref=e61] [cursor=pointer]:
- /url: /dashboard/cache/media
- generic [ref=e62]: perm_media
- generic [ref=e63]: Media
- generic [ref=e64]:
- paragraph [ref=e65]: Context & Cache
- link "compress Caveman" [ref=e66] [cursor=pointer]:
- /url: /dashboard/context/caveman
- generic [ref=e67]: compress
- generic [ref=e68]: Caveman
- link "filter_alt RTK" [ref=e69] [cursor=pointer]:
- /url: /dashboard/context/rtk
- generic [ref=e70]: filter_alt
- generic [ref=e71]: RTK
- link "hub Compression Combos" [ref=e72] [cursor=pointer]:
- /url: /dashboard/context/combos
- generic [ref=e73]: hub
- generic [ref=e74]: Compression Combos
- generic [ref=e75]:
- paragraph [ref=e76]: CLI
- link "terminal Tools" [ref=e77] [cursor=pointer]:
- /url: /dashboard/cli-tools
- generic [ref=e78]: terminal
- generic [ref=e79]: Tools
- link "smart_toy Agents" [ref=e80] [cursor=pointer]:
- /url: /dashboard/agents
- generic [ref=e81]: smart_toy
- generic [ref=e82]: Agents
- link "psychology Memory" [ref=e83] [cursor=pointer]:
- /url: /dashboard/memory
- generic [ref=e84]: psychology
- generic [ref=e85]: Memory
- link "auto_fix_high Skills" [ref=e86] [cursor=pointer]:
- /url: /dashboard/skills
- generic [ref=e87]: auto_fix_high
- generic [ref=e88]: Skills
- generic [ref=e89]:
- paragraph [ref=e90]: System
- link "description Logs" [ref=e91] [cursor=pointer]:
- /url: /dashboard/logs
- generic [ref=e92]: description
- generic [ref=e93]: Logs
- link "policy Audit Log" [ref=e94] [cursor=pointer]:
- /url: /dashboard/audit
- generic [ref=e95]: policy
- generic [ref=e96]: Audit Log
- link "webhook Webhooks" [ref=e97] [cursor=pointer]:
- /url: /dashboard/webhooks
- generic [ref=e98]: webhook
- generic [ref=e99]: Webhooks
- link "health_and_safety Health" [ref=e100] [cursor=pointer]:
- /url: /dashboard/health
- generic [ref=e101]: health_and_safety
- generic [ref=e102]: Health
- link "dns Proxy" [ref=e103] [cursor=pointer]:
- /url: /dashboard/system/proxy
- generic [ref=e104]: dns
- generic [ref=e105]: Proxy
- link "settings Settings" [ref=e106] [cursor=pointer]:
- /url: /dashboard/settings
- generic [ref=e107]: settings
- generic [ref=e108]: Settings
- generic [ref=e109]:
- paragraph [ref=e110]: Help
- link "menu_book Docs" [ref=e111] [cursor=pointer]:
- /url: /docs
- generic [ref=e112]: menu_book
- generic [ref=e113]: Docs
- link "bug_report Issues" [ref=e114] [cursor=pointer]:
- /url: https://github.com/diegosouzapw/OmniRoute/issues
- generic [ref=e115]: bug_report
- generic [ref=e116]: Issues
- link "campaign Changelog" [ref=e117] [cursor=pointer]:
- /url: /dashboard/changelog
- generic [ref=e118]: campaign
- generic [ref=e119]: Changelog
- generic [ref=e120]:
- button "restart_alt Restart" [ref=e121]:
- generic: restart_alt
- text: Restart
- button "power_settings_new Shutdown" [ref=e122]:
- generic: power_settings_new
- text: Shutdown
- main [ref=e123]:
- generic [ref=e124]:
- button "menu" [ref=e126]:
- generic: menu
- generic [ref=e127]:
- button "🇺🇸 EN expand_more" [ref=e129]:
- generic [ref=e130]: 🇺🇸
- generic [ref=e131]: EN
- generic: expand_more
- button "Switch to light mode" [ref=e132]:
- generic: light_mode
- button "logout" [ref=e133]:
- generic: logout
- navigation "Breadcrumb" [ref=e136]:
- link "Dashboard" [ref=e138] [cursor=pointer]:
- /url: /dashboard
- generic [ref=e139]:
- generic [ref=e140]:
- generic [ref=e141]: Providers
- alert [ref=e155]

View File

@@ -1,158 +0,0 @@
- generic [active] [ref=e1]:
- link "Skip to content" [ref=e2] [cursor=pointer]:
- /url: "#main-content"
- generic [ref=e3]:
- complementary [ref=e5]:
- link "Skip to content" [ref=e6] [cursor=pointer]:
- /url: "#main-content"
- link "OmniRoute v3.7.9" [ref=e12] [cursor=pointer]:
- /url: /dashboard
- img [ref=e14]
- generic [ref=e26]:
- heading "OmniRoute" [level=1] [ref=e27]
- generic [ref=e28]: v3.7.9
- navigation "Main navigation" [ref=e29]:
- generic [ref=e30]:
- link "home Home" [ref=e31] [cursor=pointer]:
- /url: /dashboard
- generic [ref=e32]: home
- generic [ref=e33]: Home
- link "api Endpoints" [ref=e34] [cursor=pointer]:
- /url: /dashboard/endpoint
- generic [ref=e35]: api
- generic [ref=e36]: Endpoints
- link "vpn_key API Manager" [ref=e37] [cursor=pointer]:
- /url: /dashboard/api-manager
- generic [ref=e38]: vpn_key
- generic [ref=e39]: API Manager
- link "dns Providers" [ref=e40] [cursor=pointer]:
- /url: /dashboard/providers
- generic [ref=e41]: dns
- generic [ref=e42]: Providers
- link "layers Combos" [ref=e43] [cursor=pointer]:
- /url: /dashboard/combos
- generic [ref=e44]: layers
- generic [ref=e45]: Combos
- link "view_list Batch Testing" [ref=e46] [cursor=pointer]:
- /url: /dashboard/batch
- generic [ref=e47]: view_list
- generic [ref=e48]: Batch Testing
- link "account_balance_wallet Costs" [ref=e49] [cursor=pointer]:
- /url: /dashboard/costs
- generic [ref=e50]: account_balance_wallet
- generic [ref=e51]: Costs
- link "analytics Analytics" [ref=e52] [cursor=pointer]:
- /url: /dashboard/analytics
- generic [ref=e53]: analytics
- generic [ref=e54]: Analytics
- link "cached Cache" [ref=e55] [cursor=pointer]:
- /url: /dashboard/cache
- generic [ref=e56]: cached
- generic [ref=e57]: Cache
- link "tune Limits & Quotas" [ref=e58] [cursor=pointer]:
- /url: /dashboard/limits
- generic [ref=e59]: tune
- generic [ref=e60]: Limits & Quotas
- link "perm_media Media" [ref=e61] [cursor=pointer]:
- /url: /dashboard/cache/media
- generic [ref=e62]: perm_media
- generic [ref=e63]: Media
- generic [ref=e64]:
- paragraph [ref=e65]: Context & Cache
- link "compress Caveman" [ref=e66] [cursor=pointer]:
- /url: /dashboard/context/caveman
- generic [ref=e67]: compress
- generic [ref=e68]: Caveman
- link "filter_alt RTK" [ref=e69] [cursor=pointer]:
- /url: /dashboard/context/rtk
- generic [ref=e70]: filter_alt
- generic [ref=e71]: RTK
- link "hub Compression Combos" [ref=e72] [cursor=pointer]:
- /url: /dashboard/context/combos
- generic [ref=e73]: hub
- generic [ref=e74]: Compression Combos
- generic [ref=e75]:
- paragraph [ref=e76]: CLI
- link "terminal Tools" [ref=e77] [cursor=pointer]:
- /url: /dashboard/cli-tools
- generic [ref=e78]: terminal
- generic [ref=e79]: Tools
- link "smart_toy Agents" [ref=e80] [cursor=pointer]:
- /url: /dashboard/agents
- generic [ref=e81]: smart_toy
- generic [ref=e82]: Agents
- link "psychology Memory" [ref=e83] [cursor=pointer]:
- /url: /dashboard/memory
- generic [ref=e84]: psychology
- generic [ref=e85]: Memory
- link "auto_fix_high Skills" [ref=e86] [cursor=pointer]:
- /url: /dashboard/skills
- generic [ref=e87]: auto_fix_high
- generic [ref=e88]: Skills
- generic [ref=e89]:
- paragraph [ref=e90]: System
- link "description Logs" [ref=e91] [cursor=pointer]:
- /url: /dashboard/logs
- generic [ref=e92]: description
- generic [ref=e93]: Logs
- link "policy Audit Log" [ref=e94] [cursor=pointer]:
- /url: /dashboard/audit
- generic [ref=e95]: policy
- generic [ref=e96]: Audit Log
- link "webhook Webhooks" [ref=e97] [cursor=pointer]:
- /url: /dashboard/webhooks
- generic [ref=e98]: webhook
- generic [ref=e99]: Webhooks
- link "health_and_safety Health" [ref=e100] [cursor=pointer]:
- /url: /dashboard/health
- generic [ref=e101]: health_and_safety
- generic [ref=e102]: Health
- link "dns Proxy" [ref=e103] [cursor=pointer]:
- /url: /dashboard/system/proxy
- generic [ref=e104]: dns
- generic [ref=e105]: Proxy
- link "settings Settings" [ref=e106] [cursor=pointer]:
- /url: /dashboard/settings
- generic [ref=e107]: settings
- generic [ref=e108]: Settings
- generic [ref=e109]:
- paragraph [ref=e110]: Help
- link "menu_book Docs" [ref=e111] [cursor=pointer]:
- /url: /docs
- generic [ref=e112]: menu_book
- generic [ref=e113]: Docs
- link "bug_report Issues" [ref=e114] [cursor=pointer]:
- /url: https://github.com/diegosouzapw/OmniRoute/issues
- generic [ref=e115]: bug_report
- generic [ref=e116]: Issues
- link "campaign Changelog" [ref=e117] [cursor=pointer]:
- /url: /dashboard/changelog
- generic [ref=e118]: campaign
- generic [ref=e119]: Changelog
- generic [ref=e120]:
- button "restart_alt Restart" [ref=e121]:
- generic: restart_alt
- text: Restart
- button "power_settings_new Shutdown" [ref=e122]:
- generic: power_settings_new
- text: Shutdown
- main [ref=e123]:
- generic [ref=e124]:
- button "menu" [ref=e126]:
- generic: menu
- generic [ref=e127]:
- button "🇺🇸 EN expand_more" [ref=e129]:
- generic [ref=e130]: 🇺🇸
- generic [ref=e131]: EN
- generic: expand_more
- button "Switch to light mode" [ref=e132]:
- generic: light_mode
- button "logout" [ref=e133]:
- generic: logout
- navigation "Breadcrumb" [ref=e136]:
- link "Dashboard" [ref=e138] [cursor=pointer]:
- /url: /dashboard
- generic [ref=e139]:
- generic [ref=e140]:
- generic [ref=e141]: Combos
- alert [ref=e155]

View File

@@ -0,0 +1,31 @@
rules:
- id: cli-no-sqlite-direct
patterns:
- pattern: new Database(...)
paths:
include:
- "bin/**"
exclude:
- "bin/cli/sqlite.mjs"
message: >
Direct SQLite access in bin/ is banned. Use src/lib/db/* helpers or
withRuntime() from bin/cli/runtime.mjs. See CLAUDE.md hard rule #5 and
bin/cli/CONVENTIONS.md.
languages: [js]
severity: ERROR
- id: cli-no-raw-sql
patterns:
- pattern: $DB.prepare("INSERT INTO ...")
- pattern: $DB.prepare("DELETE FROM ...")
- pattern: $DB.prepare("UPDATE $TABLE SET ...")
paths:
include:
- "bin/**"
exclude:
- "bin/cli/sqlite.mjs"
message: >
Raw SQL in bin/ is banned. Use src/lib/db/* helpers. See CLAUDE.md
hard rule #5 and bin/cli/CONVENTIONS.md.
languages: [js]
severity: ERROR

View File

@@ -0,0 +1,4 @@
node_modules
dist
*.log
.DS_Store

View File

@@ -0,0 +1,7 @@
src
tests
tsconfig.json
tsup.config.ts
node_modules
.DS_Store
*.log

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 OmniRoute contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,45 +1,138 @@
# @omniroute/opencode-provider
Provider plugin for connecting [OpenCode](https://github.com/anomalyco/opencode) to [OmniRoute](https://github.com/diegosouzapw/OmniRoute).
Helper for connecting [OpenCode](https://opencode.ai) to a running [OmniRoute](https://github.com/diegosouzapw/OmniRoute) AI gateway.
The package emits a **schema-valid entry** for `opencode.json` (`https://opencode.ai/config.json`) that delegates the actual runtime to [`@ai-sdk/openai-compatible`](https://www.npmjs.com/package/@ai-sdk/openai-compatible). It does not ship any new HTTP client — OmniRoute already exposes an OpenAI-compatible surface, and OpenCode already speaks it through the AI SDK.
> Pre-1.0. The API may still change. See `CHANGELOG` in the OmniRoute repo for breaking notes.
## Installation
```bash
npm install @omniroute/opencode-provider
npm install --save-dev @omniroute/opencode-provider
# or
pnpm add -D @omniroute/opencode-provider
```
## Usage
You also need OpenCode's own runtime dep, but that's a transitive concern — OpenCode itself ships with `@ai-sdk/openai-compatible`. This package only **generates configuration**.
```javascript
import { createOmniRouteProvider } from "@omniroute/opencode-provider";
## Quick start
const provider = createOmniRouteProvider({
baseURL: "http://localhost:20128/v1",
apiKey: "your-omniroute-api-key",
### 1. Scaffold a fresh `opencode.json`
```ts
import { writeFileSync } from "node:fs";
import { buildOmniRouteOpenCodeConfig } from "@omniroute/opencode-provider";
const config = buildOmniRouteOpenCodeConfig({
baseURL: "http://localhost:20128", // or your OmniRoute deployment URL
apiKey: process.env.OMNIROUTE_API_KEY ?? "sk_omniroute",
});
writeFileSync("opencode.json", JSON.stringify(config, null, 2));
```
Then configure OpenCode to use the provider:
The resulting `opencode.json`:
```jsonc
// OpenCode settings
{
"provider": provider
"$schema": "https://opencode.ai/config.json",
"provider": {
"omniroute": {
"npm": "@ai-sdk/openai-compatible",
"name": "OmniRoute",
"options": {
"baseURL": "http://localhost:20128/v1",
"apiKey": "sk_omniroute",
},
"models": {
"claude-opus-4-5-thinking": { "name": "claude-opus-4-5-thinking" },
"claude-sonnet-4-5-thinking": { "name": "claude-sonnet-4-5-thinking" },
"gemini-3.1-pro-high": { "name": "gemini-3.1-pro-high" },
"gemini-3-flash": { "name": "gemini-3-flash" },
},
},
},
}
```
### 2. Merge into an existing `opencode.json`
```ts
import { createOmniRouteProvider } from "@omniroute/opencode-provider";
const provider = createOmniRouteProvider({
baseURL: "http://localhost:20128",
apiKey: process.env.OMNIROUTE_API_KEY!,
});
// Place `provider` under provider.omniroute in your opencode.json
```
If you already have an `opencode.json` on disk and want a non-destructive merge from the OmniRoute side, use `omniroute config opencode` from the CLI (ships with the main OmniRoute install) — it preserves comments and unrelated keys.
## API
### `createOmniRouteProvider(options)`
### `createOmniRouteProvider(options): OpenCodeProviderEntry`
Creates an OpenCode-compatible provider object that routes requests through OmniRoute.
Returns the value to place under `provider.omniroute` inside `opencode.json`.
**Options:**
| Option | Type | Required | Description |
| ------------- | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------ |
| `baseURL` | `string` | Yes | OmniRoute base URL. Accepts `http://host:port` **or** `http://host:port/v1`. Trailing slashes are tolerated. |
| `apiKey` | `string` | Yes | OmniRoute API key. Use `sk_omniroute` for local installs that have `REQUIRE_API_KEY=false`. |
| `displayName` | `string` | No | Custom name shown in the OpenCode UI. Default: `"OmniRoute"`. |
| `models` | `string[]` | No | Override the surfaced model catalog. Default: 4 curated models — see `OMNIROUTE_DEFAULT_OPENCODE_MODELS`. |
| `modelLabels` | `Record<string,string>` | No | Human-readable labels keyed by model id. |
| Option | Type | Required | Description |
| --------- | -------- | -------- | ---------------------------------------------------------- |
| `baseURL` | `string` | Yes | OmniRoute API base URL (e.g., `http://localhost:20128/v1`) |
| `apiKey` | `string` | Yes | OmniRoute API key |
| `model` | `string` | No | Model identifier (default: `"opencode"`) |
Throws on empty/invalid input — `baseURL` must be a real URL, `apiKey` must be a non-empty string.
**Returns:** An OpenCode-compatible provider object with `id`, `name`, `npm`, `options`, and `auth` fields.
### `buildOmniRouteOpenCodeConfig(options): OpenCodeConfigDocument`
Same options as above, but returns a full document with `$schema` and the `provider.omniroute` wrapper, ready to write to `opencode.json`.
### `normalizeBaseURL(input): string`
Exported for completeness. Strips trailing `/`, deduplicates a trailing `/v1`, and re-appends exactly one `/v1`. Throws on empty / non-URL input.
### Constants
- `OMNIROUTE_PROVIDER_KEY``"omniroute"` (the key used under `provider.*`).
- `OMNIROUTE_PROVIDER_NPM``"@ai-sdk/openai-compatible"` (the runtime delegate).
- `OPENCODE_CONFIG_SCHEMA``"https://opencode.ai/config.json"`.
- `OMNIROUTE_DEFAULT_OPENCODE_MODELS` — readonly list of 4 default model ids.
## Custom model catalog
```ts
import { createOmniRouteProvider } from "@omniroute/opencode-provider";
createOmniRouteProvider({
baseURL: "http://localhost:20128",
apiKey: "sk_omniroute",
models: ["auto", "claude-opus-4-7", "gpt-5.5"],
modelLabels: {
auto: "Auto-Combo (recommended)",
"claude-opus-4-7": "Claude Opus 4.7",
"gpt-5.5": "GPT-5.5",
},
});
```
Duplicates and empty strings are dropped automatically, and order is preserved.
## Troubleshooting
- **Requests 404 with `/v1/v1/...`** — you're on an old version (≤1.0.0). Update to `≥0.1.0` of this re-released package. The new build normalises `baseURL` automatically.
- **`401 Invalid API key`** — your OmniRoute instance has `REQUIRE_API_KEY=true` but the key you supplied doesn't exist there. Create one via the dashboard or set `REQUIRE_API_KEY=false` and use `sk_omniroute`.
- **OpenCode complains the provider has no models** — supply an explicit `models` list; the default 4 may be hidden by your provider visibility settings.
## Related
- [OmniRoute](https://github.com/diegosouzapw/OmniRoute) — the AI gateway this plugin targets.
- [OpenCode](https://opencode.ai) — the agentic CLI consumer.
- [`@ai-sdk/openai-compatible`](https://www.npmjs.com/package/@ai-sdk/openai-compatible) — the runtime delegate that actually speaks HTTP.
## License
MIT — see [`LICENSE`](./LICENSE).

View File

@@ -1,3 +0,0 @@
import OmniRouteProvider from "./index.js";
export { OmniRouteProvider };
export default OmniRouteProvider;

View File

@@ -1 +0,0 @@
export { createOmniRouteProvider, default as default } from "./index.ts";

View File

@@ -1,54 +0,0 @@
/**
* OpenCode provider plugin for OmniRoute AI Gateway
*
* Usage:
* import { createOmniRouteProvider } from "@omniroute/opencode-provider";
* const provider = createOmniRouteProvider({
* baseURL: "http://localhost:20128/v1",
* apiKey: "your-api-key",
* });
*
* Then add to OpenCode settings:
* { "provider": provider }
*/
export interface OmniRouteProviderOptions {
baseURL: string;
apiKey: string;
model?: string;
}
export interface OmniRouteProvider {
id: string;
name: string;
npm: string;
options: Record<string, unknown>;
auth: { type: string; apiKey: string };
}
export function createOmniRouteProvider(options: OmniRouteProviderOptions): OmniRouteProvider {
if (!options.baseURL) {
throw new Error("baseURL is required");
}
if (!options.apiKey) {
throw new Error("apiKey is required");
}
const baseURL = options.baseURL.replace(/\/+$/, "");
return {
id: "omniroute",
name: "OmniRoute AI Gateway",
npm: "@omniroute/opencode-provider",
options: {
baseURL: `${baseURL}/v1`,
model: options.model || "opencode",
},
auth: {
type: "apiKey",
apiKey: options.apiKey,
},
};
}
export default createOmniRouteProvider;

File diff suppressed because it is too large Load Diff

View File

@@ -1,20 +1,59 @@
{
"name": "@omniroute/opencode-provider",
"version": "1.0.0",
"description": "OpenCode provider plugin for OmniRoute AI Gateway",
"version": "0.1.0",
"description": "OpenCode provider helper for the OmniRoute AI Gateway. Generates a schema-valid provider entry for opencode.json that delegates the runtime to @ai-sdk/openai-compatible.",
"type": "module",
"main": "index.js",
"types": "index.d.ts",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
},
"files": [
"index.js",
"index.d.ts",
"README.md"
"dist",
"README.md",
"LICENSE"
],
"scripts": {
"build": "tsup",
"clean": "rm -rf dist",
"test": "node --import tsx/esm --test tests/**/*.test.ts",
"prepublishOnly": "npm run clean && npm run build && npm test"
},
"keywords": [
"omniroute",
"opencode",
"provider"
"opencode-ai",
"ai-sdk",
"openai-compatible",
"provider",
"ai-gateway",
"llm-router"
],
"author": "OmniRoute contributors",
"license": "MIT",
"peerDependencies": {}
"repository": {
"type": "git",
"url": "git+https://github.com/diegosouzapw/OmniRoute.git",
"directory": "@omniroute/opencode-provider"
},
"bugs": {
"url": "https://github.com/diegosouzapw/OmniRoute/issues"
},
"homepage": "https://github.com/diegosouzapw/OmniRoute/tree/main/%40omniroute/opencode-provider#readme",
"engines": {
"node": ">=20.20.2"
},
"publishConfig": {
"access": "public"
},
"devDependencies": {
"tsup": "^8.5.0",
"tsx": "^4.20.0",
"typescript": "^5.9.0"
}
}

View File

@@ -0,0 +1,160 @@
/**
* OpenCode provider plugin for OmniRoute AI Gateway.
*
* Generates an OpenCode-compatible provider object that points to a running
* OmniRoute instance. The output follows the OpenCode config schema
* (https://opencode.ai/config.json) and delegates the runtime to
* `@ai-sdk/openai-compatible` so OpenCode can drive any OmniRoute-exposed
* model through its standard OpenAI-compatible client.
*
* Two ways to consume the helper:
*
* 1. As code, when you build your own opencode.json programmatically:
*
* ```ts
* import { buildOmniRouteOpenCodeConfig } from "@omniroute/opencode-provider";
* const config = buildOmniRouteOpenCodeConfig({
* baseURL: "http://localhost:20128",
* apiKey: "sk_omniroute",
* });
* // config -> { $schema, provider: { omniroute: { npm, name, options, models } } }
* ```
*
* 2. As a single-provider entry to merge into an existing opencode.json:
*
* ```ts
* import { createOmniRouteProvider } from "@omniroute/opencode-provider";
* const provider = createOmniRouteProvider({ baseURL, apiKey });
* // provider -> the value to place under provider.omniroute in opencode.json
* ```
*
* Note: `baseURL` accepts both `http://host:port` and `http://host:port/v1`.
* The helper normalises trailing slashes / `/v1` so you never get `/v1/v1`.
*/
export const OMNIROUTE_PROVIDER_KEY = "omniroute" as const;
export const OMNIROUTE_PROVIDER_NPM = "@ai-sdk/openai-compatible" as const;
export const OPENCODE_CONFIG_SCHEMA = "https://opencode.ai/config.json" as const;
/**
* Default catalog of models surfaced to OpenCode when the caller does not
* supply an explicit `models` list. Mirrors the curated set used by the
* OmniRoute dashboard's "OpenCode" config generator.
*/
export const OMNIROUTE_DEFAULT_OPENCODE_MODELS = [
"claude-opus-4-5-thinking",
"claude-sonnet-4-5-thinking",
"gemini-3.1-pro-high",
"gemini-3-flash",
] as const;
export interface OmniRouteProviderOptions {
/** OmniRoute base URL, with or without trailing `/v1`. Required. */
baseURL: string;
/** OmniRoute API key. Required. Use `sk_omniroute` for local instances without REQUIRE_API_KEY. */
apiKey: string;
/** Override the display name shown in OpenCode. Default: `"OmniRoute"`. */
displayName?: string;
/** Override the model catalog. Defaults to `OMNIROUTE_DEFAULT_OPENCODE_MODELS`. */
models?: readonly string[];
/** Optional human-readable labels keyed by model id. */
modelLabels?: Record<string, string>;
}
export interface OpenCodeProviderEntry {
/** Identifier of the OpenCode runtime package that will speak to OmniRoute. */
npm: typeof OMNIROUTE_PROVIDER_NPM;
/** Display name in the OpenCode UI. */
name: string;
/** Options forwarded to `@ai-sdk/openai-compatible`. */
options: {
baseURL: string;
apiKey: string;
};
/** Model catalog surfaced to OpenCode. */
models: Record<string, { name: string }>;
}
export interface OpenCodeConfigDocument {
$schema: typeof OPENCODE_CONFIG_SCHEMA;
provider: {
[OMNIROUTE_PROVIDER_KEY]: OpenCodeProviderEntry;
};
}
function requireNonEmpty(value: unknown, field: string): string {
if (typeof value !== "string") {
throw new TypeError(`@omniroute/opencode-provider: ${field} must be a string`);
}
const trimmed = value.trim();
if (!trimmed) {
throw new Error(`@omniroute/opencode-provider: ${field} is required and cannot be empty`);
}
return trimmed;
}
/**
* Normalise the user-supplied baseURL so the final `options.baseURL` always
* ends in exactly one `/v1`. Accepts both `http://host` and `http://host/v1`.
*/
export function normalizeBaseURL(rawBaseURL: string): string {
const trimmed = requireNonEmpty(rawBaseURL, "baseURL");
try {
// Reject malformed URLs early.
new URL(trimmed);
} catch {
throw new Error(
`@omniroute/opencode-provider: baseURL is not a valid URL: ${JSON.stringify(rawBaseURL)}`
);
}
return trimmed.replace(/\/+$/, "").replace(/\/v1$/, "") + "/v1";
}
/**
* Build the `provider.omniroute` entry for an OpenCode config document.
* The returned object is JSON-serialisable and safe to embed verbatim.
*/
export function createOmniRouteProvider(options: OmniRouteProviderOptions): OpenCodeProviderEntry {
const baseURL = normalizeBaseURL(options.baseURL);
const apiKey = requireNonEmpty(options.apiKey, "apiKey");
const modelList =
options.models && options.models.length > 0
? [...options.models]
: [...OMNIROUTE_DEFAULT_OPENCODE_MODELS];
const labels = options.modelLabels ?? {};
const models: Record<string, { name: string }> = {};
const seen = new Set<string>();
for (const raw of modelList) {
const id = typeof raw === "string" ? raw.trim() : "";
if (!id || seen.has(id)) continue;
seen.add(id);
const label = typeof labels[id] === "string" && labels[id].trim() ? labels[id].trim() : id;
models[id] = { name: label };
}
return {
npm: OMNIROUTE_PROVIDER_NPM,
name: options.displayName?.trim() || "OmniRoute",
options: { baseURL, apiKey },
models,
};
}
/**
* Build a full OpenCode config document (with `$schema` + `provider.omniroute`).
* Useful when scaffolding a fresh `opencode.json`.
*/
export function buildOmniRouteOpenCodeConfig(
options: OmniRouteProviderOptions
): OpenCodeConfigDocument {
return {
$schema: OPENCODE_CONFIG_SCHEMA,
provider: {
[OMNIROUTE_PROVIDER_KEY]: createOmniRouteProvider(options),
},
};
}
export default createOmniRouteProvider;

View File

@@ -0,0 +1,121 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
buildOmniRouteOpenCodeConfig,
createOmniRouteProvider,
normalizeBaseURL,
OMNIROUTE_DEFAULT_OPENCODE_MODELS,
OMNIROUTE_PROVIDER_NPM,
OPENCODE_CONFIG_SCHEMA,
} from "../src/index.ts";
test("normalizeBaseURL preserves a bare host:port", () => {
assert.equal(normalizeBaseURL("http://localhost:20128"), "http://localhost:20128/v1");
});
test("normalizeBaseURL strips trailing slashes", () => {
assert.equal(normalizeBaseURL("http://localhost:20128////"), "http://localhost:20128/v1");
});
test("normalizeBaseURL deduplicates an existing /v1 suffix", () => {
assert.equal(normalizeBaseURL("http://localhost:20128/v1"), "http://localhost:20128/v1");
assert.equal(normalizeBaseURL("http://localhost:20128/v1/"), "http://localhost:20128/v1");
});
test("normalizeBaseURL rejects empty input", () => {
assert.throws(() => normalizeBaseURL(" "), /baseURL is required/);
});
test("normalizeBaseURL rejects malformed URLs", () => {
assert.throws(() => normalizeBaseURL("not a url"), /not a valid URL/);
});
test("createOmniRouteProvider validates required fields", () => {
assert.throws(
() => createOmniRouteProvider({ baseURL: "", apiKey: "x" } as never),
/baseURL is required/
);
assert.throws(
() => createOmniRouteProvider({ baseURL: "http://x", apiKey: "" } as never),
/apiKey is required/
);
});
test("createOmniRouteProvider produces the OpenCode-compatible shape", () => {
const provider = createOmniRouteProvider({
baseURL: "http://localhost:20128",
apiKey: "sk_omniroute",
});
assert.equal(provider.npm, OMNIROUTE_PROVIDER_NPM);
assert.equal(provider.name, "OmniRoute");
assert.equal(provider.options.baseURL, "http://localhost:20128/v1");
assert.equal(provider.options.apiKey, "sk_omniroute");
assert.equal(typeof provider.models, "object");
});
test("createOmniRouteProvider seeds the default model catalog", () => {
const provider = createOmniRouteProvider({
baseURL: "http://localhost:20128",
apiKey: "sk_omniroute",
});
const modelIds = Object.keys(provider.models).sort();
const defaultIds = [...OMNIROUTE_DEFAULT_OPENCODE_MODELS].sort();
assert.deepEqual(modelIds, defaultIds);
for (const id of defaultIds) {
assert.equal(provider.models[id]?.name, id);
}
});
test("createOmniRouteProvider honours a custom models list and labels", () => {
const provider = createOmniRouteProvider({
baseURL: "http://localhost:20128",
apiKey: "sk_omniroute",
models: ["auto", "claude-opus-4-7"],
modelLabels: { auto: "Auto-Combo", "claude-opus-4-7": "Opus 4.7" },
});
assert.deepEqual(Object.keys(provider.models), ["auto", "claude-opus-4-7"]);
assert.equal(provider.models.auto.name, "Auto-Combo");
assert.equal(provider.models["claude-opus-4-7"].name, "Opus 4.7");
});
test("createOmniRouteProvider deduplicates and trims model ids", () => {
const provider = createOmniRouteProvider({
baseURL: "http://localhost:20128",
apiKey: "sk_omniroute",
models: [" auto ", "auto", "", "claude-opus-4-7"],
});
assert.deepEqual(Object.keys(provider.models), ["auto", "claude-opus-4-7"]);
});
test("createOmniRouteProvider honours displayName override", () => {
const provider = createOmniRouteProvider({
baseURL: "http://localhost:20128",
apiKey: "sk_omniroute",
displayName: "Local OmniRoute",
});
assert.equal(provider.name, "Local OmniRoute");
});
test("buildOmniRouteOpenCodeConfig wraps the provider with the OpenCode schema", () => {
const doc = buildOmniRouteOpenCodeConfig({
baseURL: "http://localhost:20128/v1",
apiKey: "sk_omniroute",
});
assert.equal(doc.$schema, OPENCODE_CONFIG_SCHEMA);
assert.equal(typeof doc.provider.omniroute, "object");
assert.equal(doc.provider.omniroute.options.baseURL, "http://localhost:20128/v1");
});
test("config document is JSON-serialisable", () => {
const doc = buildOmniRouteOpenCodeConfig({
baseURL: "http://localhost:20128",
apiKey: "sk_omniroute",
});
const round = JSON.parse(JSON.stringify(doc));
assert.deepEqual(round, doc);
});

View File

@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"declaration": true,
"isolatedModules": true,
"forceConsistentCasingInFileNames": true,
"noUncheckedIndexedAccess": false,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src/**/*.ts"],
"exclude": ["dist", "node_modules", "tests"]
}

View File

@@ -0,0 +1,18 @@
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/index.ts"],
format: ["esm", "cjs"],
dts: true,
clean: true,
sourcemap: false,
splitting: false,
treeshake: true,
target: "node20",
outDir: "dist",
minify: false,
});
// CJS consumers should prefer named imports (`require(pkg).createOmniRouteProvider`).
// The `default` export is also exposed for ESM ergonomics, which makes tsup warn
// about mixed exports — that's expected and harmless for this package.

View File

@@ -2,22 +2,127 @@
## [Unreleased]
### Added
- **feat(i18n):** add Azerbaijani (az / 🇦🇿) language support — new locale in `config/i18n.json` (source of truth), `src/i18n/messages/az.json` (UI strings), `docs/i18n/az/` (full documentation set), README language bar, docs i18n index, and both translation pipeline scripts (`generate-multilang.mjs`, `i18n_autotranslate.py`). Total supported languages: **42**.
- **feat(limits):** per-window quota cutoffs across all providers with usage data — operators can set per-quota-window thresholds (e.g. `session=95%, weekly=80%`) with cascading resolver (connection → provider default → global 98%) and zero-latency gate when nothing is configured. New migration 056, new `GET /api/providers/quota-windows` endpoint, and Dashboard Limits cutoff modal. ([#2267](https://github.com/diegosouzapw/OmniRoute/pull/2267) — thanks @payne0420)
- **feat(api-keys):** configurable default rate limits via `DEFAULT_RATE_LIMIT_PER_DAY` env var — replaces hardcoded 1000/day fallback with Zod-validated configuration while preserving secure defaults for existing deployments. ([#2266](https://github.com/diegosouzapw/OmniRoute/pull/2266) — thanks @gleber)
- **feat(authz):** `managementPolicy` accepts API keys with `manage` scope — enables headless/programmatic management (provisioning providers, setting rate limits) without a browser session. ([#2265](https://github.com/diegosouzapw/OmniRoute/pull/2265) — thanks @gleber)
- **feat(termux):** Android/Termux headless support — auto-detect Android platform for headless mode (no browser open), move `wreq-js` and `tls-client-node` to `optionalDependencies` for ARM compatibility, lazy-load WS proxy with graceful 503 when unavailable, set `GYP_DEFINES` for `better-sqlite3` ARM build, extended build timeout to 600s. ([#2273](https://github.com/diegosouzapw/OmniRoute/pull/2273) — thanks @t-way666)
- **feat(deepseek-web):** full DeepSeek web API executor with Keccak PoW solver (`DeepSeekHashV1`), SSE streaming, and auto-refresh session management via `ds_session_id`. ([#2295](https://github.com/diegosouzapw/OmniRoute/pull/2295) — thanks @oyi77)
- **feat(cc-bridge):** config-driven per-provider system-block transform DSL — operators can now configure system prompt transformations per-provider via Dashboard settings UI. ([#2286](https://github.com/diegosouzapw/OmniRoute/pull/2286), closes #2260 — thanks @mrmm)
- **feat(batch):** global rate-limit header cache with 60s TTL + 24h time-based retry window — shares rate-limit throttle state across sequential batches and uses time-based retry limits for robust large-batch processing. ([#2299](https://github.com/diegosouzapw/OmniRoute/pull/2299) — thanks @hartmark)
- **feat(providers):** improve Cohere provider support, expanding models and accurately updating OpenAI context limits. ([#2313](https://github.com/diegosouzapw/OmniRoute/pull/2313) — thanks @backryun)
- **feat(claude-web):** implement session-based Claude Web executor with auto-refresh authentication — enables direct Claude Web API access without an API key. ([#2283](https://github.com/diegosouzapw/OmniRoute/pull/2283) — thanks @oyi77)
- **feat(skills):** add 5 CLI skill manifests + AgentSkills / OmniSkills dashboard pages — enables external AI agents to discover and invoke OmniRoute capabilities. ([#2284](https://github.com/diegosouzapw/OmniRoute/pull/2284))
- **feat(cli):** full i18n support — 42 locales, `--lang` flag, `config lang get/set/list` commands for CLI language selection. ([#2285](https://github.com/diegosouzapw/OmniRoute/pull/2285))
### Changed
- **CLI**: Refactored architecture to use Commander.js as framework. Monolith `bin/cli-commands.mjs` (2853 lines) removed — commands now live individually in `bin/cli/commands/`. No breaking changes in normal usage; all previously listed subcommands continue working.
### Removed
- `bin/cli-commands.mjs` — replaced by modular structure in `bin/cli/commands/`.
- `bin/cli/index.mjs` — replaced by `bin/cli/program.mjs` + `bin/cli/commands/registry.mjs`.
- `bin/cli/args.mjs` — replaced by Commander.js native parsing support.
- **refactor(@omniroute/opencode-provider):** complete rewrite of the npm helper. The `1.0.0` artifact was non-functional — `index.js` re-exported from `.ts` (unrunnable at install time) and the emitted shape didn't match the OpenCode `https://opencode.ai/config.json` schema. The new release ships a real `tsup` build (CJS + ESM + `.d.ts`), schema-correct output (`npm: "@ai-sdk/openai-compatible"`, with `models` catalog), `baseURL` deduplication (no more `/v1/v1`), input validation, 13 unit tests, and full documentation in [`docs/frameworks/OPENCODE.md`](docs/frameworks/OPENCODE.md). Versioned as `0.1.0` to signal the pre-1.0 reset.
- **chore(npm):** [`@omniroute/opencode-provider@0.1.0`](https://www.npmjs.com/package/@omniroute/opencode-provider) published to npmjs.com under the new `@omniroute` org. Install with `npm install --save-dev @omniroute/opencode-provider`.
- **BREAKING**: dropped Node 20.x support. Minimum Node version is now 22.22.2 (or 24.0.0+). Required because http-proxy-middleware 4.x requires `node >=22.15.0`. Users on Node 20 must upgrade — see [`package.json` engines field](package.json) and the README Node badge.
- **Platform overhaul (FASES 1-9):** scripts cleanup, `.env` audit, `/docs` restructure, diagrams folder, i18n pipelines (docs + UI), `/src/app/docs` sync, CI gates.
- **Scripts:** `scripts/` reorganized into 6 subfolders (`build/`, `dev/`, `check/`, `docs/`, `i18n/`, `ad-hoc/`); 23 one-shot scripts archived to the `archive/scripts-scratch-pre-3.8` branch.
- **Environment:** `.env.example` cleaned (-11 orphan vars, +63 missing vars, 11 hardcoded URLs/timeouts promoted to env); new strict `scripts/check/check-env-doc-sync.mjs` validates code ↔ `.env.example``docs/reference/ENVIRONMENT.md` parity.
- **Docs:** `/docs` restructured into 8 functional subfolders (`architecture/`, `guides/`, `reference/`, `frameworks/`, `routing/`, `security/`, `compression/`, `ops/`); ~899 cross-references rewritten.
- **Diagrams:** new `docs/diagrams/` with 8 canonical Mermaid sources + SVG exports, linked into 9 docs.
- **i18n (docs):** hash-based incremental pipeline (`config/i18n.json`, `scripts/i18n/run-translation.mjs`, `.i18n-state.json`); old `i18n_autotranslate.py` and `generate-multilang.mjs` deprecated.
- **i18n (UI):** `scripts/i18n/sync-ui-keys.mjs` propagates `en.json` keys to all 40 locales (no missing keys; coverage ≥ 85.8%); cosmetic `DocsI18n.tsx` removed (locale handling unified via `next-intl`).
- **`/src/app/docs`:** drift fixes (179 → 177 providers, 13 → 14 strategies, 36 → 37 MCP tools); YAML frontmatter added to all docs; `ApiExplorer` consumes `docs/reference/openapi.yaml` (19 endpoints); `content.ts` updated (37 MCP tool groups, 7 internal deployment guide hrefs).
- **CI gates:** strict env-doc-sync in pre-commit; `check:doc-links` validates internal markdown refs; new `docs-sync-strict` and `i18n-ui-coverage` jobs in `.github/workflows/ci.yml`.
### Security
- **fix(oauth/windsurf):** Windsurf Firebase token refresh now reads `WINDSURF_CONFIG.firebaseApiKey` instead of `process.env.WINDSURF_FIREBASE_API_KEY` directly.
- **fix(kiro/translator):** assistant-first conversations no longer collide on a single `conversationId`.
- **fix(utils/publicCreds):** `decodePublicCred()` no longer silently mangles raw credential overrides that don't match `RAW_VALUE_PATTERN`.
- **fix(auth/extractApiKey):** `x-api-key` fallback now only triggers when the request also carries an `anthropic-version` header.
- **fix(providers/qoder):** the OAuth+PAT disambiguation message now actually surfaces.
- **fix(authz/clientApi):** when `REQUIRE_API_KEY=false`, an invalid Bearer no longer 401s the whole request — falls through to anonymous (matching the "no auth required" semantics of the flag) with a single warning log carrying the masked key id. Fixes the surprise 401s that hit CLI integrations (Codex Desktop auto-config, Hermes Agent) that ship a stale Bearer in their saved config. (#2257)
### Fixed
- **Docs:** 270 broken internal markdown links repaired (consequence of `/docs` subfolder restructure not relativizing all paths). Categories: 241 `i18n-relative`, 14 `parent-relative`, 9 `screenshots`, 2 deleted-RFC, 4 misc. Now `npm run check:doc-links` PASS with 0 broken links.
- **fix(claude):** guard orphan tool_use/tool_result pairs before upstream send, resolving a critical Anthropic 400 error on truncated histories. ([#2312](https://github.com/diegosouzapw/OmniRoute/pull/2312) — thanks @mrmm)
- **fix(ui):** remove count from batch removal button for cleaner interface. ([#2309](https://github.com/diegosouzapw/OmniRoute/pull/2309) — thanks @hartmark)
- **fix(sse):** strip stale `Content-Encoding`, `Content-Length`, and `Transfer-Encoding` headers on non-streaming forward — fixes JSON truncation on gzipped Gemini responses where clients honoring `Content-Length` read only the compressed byte count of the decompressed payload, causing `"Unterminated string in JSON"` parse failures. RFC 7230 §6.1 compliant. ([#2264](https://github.com/diegosouzapw/OmniRoute/pull/2264) — thanks @gleber)
- **fix(executor/claude-code):** store tool-name round-trip metadata in non-enumerable `_toolNameMap` so it survives in-memory but is stripped by `JSON.stringify()` — prevents internal OmniRoute metadata from leaking to upstream providers. ([#2254](https://github.com/diegosouzapw/OmniRoute/pull/2254) — thanks @Rikonorus)
- **fix(streaming):** strip upstream `Content-Encoding`, `Content-Length`, and `Transfer-Encoding` headers from SSE responses — prevents client-side decompression corruption when the proxy serves plain-text event streams through nginx/caddy. ([#2253](https://github.com/diegosouzapw/OmniRoute/pull/2253) — thanks @Rikonorus)
- **fix(kiro):** harden OpenAI-to-Kiro translator for API compliance: recursively strip `additionalProperties` and empty `required: []` from tool schemas; merge consecutive assistant messages; prepend synthetic user for assistant-first conversations; convert orphaned tool results to inline text; enforce `origin: "AI_EDITOR"` on all history user messages; deterministic `uuidv5` session caching. Closes #2213. ([#2251](https://github.com/diegosouzapw/OmniRoute/pull/2251) — thanks @8mbe)
- **fix(models):** sync managed model aliases with provider model visibility — remove aliases when models are hidden/deleted, skip alias creation for hidden models during sync, restore aliases when unhidden, cross-connection safety guard prevents pruning aliases still valid from another connection. ([#2250](https://github.com/diegosouzapw/OmniRoute/pull/2250) — thanks @InkshadeWoods)
- **fix(models/cleanup):** align managed model cleanup for imported models — provider-level "Delete All" now also removes synced available model storage; delete-alias button only shown for alias-source rows; compatible models section uses proper 3-way source-aware delete logic. ([#2261](https://github.com/diegosouzapw/OmniRoute/pull/2261) — thanks @InkshadeWoods)
- **fix(auth):** accept `x-api-key` header in `extractApiKey` so Anthropic-native clients (Claude Code, `@anthropic-ai/sdk`) hit the same per-key policy enforcement as Bearer clients. Previously these requests were treated as anonymous, bypassing model/budget/rate-limit policies and showing up as `NULL` in `usage_history.api_key_id` (~50% of traffic invisible in Costs/Analytics). `Authorization: Bearer` still wins when both are present (back-compat). (#2225)
- **fix(translator/claude-to-openai):** stop including `cache_creation_input_tokens` in `prompt_tokens`. Anthropic pads short prompts up to a 1024-token minimum on cache creation, so a 2-token `"hi"` could be reported as ~2008 `prompt_tokens` and inflate downstream billing (Sub2API/NewAPI/OneAPI) ~250x. `prompt_tokens` now matches the dashboard "Total In" (`input + cache_read`); `cache_creation_tokens` is exposed separately in `prompt_tokens_details.cache_creation_tokens` for auditing. (#2215)
- **fix(ui/claude-extra-usage):** clarify the toggle-success notification text to spell out the toggle→effect relationship ("Claude extra-usage blocking enabled/disabled" instead of the ambiguous "blocked/allowed"). (#2157)
- **fix(providers/qoder):** disambiguate the "Local CLI runtime is not installed" error when a user pastes a Personal Access Token but the connection is in OAuth/CLI-flavored mode. The test route now surfaces a single actionable message ("switch this connection to API Key auth") instead of cascading CLI + 401 errors. (#2247)
- **fix(dashboard/api-manager):** route custom OpenAI-/Anthropic-compatible provider IDs through `getProviderDisplayName` so the model grouping label shows `Compatible (openai)` instead of leaking the raw synthetic `openai-compatible-chat-<uuid>` value. (#2021)
- **fix(providers/blackbox-web):** add `BLACKBOX_WEB_VALIDATED_TOKEN` env override and 403 token-error disambiguation. Blackbox `/api/chat` started rejecting requests whose `validated` field didn't match the frontend `tk` token, even with a valid cookie + active subscription. Operators with the real token can now set the env var; otherwise the previous random-UUID fallback still ships, and a 403 with a token-specific body now surfaces a one-line "set BLACKBOX_WEB_VALIDATED_TOKEN" hint instead of the generic "cookie expired" message. (#2252)
- **fix(guardrails/vision-bridge):** add `VISION_BRIDGE_BASE_URL` + `VISION_BRIDGE_API_KEY` env overrides so non-Anthropic vision-bridge calls can be routed through OmniRoute's own `/v1` self-loop, Google's Gemini OpenAI-compat endpoint, OpenRouter, or any other OpenAI-compatible URL — instead of being hardcoded to `https://api.openai.com/v1` (which failed with 401 for users without an OpenAI key, even when they configured `visionBridgeModel: "google/gemini-2.0-flash"`). Anthropic models keep their dedicated path. (#2232)
- **docs(security):** document the ToS-violation hot spot of `ANTIGRAVITY_CREDITS=always` in `STEALTH_GUIDE.md`, including why it draws Google abuse detection more aggressively than free-tier-only usage and the recommended posture (`=retry`, Auto-Combo spread, per-connection RPM caps). (#2246)
- **fix(translator/developer-role):** convert OpenAI `developer` role → `system` by default for non-OpenAI-family providers. Codex/Responses API clients hitting DeepSeek (and other OpenAI-compatible gateways: MiniMax, Mimo, GLM, Fireworks, Together, etc.) were getting `400: unknown variant 'developer'` because the previous default preserved `developer` for any `targetFormat=openai` upstream. New default: preserve only for `openai`/`azure-openai`/`azure`/`github` (and any id containing `"openai"`); convert everywhere else. Operators can still force preservation per-model via the dashboard "Compatibility → preserveOpenAIDeveloperRole = true" toggle. (#2281)
- **fix(api/combos):** add API-key-safe `GET /v1/combos` endpoint that mirrors the `/v1/models` auth model. Previously `/api/combos` was management-gated, blocking read-only integrations (e.g. `opencode-omniroute-auth` plugin) that need to enrich combo capabilities from a normal Bearer API key. The new endpoint projects only public metadata (name, strategy, model ids, providerId, description) — internal routing details like `connectionId`, weights, and labels are stripped. `/api/combos` (management) is unchanged. (#2300)
- **fix(embeddings/registry):** add DeepInfra to the embedding provider registry. Custom embedding models on the DeepInfra provider (e.g. `Qwen/Qwen3-Embedding-8B`, `BAAI/bge-large-en-v1.5`) were failing with `Unknown embedding provider: deepinfra` because the registry only included Nebius/OpenAI/Together/Fireworks/NVIDIA/etc. Now ships 8 popular DeepInfra embedding models out of the box and routes through `https://api.deepinfra.com/v1/openai/embeddings`. (#2298)
- **fix(opencode-zen):** flag `qwen3.6-plus` and `qwen3.6-plus-free` with `targetFormat: "claude"`. The opencode-zen upstream returns Claude-format SSE bodies (`type: "message_start"`, no `choices` array) for these Qwen3.6 models even when the request hits the OpenAI-compatible `/chat/completions` endpoint, causing client-side Zod failures (`expected "choices" (array), received undefined`). Routing them through the Claude `/messages` endpoint + translator fixes the format mismatch. (#2292)
- **fix(settings):** default `debugMode` to `true` on fresh installations — the Debug sidebar section (Translator, Playground, Search Tools) was hidden on new installs because `debugMode` was not in the settings defaults object, making `data?.debugMode === true` evaluate to `false`. The toggle in System & Storage appeared active but had no effect until manually set. Now all sidebar sections are visible out of the box.
- **fix(providers/command-code):** send required `skills` and `stream` payload fields — Command Code upstream wrapper now includes `skills: ""` and forces `params.stream: true` to align with upstream API requirements. Validation probe defaults to `deepseek/deepseek-v4-flash`. ([#2271](https://github.com/diegosouzapw/OmniRoute/pull/2271) — thanks @ddarkr)
- **fix(sse):** strip stale `Content-Encoding`, `Content-Length`, and `Transfer-Encoding` from upstream responses — prevents JSON truncation and `ZlibError` on gzipped provider responses forwarded through the proxy. ([#2291](https://github.com/diegosouzapw/OmniRoute/pull/2291) — thanks @thepigdestroyer)
- **fix(sse):** remove dead-code flag leak in `claudeCodeToolRemapper` — eliminates a stale boolean flag that could cause incorrect tool remapping behavior on subsequent requests. ([#2290](https://github.com/diegosouzapw/OmniRoute/pull/2290) — thanks @thepigdestroyer)
- **fix(ui):** v3.8.0 polish — connections border, sticky tabs, EN translations, save toasts, auto-combo catalog. ([#2305](https://github.com/diegosouzapw/OmniRoute/pull/2305) — thanks @mrmm)
- **fix:** remove implicit API key request caps — removes the default daily/weekly/monthly rate caps (1K/5K/20K) that silently applied 429s to API keys without explicit limits configured, causing unexpected throttling for operators who hadn't set custom rate policies. ([#2289](https://github.com/diegosouzapw/OmniRoute/pull/2289) — thanks @josephvoxone)
- **fix(auth+build):** Bearer manage scope on management routes + lazy-load deepseek PoW solver — unblocks MCP remote usage and Docker Next.js standalone builds. ([#2308](https://github.com/diegosouzapw/OmniRoute/pull/2308) — thanks @mrmm)
- **fix(migrations):** resolve version collision at migration slot 056 by renaming the quota thresholds migration to 057, and add batch deletion API with bulk cleanup support and batch/file management UI. ([#2294](https://github.com/diegosouzapw/OmniRoute/pull/2294) — thanks @hartmark)
- **chore:** ignore `.playwright-mcp/` generated artifacts (CSP error logs, accessibility tree snapshots) — removes tracked test artifacts and adds the directory to `.gitignore`. ([#2269](https://github.com/diegosouzapw/OmniRoute/pull/2269) — thanks @backryun)
- **chore:** tidy up deprecated models from Windsurf provider registry. ([#2279](https://github.com/diegosouzapw/OmniRoute/pull/2279) — thanks @backryun)
- **build(deps):** bump `actions/checkout` from 4 to 6 in CI workflows. ([#2288](https://github.com/diegosouzapw/OmniRoute/pull/2288))
- **build(deps):** regenerate `package-lock.json` to match `http-proxy-middleware` 4.x bump. ([#2228](https://github.com/diegosouzapw/OmniRoute/pull/2228) — thanks @NomenAK)
- **fix(streaming):** harden stream readiness detection — recognize OpenAI Responses API lifecycle events (`response.created`, `response.in_progress`, `response.output_item.added`) and Chat Completions start chunks as readiness signals; switch GLM from idle timeout to readiness timeout; compact Provider Limits cutoff UI with i18n fallback labels; fix DeepSeek PoW dynamic import warning; static locale for docs prerender. ([#2317](https://github.com/diegosouzapw/OmniRoute/pull/2317) — thanks @dhaern)
- **chore(providers):** refresh provider model metadata, sort dashboard entries by display name, fix docs generator relative links and frontmatter. ([#2318](https://github.com/diegosouzapw/OmniRoute/pull/2318) — thanks @backryun)
- **chore(providers):** consolidate Alibaba provider entries — merge `alicode`/`alicode-intl` into shared `ALIBABA_DASHSCOPE_MODELS` array, update 42 i18n llm.txt files. ([#2319](https://github.com/diegosouzapw/OmniRoute/pull/2319) — thanks @backryun)
- **Docs:** 270 broken internal markdown links repaired.
---
## [3.8.0] - 2026-05-15
### Added
- `feat(mcp): MCP accessibility-tree smart filter engine` — collapses ≥30 repeated sibling lines, preserves `[ref=eXX]` anchors, 60-80% savings on browser snapshot outputs (Task 1)
- `docs(skills): publish 10 SKILL.md manifests for external AI agents` — zero-friction onboarding for Claude Desktop, ChatGPT, Cursor, Cline (Task 2)
- `feat(cli): standalone system tray with PowerShell fallback on Windows` — no Electron required; `omniroute --tray`; autostart via LaunchAgent/.desktop/registry (Task 3)
- `feat(auth): CLI machine-ID HMAC-SHA256 token` — zero-friction local auth without JWT/password; loopback-only; constant-time compare (Task 4)
- `feat(security): route protection tiers` — 5 tiers: public/read-only/protected/always/local-only; spawn-capable routes enforce loopback even with valid JWT (Task 5)
- `feat(compression): Caveman SHARED_BOUNDARIES` — all 6 languages × 3 intensities embed boundary clause; `alreadyApplied` check order fixed (Task 6)
- `feat(runtime): dynamic SQLite 5-step fallback chain` — bundled → runtime-installed → lazy-install → node:sqlite → sql.js; magic-byte validation (ELF/Mach-O/PE) (Task 7)
- `docs/ux: tier 1/2/3 marketing, onboarding tour, dashboard widget` — README tier diagram, `docs/marketing/TIERS.md`, TierTour onboarding step, Tier Coverage widget (Task 8)
- `docs(comparison): OMNIROUTE_VS_ALTERNATIVES.md` — objective comparison vs LiteLLM, OpenRouter, Portkey
### Changed
- `getDbInstance()` requires prior `ensureDbInitialized()` call — server startup awaits it automatically (see release notes for migration)
- Caveman prompts embed `SHARED_BOUNDARIES` verbatim (LITE/FULL/ULTRA × 6 languages)
- README "Why OmniRoute?" enhanced with 3-tier ASCII diagram and comparison table
- Onboarding wizard gains "How It Works" tier tour step (after Welcome, before Security)
- Home dashboard shows "Tier coverage" widget (configured + active counts per tier)
### Security
- Hard Rule #15: spawn-capable routes must call `assertRouteAllowed(req)` (CLAUDE.md)
- CLI token rejected on non-loopback hosts even when the HMAC is correct
- `always`-protected routes (shutdown, db export) reject CLI tokens unconditionally
### Documentation
- `docs/security/CLI_TOKEN.md`
- `docs/security/ROUTE_GUARD_TIERS.md`
- `docs/ops/SQLITE_RUNTIME.md`
- `docs/marketing/TIERS.md`
- `docs/comparison/OMNIROUTE_VS_ALTERNATIVES.md`
- `docs/releases/v3.8.0.md`
---
### Dependencies
- **chore(deps):** node dependency updates — bump multiple runtime and dev dependencies to latest patch/minor versions. ([#2259](https://github.com/diegosouzapw/OmniRoute/pull/2259) — thanks @backryun)
## [3.8.0] — 2026-05-06
@@ -28,33 +133,33 @@
- **feat(providers):** update Gemini CLI provider models catalog (#2196 — thanks @nickwizard)
- **feat(antigravity):** integrate Antigravity provider with dynamic `maxOutputTokens` calculation, identity fingerprinting overhaul, and Cloud Code envelope payload sanitization (#2055, #2063)
- **feat(gemini-cli):** add custom projectId support for Gemini CLI transport (UI, DB, executor) (#1991)
- **feat(providers):** add KIE media provider support with dynamic polling, text models, and expanded video models catalog
- **feat(providers):** add Z.AI provider support with GLM quota handling and new quota labels
- **feat(providers):** add 9 new free AI providers — LLM7, Lepton, Kluster, UncloseAI, BazaarLink, Completions, Enally, FreeTheAi (#2096)
- **feat(providers):** batch delete provider connections via checkbox multi-select (#2094)
- **feat(cursor):** full OpenAI parity — tool calls, streaming, and session management (#2082)
- **feat(providers):** add KIE media provider support with dynamic polling, text models, and expanded video models catalog (#2009 — thanks @wauputr4)
- **feat(providers):** add Z.AI provider support with GLM quota handling and new quota labels — thanks @JxnLexn
- **feat(providers):** add 9 new free AI providers — LLM7, Lepton, Kluster, UncloseAI, BazaarLink, Completions, Enally, FreeTheAi (#2096 — thanks @oyi77)
- **feat(providers):** batch delete provider connections via checkbox multi-select (#2094 — thanks @oyi77)
- **feat(cursor):** full OpenAI parity — tool calls, streaming, and session management (#2082 — thanks @payne0420)
- **feat(cursor):** surface Cursor Pro plan usage on provider-limits dashboard (#2128 — thanks @payne0420)
- **feat(cli):** comprehensive CLI enhancement suite with 20+ new commands including `omniroute providers`, `omniroute combos`, `omniroute doctor` (#2074)
- **feat(cli):** add modular CLI setup and provider management commands (#2046)
- **feat(mcp):** add DeepSeek quota and limit monitoring feature (#2089)
- **feat(circuit-breaker):** classify 429 errors and apply per-kind cooldowns (#2116)
- **feat(multi):** manifest-aware tier routing — W1-W4 complete (#2014)
- **feat(combos):** add reset-aware routing strategy for quota-based providers
- **feat(combo):** add context_length input field to combo edit form (#2047)
- **feat(combo):** add `fallbackDelayMs` to combo configuration and related settings
- **feat(chat):** dynamic tool limit detection with proactive truncation (#2061)
- **feat(chat):** add `STREAM_READINESS_TIMEOUT_MS` and integrate into chat handling
- **feat(chat):** enhance error handling for semaphore capacity with fallback logic
- **feat(sse):** refresh Claude OAuth wire image to claude-cli/2.1.131 (#2011)
- **feat(github):** add `targetFormat: openai-responses` to all GitHub models (#2122)
- **feat(api):** allow configuration via API calls — open management routes to Bearer keys with manage scope (#2103)
- **feat(api):** update API bridge proxy timeout to 600,000ms (#2019)
- **feat(cli):** comprehensive CLI enhancement suite with 20+ new commands including `omniroute providers`, `omniroute combos`, `omniroute doctor` (#2074 — thanks @oyi77)
- **feat(cli):** add modular CLI setup and provider management commands (#2046 — thanks @wauputr4)
- **feat(mcp):** add DeepSeek quota and limit monitoring feature (#2089 — thanks @HoaPham98)
- **feat(circuit-breaker):** classify 429 errors and apply per-kind cooldowns (#2116 — thanks @eleata)
- **feat(multi):** manifest-aware tier routing — W1-W4 complete (#2014 — thanks @oyi77)
- **feat(combos):** add reset-aware routing strategy for quota-based providers — thanks @JxnLexn
- **feat(combo):** add context_length input field to combo edit form (#2047 — thanks @ddarkr)
- **feat(combo):** add `fallbackDelayMs` to combo configuration and related settings — thanks @JxnLexn
- **feat(chat):** dynamic tool limit detection with proactive truncation (#2061 — thanks @oyi77)
- **feat(chat):** add `STREAM_READINESS_TIMEOUT_MS` and integrate into chat handling — thanks @JxnLexn
- **feat(chat):** enhance error handling for semaphore capacity with fallback logic — thanks @JxnLexn
- **feat(sse):** refresh Claude OAuth wire image to claude-cli/2.1.131 (#2011 — thanks @Tentoxa)
- **feat(github):** add `targetFormat: openai-responses` to all GitHub models (#2122 — thanks @abhinavjnu)
- **feat(api):** allow configuration via API calls — open management routes to Bearer keys with manage scope (#2103 — thanks @gleber)
- **feat(api):** update API bridge proxy timeout to 600,000ms (#2019 — thanks @JxnLexn)
- **feat(api):** aggregate combo model metadata in catalog endpoint — `buildComboCatalogMetadata()` inlines contextLength, strategy, and target count for combo entries (#2166 — thanks @faisalill)
- **feat(usage):** add service tier breakdown, codex fast service tier analytics, and account for fast tier
- **feat(qdrant):** embedding model discovery (#2086)
- **feat(usage):** add service tier breakdown, codex fast service tier analytics, and account for fast tier — thanks @JxnLexn
- **feat(qdrant):** embedding model discovery (#2086 — thanks @rafacpti23)
- **feat(auth):** per-session sticky routing for Codex (#1887)
- **feat(oauth):** complete Windsurf and Devin CLI OAuth + API-token flows — WindsurfExecutor (gRPC-web/protobuf), DevinCliExecutor (ACP JSON-RPC 2.0 over stdio), model alias map, OAuth provider config (#2168 — thanks @Zhaba1337228)
- **feat(inworld):** enhance Inworld TTS support (#2123)
- **feat(inworld):** enhance Inworld TTS support (#2123 — thanks @backryun)
- **feat(kiro):** headless auth via kiro-cli SQLite, image support, tool overflow handling, and model list sync (#2129 — thanks @christlau)
- **feat(auto):** zero-config auto-routing with `auto/` prefix — dynamic virtual combo from connected providers with 6 variant profiles (coding, fast, cheap, offline, smart, lkgp), analytics tab, and settings UI (#2131 — thanks @oyi77)
- **feat(resilience):** add model cooldowns dashboard card with real-time list, individual/bulk re-enable, and auto-refresh (#2146 — thanks @rafacpti23)
@@ -74,45 +179,45 @@
- **fix(gemini):** prevent `functionDeclarations` from being dropped by the sanitizer when `googleSearch` tool is present (#2077)
- **fix(pollinations):** add `jsonMode: true` flag in the request transformation to enforce correct JSON structure from Pollinations API (#2109)
- **fix(docker):** update Dockerfile to copy `/docs` directory during build ensuring API catalog availability at runtime (#2083)
- **fix(docker):** include OpenAPI spec in runtime image (#2007)
- **fix(docker):** include OpenAPI spec in runtime image (#2007 — thanks @tatsster)
- **fix(providers):** strip OpenAI-specific fields in Kiro translator to prevent 400 errors (#2037)
- **fix(kiro):** normalize tool-use payloads to prevent 400 errors from agents (#2104)
- **fix(kiro):** merge adjacent user history turns after role normalization (#2105)
- **fix(kiro):** normalize tool-use payloads to prevent 400 errors from agents (#2104 — thanks @rilham97)
- **fix(kiro):** merge adjacent user history turns after role normalization (#2105 — thanks @Gioxaa)
- **fix(ui):** resolve text contrast issues for zero-config warning banner in light mode (#2050)
- **fix(core):** inject global system prompt correctly into downstream chat completions pipeline (#2080)
- **fix(core):** restore Claude Code adaptive thinking defaults and resolve audio transcription CORS regression
- **fix(routing):** add missing v1beta rewrites to next.config to resolve 404 on Gemini models endpoint (#2102)
- **fix(routing):** fix bare GPT-5.5 routing for Codex-only installations (#2054)
- **fix(routing):** add fuzzy auto-combo routing for `auto/*` model prefix (#2010)
- **fix(routing):** fix bare GPT-5.5 routing for Codex-only installations (#2054 — thanks @guanbear)
- **fix(routing):** add fuzzy auto-combo routing for `auto/*` model prefix (#2010 — thanks @oyi77)
- **fix(cache):** optimize cache_control preservation logic and explicitly align tool schema with upstream Claude Code expectations
- **fix(db):** preserve legacy SQLite database path on Windows to prevent data loss (#1973)
- **fix(db):** reduce hot-path persistence overhead (#2039)
- **fix(db):** resolve migration conflict by renumbering overlapping migration entries (#2041)
- **fix(db):** reduce hot-path persistence overhead (#2039 — thanks @dhaern)
- **fix(db):** resolve migration conflict by renumbering overlapping migration entries (#2041 — thanks @oyi77)
- **fix(settings):** resolve model alias persistence double stringification preventing UI updates (#2018)
- **fix(routing):** dynamically filter bare model auto-resolution by active provider connections to prevent dead-routing (#2029)
- **fix(embeddings):** add Google Gemini embeddings compatibility via OpenAI-compatible endpoint mapping (#2006)
- **fix(sse):** prevent Claude OAuth multi-account correlation via metadata.user_id (#2053)
- **fix(sse):** prevent Claude Code identity cloak overrides and fix fallback resilience (#2053)
- **fix(sse):** classify hour quota errors as QUOTA_EXHAUSTED (#2119)
- **fix(sse):** fix CC-compatible streaming bridge (#2118)
- **fix(antigravity):** sanitize Claude Cloud Code payloads (#2090)
- **fix(antigravity):** add duplex half for streaming bodies
- **fix(antigravity):** align identity protocol and behavior with official AM
- **fix(chatgpt-web):** plumb proxy through to native tls-client (#2022, #2023)
- **fix(codex):** expose native model IDs in catalog (#2012)
- **fix(glm):** add dedicated coding transport (#2087)
- **fix(compression):** support Responses input and expand Spanish compression rules (#2028)
- **fix(catalog):** auto-calculate combo context_length from target model limits (#2030)
- **fix(api):** fix usage analytics and API key identity (#2008, #2092)
- **fix(api-key):** allow Unicode letters in API key name validation (#1996)
- **fix(auth):** allow bootstrap without password (#2048)
- **fix(proxy):** clean up proxy page redundancy and fix 1proxy sync empty body error (#2052)
- **fix(dashboard):** resolve Unknown plan display in Provider Limits
- **fix(sse):** prevent Claude OAuth multi-account correlation via metadata.user_id (#2053 — thanks @Tentoxa)
- **fix(sse):** prevent Claude Code identity cloak overrides and fix fallback resilience (#2053 — thanks @Tentoxa)
- **fix(sse):** classify hour quota errors as QUOTA_EXHAUSTED (#2119 — thanks @clousky2020)
- **fix(sse):** fix CC-compatible streaming bridge (#2118 — thanks @rdself)
- **fix(antigravity):** sanitize Claude Cloud Code payloads (#2090 — thanks @dhaern)
- **fix(antigravity):** add duplex half for streaming bodies — thanks @Gi99lin
- **fix(antigravity):** align identity protocol and behavior with official AM — thanks @Gi99lin
- **fix(chatgpt-web):** plumb proxy through to native tls-client (#2022, #2023 — thanks @xssdem)
- **fix(codex):** expose native model IDs in catalog (#2012 — thanks @Tr0sT)
- **fix(glm):** add dedicated coding transport (#2087 — thanks @dhaern)
- **fix(compression):** support Responses input and expand Spanish compression rules (#2028 — thanks @dhaern)
- **fix(catalog):** auto-calculate combo context_length from target model limits (#2030 — thanks @herjarsa)
- **fix(api):** fix usage analytics and API key identity (#2008, #2092 — thanks @AveryanAlex, @yoviarpauzi)
- **fix(api-key):** allow Unicode letters in API key name validation (#1996 — thanks @rodrigogbbr-stack)
- **fix(auth):** allow bootstrap without password (#2048 — thanks @tces1)
- **fix(proxy):** clean up proxy page redundancy and fix 1proxy sync empty body error (#2052 — thanks @oyi77)
- **fix(dashboard):** resolve Unknown plan display in Provider Limits — thanks @congvc-dev
- **fix(usage):** add extensible CURRENCY_SYMBOLS mapping for deepseek currencies
- **fix(runtime):** harden timer handling and model pricing fallback
- **fix(i18n):** complete Simplified Chinese translations (#2115)
- **fix(mitm):** add Linux cert install and skip sudo password when root (#1999)
- **fix(mitm):** prevent stub from loading at runtime via bypass module
- **fix(i18n):** complete Simplified Chinese translations (#2115 — thanks @boa-z)
- **fix(mitm):** add Linux cert install and skip sudo password when root (#1999 — thanks @NekoMonci12)
- **fix(mitm):** prevent stub from loading at runtime via bypass module — thanks @NekoMonci12
- **fix:** remove Anthropic-Beta header from non-Anthropic providers to fix identity contamination (#1989)
- **fix(cli):** resolve .env loading failure for global npm installations
- **fix(authz):** classify `/dashboard/onboarding` as PUBLIC to unblock setup wizard (#2127)
@@ -201,59 +306,62 @@
Thank you to all **55+ community contributors** who made v3.8.0 possible! 🎉
| Contributor | PRs | Contributions |
| :--------------------------------------------------------- | :-: | :--------------------------------------------------------------------------------- |
| [@NomenAK](https://github.com/NomenAK) | 12 | #2217, #2218, #2219, #2221, #2222, #2223, #2224, #2228, #2233, #2234, #2242, #2192 |
| [@oyi77](https://github.com/oyi77) | 12 | #2010, #2014, #2041, #2052, #2061, #2074, #2091, #2094, #2096, #2131, #2135, #2240 |
| [@backryun](https://github.com/backryun) | 8 | #1992, #2033, #2088, #2123, #2138, #2141, #2150, #2177 |
| [@Brkic-Nikola](https://github.com/Brkic-Nikola) | 6 | #2165, #2189, #2190, #2191, #2192, #2197 |
| [@Gioxaa](https://github.com/Gioxaa) | 5 | #2105, #2149, #2153, #2154, #2159 |
| [@dhaern](https://github.com/dhaern) | 4 | #2028, #2039, #2087, #2090 |
| [@andrewmunsell](https://github.com/andrewmunsell) | 3 | #2169, #2176, #2238 |
| [@ddarkr](https://github.com/ddarkr) | 3 | #2047, #2199, #2243 |
| [@nickwizard](https://github.com/nickwizard) | 3 | #1991, #2196, #2227 |
| [@herjarsa](https://github.com/herjarsa) | 3 | #2030, #2136, #2152 |
| [@rafacpti23](https://github.com/rafacpti23) | 3 | #2086, #2146, #2201 |
| [@Tentoxa](https://github.com/Tentoxa) | 2 | #2011, #2053 |
| [@wauputr4](https://github.com/wauputr4) | 2 | #2009, #2046 |
| [@hartmark](https://github.com/hartmark) | 2 | #2045, #2137 |
| [@payne0420](https://github.com/payne0420) | 2 | #2082, #2128 |
| [@bypanghu](https://github.com/bypanghu) | 2 | #2027, #2156 |
| [@eleata](https://github.com/eleata) | 2 | #2116, #2133 |
| [@Tr0sT](https://github.com/Tr0sT) | 1 | #2012 |
| [@AveryanAlex](https://github.com/AveryanAlex) | 1 | #2008 |
| [@rodrigogbbr-stack](https://github.com/rodrigogbbr-stack) | 1 | #1996 |
| [@NekoMonci12](https://github.com/NekoMonci12) | 1 | #1999 |
| [@congvc-dev](https://github.com/congvc-dev) | 1 | #2004 |
| [@tatsster](https://github.com/tatsster) | 1 | #2007 |
| [@xssdem](https://github.com/xssdem) | 1 | #2023 |
| [@wucm667](https://github.com/wucm667) | 1 | #2031 |
| [@tces1](https://github.com/tces1) | 1 | #2048 |
| [@guanbear](https://github.com/guanbear) | 1 | #2054 |
| [@Gi99lin](https://github.com/Gi99lin) | 1 | #2055 |
| [@ivan-mezentsev](https://github.com/ivan-mezentsev) | 1 | #2063 |
| [@JxnLexn](https://github.com/JxnLexn) | 1 | #2019 |
| [@yoviarpauzi](https://github.com/yoviarpauzi) | 1 | #2092 |
| [@gleber](https://github.com/gleber) | 1 | #2103 |
| [@rilham97](https://github.com/rilham97) | 1 | #2104 |
| [@boa-z](https://github.com/boa-z) | 1 | #2115 |
| [@rdself](https://github.com/rdself) | 1 | #2118 |
| [@clousky2020](https://github.com/clousky2020) | 1 | #2119 |
| [@abhinavjnu](https://github.com/abhinavjnu) | 1 | #2122 |
| [@HoaPham98](https://github.com/HoaPham98) | 1 | #2089 |
| [@christlau](https://github.com/christlau) | 1 | #2129 |
| [@flyingmongoose](https://github.com/flyingmongoose) | 1 | #2134 |
| [@05dunski](https://github.com/05dunski) | 1 | #1978 (cherry-picked) |
| [@DavyMassoneto](https://github.com/DavyMassoneto) | 1 | #2140 |
| [@Zhaba1337228](https://github.com/Zhaba1337228) | 1 | #2168 |
| [@faisalill](https://github.com/faisalill) | 1 | #2166 |
| [@Yosee11](https://github.com/Yosee11) | 1 | #2164 |
| [@hachimed](https://github.com/hachimed) | 1 | #2162 |
| [@JohnDoe-oss](https://github.com/JohnDoe-oss) | 1 | #2161 |
| [@brucevoin](https://github.com/brucevoin) | 1 | #2163 |
| [@InkshadeWoods](https://github.com/InkshadeWoods) | 1 | #2202 |
| [@kang-heewon](https://github.com/kang-heewon) | 1 | #2231 |
| [@one-vs](https://github.com/one-vs) | 1 | #2236 |
| Contributor | PRs | Contributions |
| :--------------------------------------------------------- | :-: | :----------------------------------------------------------------------------------------------- |
| [@NomenAK](https://github.com/NomenAK) | 12 | #2217, #2218, #2219, #2221, #2222, #2223, #2224, #2228, #2233, #2234, #2242, #2192 |
| [@oyi77](https://github.com/oyi77) | 14 | #2010, #2014, #2041, #2052, #2061, #2074, #2091, #2094, #2096, #2131, #2135, #2240, #2283, #2295 |
| [@backryun](https://github.com/backryun) | 9 | #1992, #2033, #2088, #2123, #2138, #2141, #2150, #2177, #2279 |
| [@Brkic-Nikola](https://github.com/Brkic-Nikola) | 6 | #2165, #2189, #2190, #2191, #2192, #2197 |
| [@Gioxaa](https://github.com/Gioxaa) | 5 | #2105, #2149, #2153, #2154, #2159 |
| [@dhaern](https://github.com/dhaern) | 4 | #2028, #2039, #2087, #2090 |
| [@andrewmunsell](https://github.com/andrewmunsell) | 3 | #2169, #2176, #2238 |
| [@ddarkr](https://github.com/ddarkr) | 4 | #2047, #2199, #2243, #2271 |
| [@nickwizard](https://github.com/nickwizard) | 3 | #1991, #2196, #2227 |
| [@herjarsa](https://github.com/herjarsa) | 3 | #2030, #2136, #2152 |
| [@rafacpti23](https://github.com/rafacpti23) | 3 | #2086, #2146, #2201 |
| [@Tentoxa](https://github.com/Tentoxa) | 2 | #2011, #2053 |
| [@wauputr4](https://github.com/wauputr4) | 2 | #2009, #2046 |
| [@hartmark](https://github.com/hartmark) | 4 | #2045, #2137, #2294, #2299 |
| [@payne0420](https://github.com/payne0420) | 2 | #2082, #2128 |
| [@bypanghu](https://github.com/bypanghu) | 2 | #2027, #2156 |
| [@eleata](https://github.com/eleata) | 2 | #2116, #2133 |
| [@Tr0sT](https://github.com/Tr0sT) | 1 | #2012 |
| [@AveryanAlex](https://github.com/AveryanAlex) | 1 | #2008 |
| [@rodrigogbbr-stack](https://github.com/rodrigogbbr-stack) | 1 | #1996 |
| [@NekoMonci12](https://github.com/NekoMonci12) | 1 | #1999 |
| [@congvc-dev](https://github.com/congvc-dev) | 1 | #2004 |
| [@tatsster](https://github.com/tatsster) | 1 | #2007 |
| [@xssdem](https://github.com/xssdem) | 1 | #2023 |
| [@wucm667](https://github.com/wucm667) | 1 | #2031 |
| [@tces1](https://github.com/tces1) | 1 | #2048 |
| [@guanbear](https://github.com/guanbear) | 1 | #2054 |
| [@Gi99lin](https://github.com/Gi99lin) | 1 | #2055 |
| [@ivan-mezentsev](https://github.com/ivan-mezentsev) | 1 | #2063 |
| [@JxnLexn](https://github.com/JxnLexn) | 1 | #2019 |
| [@yoviarpauzi](https://github.com/yoviarpauzi) | 1 | #2092 |
| [@gleber](https://github.com/gleber) | 1 | #2103 |
| [@rilham97](https://github.com/rilham97) | 1 | #2104 |
| [@boa-z](https://github.com/boa-z) | 1 | #2115 |
| [@rdself](https://github.com/rdself) | 1 | #2118 |
| [@clousky2020](https://github.com/clousky2020) | 1 | #2119 |
| [@abhinavjnu](https://github.com/abhinavjnu) | 1 | #2122 |
| [@HoaPham98](https://github.com/HoaPham98) | 1 | #2089 |
| [@christlau](https://github.com/christlau) | 1 | #2129 |
| [@flyingmongoose](https://github.com/flyingmongoose) | 1 | #2134 |
| [@05dunski](https://github.com/05dunski) | 1 | #1978 (cherry-picked) |
| [@DavyMassoneto](https://github.com/DavyMassoneto) | 1 | #2140 |
| [@Zhaba1337228](https://github.com/Zhaba1337228) | 1 | #2168 |
| [@faisalill](https://github.com/faisalill) | 1 | #2166 |
| [@Yosee11](https://github.com/Yosee11) | 1 | #2164 |
| [@hachimed](https://github.com/hachimed) | 1 | #2162 |
| [@JohnDoe-oss](https://github.com/JohnDoe-oss) | 1 | #2161 |
| [@brucevoin](https://github.com/brucevoin) | 1 | #2163 |
| [@InkshadeWoods](https://github.com/InkshadeWoods) | 1 | #2202 |
| [@kang-heewon](https://github.com/kang-heewon) | 1 | #2231 |
| [@one-vs](https://github.com/one-vs) | 1 | #2236 |
| [@thepigdestroyer](https://github.com/thepigdestroyer) | 2 | #2290, #2291 |
| [@josephvoxone](https://github.com/josephvoxone) | 1 | #2289 |
| [@mrmm](https://github.com/mrmm) | 3 | #2286, #2305, #2308 |
## [3.7.9] — 2026-05-03
@@ -1729,7 +1837,7 @@ We identified that **155 community PRs** across the entire project history (from
- **feat(ui):** Implement on-demand per-model testing in the provider dashboard, allowing single-token diagnostic checks without triggering rate-limits (Issue #1532).
- **Detailed Token Tracking:** Added granular token breakdown columns (cache read, cache write, reasoning) to call logs with proper null vs zero distinction. Includes DB migration 018 and 5-label UI display per provider capability (#1017 — thanks @rdself).
- **Legacy JSON Config Import/Export:** Restored JSON-based settings export and import for migration from legacy 9router configurations. Security-hardened with Zero-Trust redaction of passwords and `requireLogin` fields, and automatic pre-import database backups (#1012 — thanks @luandiasrj).
- **Legacy JSON Config Import/Export:** Restored JSON-based settings export and import for migration from legacy configurations. Security-hardened with Zero-Trust redaction of passwords and `requireLogin` fields, and automatic pre-import database backups (#1012 — thanks @luandiasrj).
- **Non-Stream Aliases:** Added API support for explicit non-streaming aliases (`non_stream`, `disable_stream`, `disable_streaming`, `streaming=false`), normalized at the boundary before provider translation (#1036 — thanks @wlfonseca).
- **Russian Dashboard Localization:** Comprehensive Russian translation for the dashboard UI, including fixes for 2 Ukrainian locale keys (#1003 — thanks @mercs2910).

View File

@@ -413,3 +413,5 @@ git push -u origin feat/your-feature
12. Never return raw `err.stack` / `err.message` in HTTP / SSE / executor responses — always route through `buildErrorBody()` or `sanitizeErrorMessage()` (`open-sse/utils/error.ts`). See `docs/security/ERROR_SANITIZATION.md`.
13. Never string-interpolate external paths or runtime values into shell scripts passed to `exec()`/`spawn()` — pass via the `env` option instead. Reference: `src/mitm/cert/install.ts::updateNssDatabases`.
14. Never dismiss a CodeQL / Secret-Scanning alert without (a) first checking the pattern docs above to see if the helper applies, and (b) recording the technical justification in the dismissal comment. Precedent: `js/stack-trace-exposure` raised on callsites that already route through `sanitizeErrorMessage()` is a known CodeQL limitation (custom sanitizers not recognized) — dismiss as `false positive` referencing `docs/security/ERROR_SANITIZATION.md`.
15. Never expose routes that spawn child processes (`/api/mcp/`, `/api/cli-tools/runtime/`) without `isLocalOnlyPath()` classification in `src/server/authz/routeGuard.ts`. Loopback enforcement happens unconditionally before any auth check — leaked JWT via tunnel cannot trigger process spawning. See `docs/security/ROUTE_GUARD_TIERS.md`.
16. Never include `Co-Authored-By` trailers in commit messages. Commits must appear solely under the repository owner's Git identity (`diegosouzapw`). The `Co-Authored-By: Claude …` line causes GitHub to attribute commits to the `claude` Anthropic account, hiding the real author in the PR history.

View File

@@ -133,7 +133,7 @@ npm run test:protocols:e2e
# Ecosystem compatibility tests
npm run test:ecosystem
# Coverage (60% min statements/lines/functions/branches)
# Coverage gate: 75% statements/lines/functions, 70% branches
npm run test:coverage
npm run coverage:report
@@ -145,7 +145,7 @@ npm run check
Coverage notes:
- `npm run test:coverage` measures source coverage for the main unit test suite, excludes `tests/**`, and includes `open-sse/**`
- Pull requests must keep the overall coverage gate at **60% or higher** for statements, lines, functions, and branches
- Pull requests must keep the coverage gate at **75%+** statements/lines/functions and **70%+** branches
- If a PR changes production code in `src/`, `open-sse/`, `electron/`, or `bin/`, it must add or update automated tests in the same PR
- `npm run coverage:report` prints the detailed file-by-file report from the latest coverage run
- `npm run test:coverage:legacy` preserves the older metric for historical comparison
@@ -157,7 +157,7 @@ Before opening or merging a PR:
- Run `npm run test:unit`
- Run `npm run test:coverage`
- Ensure the coverage gate stays at **60%+** for all metrics
- Ensure the coverage gate stays at **75%+** statements/lines/functions, **70%+** branches
- Include the changed or added test files in the PR description when production code changed
- Check the SonarQube result on the PR when the project secrets are configured in CI
@@ -298,6 +298,8 @@ Write unit tests in `tests/unit/` covering at minimum:
- [ ] CHANGELOG updated (if user-facing change)
- [ ] Documentation updated (if applicable)
- [ ] No new CodeQL / Secret-Scanning alerts opened, or each one dismissed with technical justification referencing the relevant `docs/security/` doc
- [ ] Routes that spawn child processes (`/api/mcp/`, `/api/cli-tools/runtime/`) classified as `isLocalOnlyPath()` in `src/server/authz/routeGuard.ts` — see [Hard Rule #15](docs/security/ROUTE_GUARD_TIERS.md)
- [ ] No `Co-Authored-By` trailers in commit messages — commits must appear solely under the repository owner's Git identity (Hard Rule #16)
---
@@ -311,5 +313,7 @@ Releases are managed via the `/generate-release` workflow. When a new GitHub Rel
- **Architecture**: See [`docs/architecture/ARCHITECTURE.md`](docs/architecture/ARCHITECTURE.md)
- **API Reference**: See [`docs/reference/API_REFERENCE.md`](docs/reference/API_REFERENCE.md)
- **Security docs**: [`docs/security/CLI_TOKEN.md`](docs/security/CLI_TOKEN.md), [`docs/security/ROUTE_GUARD_TIERS.md`](docs/security/ROUTE_GUARD_TIERS.md), [`docs/security/ERROR_SANITIZATION.md`](docs/security/ERROR_SANITIZATION.md), [`docs/security/PUBLIC_CREDS.md`](docs/security/PUBLIC_CREDS.md)
- **Ops docs**: [`docs/ops/SQLITE_RUNTIME.md`](docs/ops/SQLITE_RUNTIME.md)
- **Issues**: [github.com/diegosouzapw/OmniRoute/issues](https://github.com/diegosouzapw/OmniRoute/issues)
- **ADRs**: See `docs/adr/` for architectural decision records

151
README.md
View File

@@ -32,7 +32,7 @@ _The most complete open-source AI proxy — **one endpoint**, **160+ providers**
<div align="">
🌐 **Available in:** 🇺🇸 [English](README.md) | 🇧🇷 [Português (Brasil)](docs/i18n/pt-BR/README.md) | 🇪🇸 [Español](docs/i18n/es/README.md) | 🇫🇷 [Français](docs/i18n/fr/README.md) | 🇮🇹 [Italiano](docs/i18n/it/README.md) | 🇷🇺 [Русский](docs/i18n/ru/README.md) | 🇨🇳 [中文 (简体)](docs/i18n/zh-CN/README.md) | 🇩🇪 [Deutsch](docs/i18n/de/README.md) | 🇮🇳 [हिन्दी](docs/i18n/in/README.md) | 🇹🇭 [ไทย](docs/i18n/th/README.md) | 🇺🇦 [Українська](docs/i18n/uk-UA/README.md) | 🇸🇦 [العربية](docs/i18n/ar/README.md) | 🇯🇵 [日本語](docs/i18n/ja/README.md) | 🇻🇳 [Tiếng Việt](docs/i18n/vi/README.md) | 🇧🇬 [Български](docs/i18n/bg/README.md) | 🇩🇰 [Dansk](docs/i18n/da/README.md) | 🇫🇮 [Suomi](docs/i18n/fi/README.md) | 🇮🇱 [עברית](docs/i18n/he/README.md) | 🇭🇺 [Magyar](docs/i18n/hu/README.md) | 🇮🇩 [Bahasa Indonesia](docs/i18n/id/README.md) | 🇰🇷 [한국어](docs/i18n/ko/README.md) | 🇲🇾 [Bahasa Melayu](docs/i18n/ms/README.md) | 🇳🇱 [Nederlands](docs/i18n/nl/README.md) | 🇳🇴 [Norsk](docs/i18n/no/README.md) | 🇵🇹 [Português (Portugal)](docs/i18n/pt/README.md) | 🇷🇴 [Română](docs/i18n/ro/README.md) | 🇵🇱 [Polski](docs/i18n/pl/README.md) | 🇸🇰 [Slovenčina](docs/i18n/sk/README.md) | 🇸🇪 [Svenska](docs/i18n/sv/README.md) | 🇵🇭 [Filipino](docs/i18n/phi/README.md) | 🇨🇿 [Čeština](docs/i18n/cs/README.md)
🌐 **Available in:** 🇺🇸 [English](README.md) | 🇧🇷 [Português (Brasil)](docs/i18n/pt-BR/README.md) | 🇪🇸 [Español](docs/i18n/es/README.md) | 🇫🇷 [Français](docs/i18n/fr/README.md) | 🇮🇹 [Italiano](docs/i18n/it/README.md) | 🇷🇺 [Русский](docs/i18n/ru/README.md) | 🇨🇳 [中文 (简体)](docs/i18n/zh-CN/README.md) | 🇩🇪 [Deutsch](docs/i18n/de/README.md) | 🇮🇳 [हिन्दी](docs/i18n/in/README.md) | 🇹🇭 [ไทย](docs/i18n/th/README.md) | 🇺🇦 [Українська](docs/i18n/uk-UA/README.md) | 🇸🇦 [العربية](docs/i18n/ar/README.md) | 🇦🇿 [Azərbaycan dili](docs/i18n/az/README.md) | 🇯🇵 [日本語](docs/i18n/ja/README.md) | 🇻🇳 [Tiếng Việt](docs/i18n/vi/README.md) | 🇧🇬 [Български](docs/i18n/bg/README.md) | 🇩🇰 [Dansk](docs/i18n/da/README.md) | 🇫🇮 [Suomi](docs/i18n/fi/README.md) | 🇮🇱 [עברית](docs/i18n/he/README.md) | 🇭🇺 [Magyar](docs/i18n/hu/README.md) | 🇮🇩 [Bahasa Indonesia](docs/i18n/id/README.md) | 🇰🇷 [한국어](docs/i18n/ko/README.md) | 🇲🇾 [Bahasa Melayu](docs/i18n/ms/README.md) | 🇳🇱 [Nederlands](docs/i18n/nl/README.md) | 🇳🇴 [Norsk](docs/i18n/no/README.md) | 🇵🇹 [Português (Portugal)](docs/i18n/pt/README.md) | 🇷🇴 [Română](docs/i18n/ro/README.md) | 🇵🇱 [Polski](docs/i18n/pl/README.md) | 🇸🇰 [Slovenčina](docs/i18n/sk/README.md) | 🇸🇪 [Svenska](docs/i18n/sv/README.md) | 🇵🇭 [Filipino](docs/i18n/phi/README.md) | 🇨🇿 [Čeština](docs/i18n/cs/README.md)
</div>
@@ -211,26 +211,80 @@ _Connect any AI-powered IDE or CLI tool through OmniRoute — free API gateway f
## 🤔 Why OmniRoute?
**Stop wasting money, tokens and hitting limits:**
**One endpoint. 207+ providers. Never stop building.**
❌ Subscription quota expires unused every month
❌ Rate limits stop you mid-coding
❌ Tool outputs (`git diff`, `grep`, `ls`...) burn tokens fast
❌ Expensive APIs ($20-50/month per provider)
❌ Manual switching between providers
❌ Each provider has a different API format
❌ AI providers blocked in your country
Stop juggling 10 dashboards, dead API keys, and surprise bills. OmniRoute
routes every request through the cheapest viable provider — automatically.
**OmniRoute solves all of this:**
### The 3-tier fallback (zero-downtime AI)
```
┌──────────────────────────────────────────────────────────┐
│ Your IDE / CLI / App │
│ (Claude Code, Cursor, Cline, Copilot, …) │
└─────────────────────┬────────────────────────────────────┘
│ http://localhost:20128/v1
┌──────────────────────────────────────────────────────────┐
│ OmniRoute (Smart Router) │
│ • RTK token saver (47 specialized filters) │
│ • Caveman terse-mode (3 levels + SHARED_BOUNDARIES) │
│ • Auto-fallback combos (14 strategies) │
│ • Circuit breaker · TLS fingerprint stealth (JA3/JA4) │
│ • Memory · MCP server · A2A · Guardrails · Evals │
└─────────────────────┬────────────────────────────────────┘
┌──────────────────┼─────────────────┐
▼ Tier 1 ▼ Tier 2 ▼ Tier 3
SUBSCRIPTION CHEAP FREE
(Claude Code, (DeepSeek $0.27, (Kiro, OpenCode,
Codex, Copilot, GLM $0.60, Gemini CLI,
Cursor, Antigravity) MiniMax $0.20) Vertex $300cr)
quota exhausted? budget hit? always available
→ falls to Tier 2 → falls to Tier 3
```
### Why this matters
-**Subscription quota wasted** every month? OmniRoute uses every token before expiry.
-**Rate limits stop you mid-flow?** Auto-fallback to the next provider in milliseconds.
-**Tool outputs burn tokens?** RTK compresses `git diff`, logs, and grep results 30-50%.
-**Paying $50/mo across 5 providers?** Route to the cheapest viable model automatically.
-**Each AI tool wants its own setup?** One endpoint, every tool, one dashboard.
### What sets OmniRoute apart
| Feature | OmniRoute | Other routers |
| ----------------------------------- | ------------------------------------------------------------- | ------------- |
| Providers | **207+** | 20-100 |
| Combo strategies | **14** (priority, weighted, cost-optimized, context-relay, …) | 1-3 |
| Token compression (RTK) | **47 specialized filters** | None |
| Built-in MCP server | **37 tools, 3 transports, 13 scopes** | Rare |
| A2A agent protocol | **5 skills, JSON-RPC 2.0** | None |
| Memory (FTS5 + vector) | **Yes** | Rare |
| Guardrails (PII, injection, vision) | **Yes** | Rare |
| Cloud agent integrations | Codex, Devin, Jules | None |
| Circuit breaker per provider | **3-state, lazy recovery** | Rare |
| TLS fingerprint stealth | **JA3/JA4 via wreq-js** | None |
| Eval framework | **Built-in** | Rare |
| CLI (no Electron required) | **Yes** + system tray | Varies |
| i18n | **40+ locales** | 0-4 |
See [`docs/comparison/OMNIROUTE_VS_ALTERNATIVES.md`](docs/comparison/OMNIROUTE_VS_ALTERNATIVES.md) for a detailed comparison vs LiteLLM, OpenRouter, and Portkey.
---
**Also solves:**
**Prompt Compression** — auto-compress prompts & tool outputs, save 15-95% eligible tokens per request with RTK+Caveman stacked mode
**Maximize subscriptions** — track quota, use every bit before reset
**Auto fallback** — Subscription → API Key → Cheap → Free, zero downtime
**Auto fallback** — Subscription → Cheap → Free, zero downtime
**Multi-account** — round-robin between accounts per provider
**Format translation** — OpenAI ↔ Claude ↔ Gemini ↔ Responses API, any tool works
**3-level proxy** — bypass geo-blocks with global, per-provider, and per-key proxies
**10 multi-modal APIs** — chat, images, video, music, audio, search in one endpoint
**MCP + A2A**29 MCP tools + agent-to-agent protocol, production-ready
**MCP + A2A**37 MCP tools + agent-to-agent protocol, production-ready
**Universal** — works with Claude Code, Codex, Gemini CLI, Cursor, Cline, OpenClaw, any CLI tool
---
@@ -244,7 +298,6 @@ _Connect any AI-powered IDE or CLI tool through OmniRoute — free API gateway f
- **Issues**: [github.com/diegosouzapw/OmniRoute/issues](https://github.com/diegosouzapw/OmniRoute/issues)
- **WhatsApp**: [Community Group](https://chat.whatsapp.com/JI7cDQ1GyaiDHhVBpLxf8b?mode=gi_t)
- **Contributing**: See [CONTRIBUTING.md](CONTRIBUTING.md), open a PR, or pick a `good first issue`
- **Original Project**: [9router by decolua](https://github.com/decolua/9router)
### 🐛 Reporting a Bug?
@@ -291,6 +344,63 @@ OmniRoute works seamlessly with **16+ AI coding tools** — one config, all tool
📖 Full setup for each tool: [`docs/CLI-TOOLS.md`](docs/CLI-TOOLS.md)
### 🧩 OpenCode integration — `@omniroute/opencode-provider`
[![npm version](https://img.shields.io/npm/v/@omniroute/opencode-provider.svg?logo=npm&label=%40omniroute%2Fopencode-provider)](https://www.npmjs.com/package/@omniroute/opencode-provider)
[![npm downloads](https://img.shields.io/npm/dm/@omniroute/opencode-provider.svg?logo=npm)](https://www.npmjs.com/package/@omniroute/opencode-provider)
[![bundle size](https://img.shields.io/bundlephobia/minzip/@omniroute/opencode-provider?label=minzip)](https://bundlephobia.com/package/@omniroute/opencode-provider)
[![license](https://img.shields.io/npm/l/@omniroute/opencode-provider.svg)](./@omniroute/opencode-provider/LICENSE)
Schema-valid generator for [`opencode.json`](https://opencode.ai/config.json). Emits a `provider.omniroute` entry that delegates the runtime to [`@ai-sdk/openai-compatible`](https://www.npmjs.com/package/@ai-sdk/openai-compatible) — every OpenCode request flows through OmniRoute's `/v1` surface and benefits from Auto-Combo routing, circuit breakers, key policies, and observability.
**Two integration paths:**
```bash
# Path 1 — CLI generator (ships with OmniRoute)
omniroute config opencode \
--baseUrl http://localhost:20128 \
--apiKey "$OMNIROUTE_API_KEY"
```
```bash
# Path 2 — npm package (for scripted / programmatic setups)
npm install --save-dev @omniroute/opencode-provider
```
```ts
import { writeFileSync } from "node:fs";
import { buildOmniRouteOpenCodeConfig } from "@omniroute/opencode-provider";
const config = buildOmniRouteOpenCodeConfig({
baseURL: "http://localhost:20128",
apiKey: process.env.OMNIROUTE_API_KEY ?? "sk_omniroute",
});
writeFileSync("opencode.json", JSON.stringify(config, null, 2));
```
Resulting `opencode.json` (excerpt):
```jsonc
{
"$schema": "https://opencode.ai/config.json",
"provider": {
"omniroute": {
"npm": "@ai-sdk/openai-compatible",
"name": "OmniRoute",
"options": { "baseURL": "http://localhost:20128/v1", "apiKey": "sk_omniroute" },
"models": {
"claude-opus-4-5-thinking": { "name": "claude-opus-4-5-thinking" },
"gemini-3.1-pro-high": { "name": "gemini-3.1-pro-high" },
// …
},
},
},
}
```
📦 Package: [`@omniroute/opencode-provider`](https://www.npmjs.com/package/@omniroute/opencode-provider) · 📖 Full guide: [`docs/frameworks/OPENCODE.md`](docs/frameworks/OPENCODE.md) · 🛠 Source: [`@omniroute/opencode-provider/`](./@omniroute/opencode-provider)
---
## 🌐 Supported Providers — 160+
@@ -403,6 +513,19 @@ Alibaba · Amazon Q · AssemblyAI · Baidu Qianfan · Baseten · Black Forest La
---
## 🤖 AI Agent Skills
Drop-in markdown manifests that let any AI agent consume OmniRoute via one fetch.
Tell your agent (Claude Desktop, ChatGPT, Cursor, Cline, etc.):
> "Fetch this URL and use OmniRoute according to its instructions:
> `https://raw.githubusercontent.com/diegosouzapw/OmniRoute/main/skills/omniroute/SKILL.md`"
10 skills available — see [skills/README.md](./skills/README.md).
---
## 🔄 How It Works
```
@@ -1529,8 +1652,6 @@ gh release create v2.0.0 --title "v2.0.0" --generate-notes
## 🙏 Acknowledgments
Special thanks to **[9router](https://github.com/decolua/9router)** by **[decolua](https://github.com/decolua)** — the original project that inspired this fork. OmniRoute builds upon that incredible foundation with additional features, multi-modal APIs, and a full TypeScript rewrite.
Special thanks to **[CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI)** by **[router-for-me](https://github.com/router-for-me)** — the original Go implementation that inspired this JavaScript port.
Special thanks to **[Caveman](https://github.com/JuliusBrussee/caveman)** by **[JuliusBrussee](https://github.com/JuliusBrussee)** (⭐ 51K+) — the viral "why use many token when few token do trick" project whose caveman-speak compression philosophy inspired OmniRoute's standard compression mode and 30+ filler/condensation regex rules.

File diff suppressed because it is too large Load Diff

224
bin/cli/CONVENTIONS.md Normal file
View File

@@ -0,0 +1,224 @@
# OmniRoute CLI — Internal Conventions
> Status: normative. Source: `_tasks/features-v3.8.0/cli/fase-0-preparacao/0.3-definir-convencoes.md`.
> This file is the authoritative reference for every new or migrated CLI command.
> If reality diverges from this document, fix the code first; only edit this file
> after the discrepancy has been justified in a PR.
## 1. Subcommand style
**Standard**: `git`-style nested verbs.
```
omniroute keys add openai sk-xxx
omniroute combo switch fastest
omniroute memory search "react hooks"
```
**Not allowed**:
```
omniroute --add-key openai sk-xxx # ❌ flag-as-verb
omniroute add-key openai sk-xxx # ❌ hyphen at the top level
```
## 2. Flags
- Only `--long` and `-s` shorts (one-letter shorts reserved for very common
flags: `-h`, `-v`, `-o`, `-q`, `--no-open`).
- Format: `--api-key sk-xxx` (space). `=` accepted for parity but doc uses space.
- Naming: kebab-case (`--api-key`, `--non-interactive`, `--max-tokens`).
- Booleans: `--no-foo` (negative) and `--foo` (positive). Default `false` unless
documented.
- Multi-value: repeat the flag (`--header X-A=1 --header X-B=2`).
## 3. Output (`--output`)
| Value | Use case |
| ------- | -------------------------------------------- |
| `table` | default human-readable |
| `json` | single JSON object, pretty-printed |
| `jsonl` | streamed objects, one per line (logs, lists) |
| `csv` | spreadsheet ingestion |
Related flags:
- `--quiet` / `-q` — suppress headers/spinners (pipe-friendly).
- `--no-color` — force ANSI off (auto-detected if `!stdout.isTTY`).
Helper: `emit(rows, opts)` from `bin/cli/output.mjs` handles all four formats.
## 4. Exit codes
| Code | Meaning |
| ----- | --------------------------------- |
| `0` | success |
| `1` | generic error (uncaught, runtime) |
| `2` | invalid argument / misuse |
| `3` | server offline (when required) |
| `4` | auth / permission (401/403) |
| `5` | rate limit / quota (429) |
| `124` | timeout |
Helper: `exitWith(code, message?)` from `bin/cli/exit.mjs` (added under
`output.mjs` if needed) — always uses these constants. **Never** raw
`process.exit(N)` in command code.
## 5. HTTP errors + retry/backoff
All API calls go through `apiFetch(path, opts)` (`bin/cli/api.mjs`), which:
- Reads base URL from `OMNIROUTE_BASE_URL` env or `~/.omniroute/config.json`
(active profile).
- Injects `Authorization: Bearer ${OMNIROUTE_API_KEY}` when available.
- Injects `x-omniroute-cli-token` when applicable (see task 8.12).
- Applies a per-attempt timeout (`--timeout 30000`, default 30s).
- Maps status → exit code (401→4, 429→5, 5xx→1, etc.).
- Never exposes `err.stack` (CLAUDE.md hard rule #12).
- Applies exponential backoff with jitter on retryable statuses.
### Retry defaults
```js
export const RETRY_DEFAULTS = {
maxAttempts: 3, // 1 initial + 2 retries
baseMs: 500,
maxMs: 8000, // jitter can slightly exceed
jitter: true, // ±25%
retryableStatuses: [408, 425, 429, 502, 503, 504],
retryableErrorCodes: [
"ECONNRESET",
"ECONNREFUSED",
"ETIMEDOUT",
"ENOTFOUND",
"EAI_AGAIN",
"EPIPE",
],
};
```
### Global flags wired
- `--retry` (default on) / `--no-retry`
- `--retry-max <n>` (default 3) — total attempts
- `--timeout <ms>` (default 30000) — per attempt
- `--retry-on <csv>` — extra retryable statuses (e.g. `--retry-on 500`)
### Method semantics
- Mutations (`POST`/`PUT`/`DELETE`) retry **only** on idempotent-ish statuses
(`502`/`503`/`504`/`408`/network), never `409`/`422`. This avoids duplicate
side-effects.
- `GET` retries all `RETRY_DEFAULTS.retryableStatuses`.
- SSE / streaming does **not** auto-retry (operator decides).
- Optional `--idempotency-key <uuid>` for extra-safe mutations.
### Status → exit code map
| Status | Exit | Retry? |
| --------------- | ---- | ------------------------------ |
| 200299 | 0 | n/a |
| 400 | 2 | no |
| 401 | 4 | no |
| 403 | 4 | no |
| 404 | 2 | no |
| 408 | 124 | **yes** |
| 409 | 1 | no (mutations) |
| 422 | 2 | no |
| 425 | 1 | **yes** |
| 429 | 5 | **yes** (respects Retry-After) |
| 500 | 1 | configurable (default no) |
| 502 / 503 / 504 | 1 | **yes** |
| Network errors | 1 | **yes** |
| Timeout | 124 | **yes** |
## 6. Internationalization
- Every user-facing string goes through `t("module.key", vars)`.
- Catalogs live in `bin/cli/locales/{locale}.json` (nested objects).
42 files ship out-of-the-box: `en`, `pt-BR`, and 40 additional locales.
11 locales are scaffold-only (empty `{}`); all keys fall back to `en` automatically.
- Detection order: `--lang` flag → `OMNIROUTE_LANG` env → `LC_ALL``LC_MESSAGES``LANG``en`.
- Locale persisted via `config lang set <code>` — saves `OMNIROUTE_LANG` to `~/.omniroute/.env`.
- Missing keys return the key itself (no crash).
- PRs that add new strings **must** update `en.json` and `pt-BR.json`.
Other locale files are best-effort; missing keys silently fall back to `en`.
- `normalize()` in `i18n.mjs` validates locale codes via `/^[a-zA-Z0-9-]+$/` to
prevent path traversal — never pass raw filesystem paths.
- Canonical locale list: `config/i18n.json` — source of truth used by both CLI and
dashboard i18n pipelines.
### Adding a new locale file
1. Add entry to `config/i18n.json` with `code`, `english`, `native`, `flag`.
2. Run `node bin/cli/scripts/generate-locales.mjs` — creates `bin/cli/locales/{code}.json`.
3. Fill in translations (or leave as `{}` for en-fallback scaffold).
4. The pre-commit hook `check-cli-i18n` will verify all `t()` keys exist in `en.json`.
## 7. Logs / output channels
- `stdout` — useful output (parseable when `--output json|jsonl|csv`).
- `stderr` — progress, warnings, errors, spinners.
- `--verbose` / `-V` — extra detail on stderr.
- `--debug` — stack traces, request bodies (dev-mode only; redacts secrets).
## 8. Server-first / DB-fallback
Single helper:
```js
import { withRuntime } from "./runtime.mjs";
await withRuntime(async ({ kind, api, db }) => {
if (kind === "http")
return api("/api/combos", { retry: false, timeout: 5000, acceptNotOk: true });
return db.combos.getCombos();
});
```
- `kind: "http"` when server is up (preferred). `api` is `apiFetch` bound to
the current profile/base-URL.
- `kind: "db"` when server is offline. `db` exposes typed module exports:
- `db.combos``src/lib/db/combos.ts` (getCombos, getComboByName, createCombo,
deleteComboByName, setActiveCombo, …)
- `db.recovery``src/lib/db/recovery.ts` (countEncryptedCredentials,
resetEncryptedColumns)
- Mutations that require server **must** error with exit code `3` when the
server is down, never silently fall back.
- **Never** write raw SQL in commands — always go through `src/lib/db/` modules.
The Semgrep rule at `.semgrep/rules/cli-no-sqlite.yaml` enforces this at commit time.
## 9. Audit of destructive actions
Commands that mutate state (delete, reset, `--force`) **must**:
- Ask for interactive confirmation (skipped with `--yes`).
- POST to `/api/compliance/audit-log` when the server is up.
- Support `--dry-run` (preview without effect).
## 10. Secrets
- **Never** log secrets. Mask as `sk-***-xxx` via `maskSecret()` from
`bin/cli/output.mjs`.
- **Never** accept a secret via positional without warning. Prefer:
- env (`OMNIROUTE_*_API_KEY`)
- stdin (`--api-key-stdin`)
- interactive `askSecret()` (echo off — already implemented in `io.mjs`)
- Secrets must not appear in `--verbose` / `--debug` output.
## 11. Testing baseline
- Every new command ships with at least one smoke test (happy path + one
error path).
- Use `tests/unit/cli-*.test.ts` naming. Prefer `node:test` for CLI suites
(no extra deps).
- Coverage target: ≥60% for `bin/cli/commands/`, ≥75% for `bin/cli/` overall
after Fase 8.
## 12. References
- CLAUDE.md hard rules — especially #11 (publicCreds), #12 (error
sanitization), #13 (shell injection).
- `docs/security/ERROR_SANITIZATION.md` — the only acceptable error shapes.
- `tests/unit/cli-tools-i18n.test.ts` — current i18n infrastructure (pre-`t()`).
- Commander.js docs — Options & subcommand patterns.

146
bin/cli/README.md Normal file
View File

@@ -0,0 +1,146 @@
# bin/cli — OmniRoute CLI internals
This directory contains the CLI runtime, helpers, and commands for the `omniroute` binary.
## Structure
```
bin/cli/
├── CONVENTIONS.md ← normative design rules (read this first)
├── README.md ← this file
├── program.mjs ← Commander setup — global flags, registerCommands()
├── api.mjs ← apiFetch() — all HTTP calls + retry/backoff
├── runtime.mjs ← withRuntime() — server-first / DB-fallback
├── i18n.mjs ← t() — i18n helper + locale detection
├── output.mjs ← emit() — table/json/jsonl/csv + printSuccess/printError
├── io.mjs ← ask() / askSecret() — interactive prompts
├── data-dir.mjs ← resolveDataDir() / resolveStoragePath()
├── sqlite.mjs ← openOmniRouteDb() — DB bootstrap
├── encryption.mjs ← encrypt/decrypt credentials
├── provider-catalog.mjs ← static provider catalog
├── provider-store.mjs ← DB CRUD for provider_connections
├── provider-test.mjs ← testProviderApiKey()
├── settings-store.mjs ← DB CRUD for key_value settings
├── locales/
│ ├── en.json ← English strings (source of truth, 42+ locales)
│ ├── pt-BR.json ← Portuguese (Brazil) — fully translated
│ └── {locale}.json ← 40 additional locales (ar, az, de, es, fr, ja, zh-CN, …)
├── scripts/
│ └── generate-locales.mjs ← scaffold new locale files from config/i18n.json
└── commands/
├── setup.mjs
├── doctor.mjs
├── providers.mjs
├── config.mjs ← includes `config lang get/set/list`
├── status.mjs
├── logs.mjs
└── update.mjs
```
## Key helpers
### `apiFetch(path, opts)` — `api.mjs`
All HTTP calls to the OmniRoute server must go through this wrapper.
```js
import { apiFetch } from "./api.mjs";
const res = await apiFetch("/api/health");
if (!res.ok) await res.assertOk(); // throws ApiError with mapped exit code
const data = await res.json();
```
Options:
- `baseUrl` — override base URL (default: `OMNIROUTE_BASE_URL` env or `localhost:20128`)
- `apiKey` — override API key (default: `OMNIROUTE_API_KEY`)
- `method`, `body`, `headers` — standard fetch options
- `timeout` — per-attempt ms (default: `30000`)
- `retry``false` to disable (default: enabled)
- `retryMax` — total attempts (default: `3`)
- `verbose` — log retry attempts to stderr
### `withRuntime(fn, opts)` — `runtime.mjs`
Provides server-first / DB-fallback transparently.
```js
import { withRuntime } from "./runtime.mjs";
await withRuntime(async (ctx) => {
if (ctx.kind === "http") {
const res = await ctx.api("/v1/providers");
return res.json();
}
return ctx.db.prepare("SELECT * FROM provider_connections").all();
});
```
- `opts.requireServer = true` — throws `ServerOfflineError` (exit 3) if offline
- `opts.preferDb = true` — always use DB (skip server check)
### `t(key, vars)` — `i18n.mjs`
Internationalized strings. Catalog loaded from `locales/{locale}.json`.
```js
import { t } from "./i18n.mjs";
console.log(t("common.serverOffline"));
console.log(t("setup.testFailed", { error: err.message }));
```
Locale detection order: `OMNIROUTE_LANG``LC_ALL``LC_MESSAGES``LANG``en`.
### `emit(data, opts)` — `output.mjs`
Format-aware output. Reads `opts.output` to select table/json/jsonl/csv.
```js
import { emit, printError, EXIT_CODES } from "./output.mjs";
emit(providers, { output: opts.output ?? "table" });
printError("Something went wrong");
process.exit(EXIT_CODES.SERVER_OFFLINE);
```
## Locale selection
The CLI displays text in the user's language. Detection order:
1. `--lang <code>` flag on the command line
2. `OMNIROUTE_LANG` environment variable
3. System env: `LC_ALL``LC_MESSAGES``LANG`
4. Fallback: `en`
**Set permanently:**
```bash
omniroute config lang set pt-BR # saves to ~/.omniroute/.env
omniroute config lang list # show all 42 available locales
omniroute config lang get # show currently active locale
```
**One-time override:**
```bash
omniroute --lang de providers list # run in German, not persisted
OMNIROUTE_LANG=ja omniroute status # same effect via env
```
**Adding a new locale**: add entry to `config/i18n.json`, then run:
```bash
node bin/cli/scripts/generate-locales.mjs
```
## Adding a new command
1. Create `bin/cli/commands/your-command.mjs`
2. Export `registerYourCommand(program)` following the Commander pattern
3. Register in `bin/cli/commands/registry.mjs`
4. Add strings to `locales/en.json` and `locales/pt-BR.json`
5. Write test in `tests/unit/cli-your-command.test.ts`
See `CONVENTIONS.md` for exit codes, flag naming, output format, and destructive-action rules.

View File

@@ -0,0 +1,58 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_api_keys(parent) {
const tag = parent.command("api-keys").description("API Keys endpoints");
tag
.command("get-api-keys")
.description("List API keys")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/keys";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-keys")
.description("Create API key")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/keys";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-keys-id-")
.description("Delete API key")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/keys/{id}";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,52 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_audio(parent) {
const tag = parent.command("audio").description("Audio endpoints");
tag
.command("post-api-v1-audio-speech")
.description("Generate speech audio")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/audio/speech";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-v1-audio-transcriptions")
.description("Transcribe audio")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/audio/transcriptions";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,76 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_chat(parent) {
const tag = parent.command("chat").description("Chat endpoints");
tag
.command("post-api-v1-chat-completions")
.description("Create chat completion")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/chat/completions";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-v1-providers-provider-chat-completions")
.description("Create chat completion (provider-specific)")
.requiredOption("--provider <provider>", "")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/providers/{provider}/chat/completions";
url = url.replace("{provider}", encodeURIComponent(opts.provider ?? ""));
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-v1-api-chat")
.description("Ollama-compatible chat endpoint")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/api/chat";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,526 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_cli_tools(parent) {
const tag = parent.command("cli-tools").description("CLI Tools endpoints");
tag
.command("get-api-cli-tools-backups")
.description("List CLI tool backups")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/backups";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-cli-tools-backups")
.description("Create CLI tool backup")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/backups";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cli-tools-runtime-tool-id-")
.description("Get runtime status for a CLI tool")
.requiredOption("--tool-id <toolId>", "")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/runtime/{toolId}";
url = url.replace("{toolId}", encodeURIComponent(opts.toolId ?? ""));
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cli-tools-guide-settings-tool-id-")
.description("Get guide settings for a tool")
.requiredOption("--tool-id <toolId>", "")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/guide-settings/{toolId}";
url = url.replace("{toolId}", encodeURIComponent(opts.toolId ?? ""));
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cli-tools-antigravity-mitm")
.description("Get Antigravity MITM proxy settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/antigravity-mitm";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-cli-tools-antigravity-mitm")
.description("Update Antigravity MITM proxy settings")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/antigravity-mitm";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-cli-tools-antigravity-mitm")
.description("Reset Antigravity MITM proxy settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/antigravity-mitm";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cli-tools-antigravity-mitm-alias")
.description("Get Antigravity MITM alias configuration")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/antigravity-mitm/alias";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("put-api-cli-tools-antigravity-mitm-alias")
.description("Update Antigravity MITM alias configuration")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/antigravity-mitm/alias";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PUT",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cli-tools-claude-settings")
.description("Get Claude CLI settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/claude-settings";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-cli-tools-claude-settings")
.description("Apply Claude CLI settings")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/claude-settings";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-cli-tools-claude-settings")
.description("Reset Claude CLI settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/claude-settings";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cli-tools-cline-settings")
.description("Get Cline CLI settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/cline-settings";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-cli-tools-cline-settings")
.description("Apply Cline CLI settings")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/cline-settings";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-cli-tools-cline-settings")
.description("Reset Cline CLI settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/cline-settings";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cli-tools-codex-profiles")
.description("Get Codex profiles")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/codex-profiles";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-cli-tools-codex-profiles")
.description("Create Codex profile")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/codex-profiles";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("put-api-cli-tools-codex-profiles")
.description("Update Codex profile")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/codex-profiles";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PUT",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-cli-tools-codex-profiles")
.description("Delete Codex profile")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/codex-profiles";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cli-tools-codex-settings")
.description("Get Codex CLI settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/codex-settings";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-cli-tools-codex-settings")
.description("Apply Codex CLI settings")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/codex-settings";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-cli-tools-codex-settings")
.description("Reset Codex CLI settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/codex-settings";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cli-tools-droid-settings")
.description("Get Droid CLI settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/droid-settings";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-cli-tools-droid-settings")
.description("Apply Droid CLI settings")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/droid-settings";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-cli-tools-droid-settings")
.description("Reset Droid CLI settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/droid-settings";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cli-tools-kilo-settings")
.description("Get Kilo CLI settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/kilo-settings";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-cli-tools-kilo-settings")
.description("Apply Kilo CLI settings")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/kilo-settings";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-cli-tools-kilo-settings")
.description("Reset Kilo CLI settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/kilo-settings";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cli-tools-openclaw-settings")
.description("Get OpenClaw CLI settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/openclaw-settings";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-cli-tools-openclaw-settings")
.description("Apply OpenClaw CLI settings")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/openclaw-settings";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-cli-tools-openclaw-settings")
.description("Reset OpenClaw CLI settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cli-tools/openclaw-settings";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,110 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_cloud(parent) {
const tag = parent.command("cloud").description("Cloud endpoints");
tag
.command("post-api-cloud-auth")
.description("Authenticate with cloud worker")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cloud/auth";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("put-api-cloud-credentials-update")
.description("Update cloud worker credentials")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cloud/credentials/update";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PUT",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-cloud-model-resolve")
.description("Resolve model via cloud")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cloud/model/resolve";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cloud-models-alias")
.description("Get cloud model aliases")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cloud/models/alias";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("put-api-cloud-models-alias")
.description("Update cloud model alias")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cloud/models/alias";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PUT",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,100 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_combos(parent) {
const tag = parent.command("combos").description("Combos endpoints");
tag
.command("get-api-combos")
.description("List routing combos")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/combos";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-combos")
.description("Create routing combo")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/combos";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("patch-api-combos-id-")
.description("Update combo")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/combos/{id}";
const res = await apiFetch(url, {
method: "PATCH",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-combos-id-")
.description("Delete combo")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/combos/{id}";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-combos-metrics")
.description("Get combo metrics")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/combos/metrics";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-combos-test")
.description("Test a combo configuration")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/combos/test";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,182 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_compression(parent) {
const tag = parent.command("compression").description("Compression endpoints");
tag
.command("get-api-settings-compression")
.description("Get global compression settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/compression";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("put-api-settings-compression")
.description("Update global compression settings")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/compression";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PUT",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-compression-preview")
.description("Preview compression for a message payload")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/compression/preview";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-compression-language-packs")
.description("List Caveman compression language packs")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/compression/language-packs";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-compression-rules")
.description("List Caveman compression rule metadata")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/compression/rules";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-context-rtk-config")
.description("Get RTK compression settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/context/rtk/config";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("put-api-context-rtk-config")
.description("Update RTK compression settings")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/context/rtk/config";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PUT",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-context-rtk-filters")
.description("List RTK filters and load diagnostics")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/context/rtk/filters";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-context-rtk-test")
.description("Run RTK compression preview for text")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/context/rtk/test";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-context-rtk-raw-output-id-")
.description("Read retained redacted RTK raw output")
.requiredOption("--id <id>", "")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/context/rtk/raw-output/{id}";
url = url.replace("{id}", encodeURIComponent(opts.id ?? ""));
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,54 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_embeddings(parent) {
const tag = parent.command("embeddings").description("Embeddings endpoints");
tag
.command("post-api-v1-embeddings")
.description("Create embeddings")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/embeddings";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-v1-providers-provider-embeddings")
.description("Create embeddings (provider-specific)")
.requiredOption("--provider <provider>", "")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/providers/{provider}/embeddings";
url = url.replace("{provider}", encodeURIComponent(opts.provider ?? ""));
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,66 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_fallback(parent) {
const tag = parent.command("fallback").description("Fallback endpoints");
tag
.command("get-api-fallback-chains")
.description("List fallback chains")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/fallback/chains";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-fallback-chains")
.description("Create fallback chain")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/fallback/chains";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-fallback-chains")
.description("Delete fallback chain")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/fallback/chains";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "DELETE",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,54 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_images(parent) {
const tag = parent.command("images").description("Images endpoints");
tag
.command("post-api-v1-images-generations")
.description("Generate images")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/images/generations";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-v1-providers-provider-images-generations")
.description("Generate images (provider-specific)")
.requiredOption("--provider <provider>", "")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/providers/{provider}/images/generations";
url = url.replace("{provider}", encodeURIComponent(opts.provider ?? ""));
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,52 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_messages(parent) {
const tag = parent.command("messages").description("Messages endpoints");
tag
.command("post-api-v1-messages")
.description("Create message (Anthropic-compatible)")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/messages";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-v1-messages-count-tokens")
.description("Count tokens for a message")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/messages/count_tokens";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,129 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_models(parent) {
const tag = parent.command("models").description("Models endpoints");
tag
.command("get-api-v1-models")
.description("List available models")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/models";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-v1-providers-provider-models")
.description("List models for a specific provider")
.requiredOption(
"--provider <provider>",
"Provider id or alias (for example `openai`, `claude`, `cc`)."
)
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/providers/{provider}/models";
url = url.replace("{provider}", encodeURIComponent(opts.provider ?? ""));
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-models")
.description("List models (management)")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/models";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-models-alias")
.description("Create or update a model alias")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/models/alias";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-models-catalog")
.description("Get full model catalog")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/models/catalog";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-v1beta-models")
.description("List models (Gemini format)")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1beta/models";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-v1beta-models-path-")
.description("Gemini generateContent")
.requiredOption("--path <path>", "")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1beta/models/{path}";
url = url.replace("{path}", encodeURIComponent(opts.path ?? ""));
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,30 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_moderations(parent) {
const tag = parent.command("moderations").description("Moderations endpoints");
tag
.command("post-api-v1-moderations")
.description("Create moderation")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/moderations";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,162 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_oauth(parent) {
const tag = parent.command("oauth").description("OAuth endpoints");
tag
.command("get-api-oauth-provider-action-")
.description("OAuth flow handler")
.requiredOption("--provider <provider>", "")
.requiredOption("--action <action>", "")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/oauth/{provider}/{action}";
url = url.replace("{provider}", encodeURIComponent(opts.provider ?? ""));
url = url.replace("{action}", encodeURIComponent(opts.action ?? ""));
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-oauth-cursor-auto-import")
.description("Auto-import Cursor OAuth credentials")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/oauth/cursor/auto-import";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-oauth-cursor-import")
.description("Get Cursor import status")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/oauth/cursor/import";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-oauth-cursor-import")
.description("Import Cursor OAuth credentials")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/oauth/cursor/import";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-oauth-kiro-auto-import")
.description("Auto-import Kiro OAuth credentials")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/oauth/kiro/auto-import";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-oauth-kiro-import")
.description("Get Kiro import status")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/oauth/kiro/import";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-oauth-kiro-import")
.description("Import Kiro OAuth credentials")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/oauth/kiro/import";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-oauth-kiro-social-authorize")
.description("Initiate Kiro social OAuth authorization")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/oauth/kiro/social-authorize";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-oauth-kiro-social-exchange")
.description("Exchange Kiro social OAuth token")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/oauth/kiro/social-exchange";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,64 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_pricing(parent) {
const tag = parent.command("pricing").description("Pricing endpoints");
tag
.command("get-api-pricing")
.description("Get model pricing")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/pricing";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-pricing")
.description("Set model pricing")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/pricing";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-pricing-defaults")
.description("Get default pricing")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/pricing/defaults";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-pricing-models")
.description("Get pricing per model")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/pricing/models";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,92 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_provider_nodes(parent) {
const tag = parent.command("provider-nodes").description("Provider Nodes endpoints");
tag
.command("get-api-provider-nodes")
.description("List provider nodes")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/provider-nodes";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-provider-nodes")
.description("Create provider node")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/provider-nodes";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("patch-api-provider-nodes-id-")
.description("Update provider node")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/provider-nodes/{id}";
const res = await apiFetch(url, {
method: "PATCH",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-provider-nodes-id-")
.description("Delete provider node")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/provider-nodes/{id}";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-provider-nodes-validate")
.description("Validate a provider node")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/provider-nodes/validate";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-provider-models")
.description("List provider models")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/provider-models";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,164 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_providers(parent) {
const tag = parent.command("providers").description("Providers endpoints");
tag
.command("get-api-providers")
.description("List provider connections")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/providers";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-providers")
.description("Create provider connection")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/providers";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-providers-id-")
.description("Get provider connection")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/providers/{id}";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("patch-api-providers-id-")
.description("Update provider connection")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/providers/{id}";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PATCH",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-providers-id-")
.description("Delete provider connection")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/providers/{id}";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-providers-id-test")
.description("Test provider connection")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/providers/{id}/test";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-providers-id-models")
.description("List models for a provider")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/providers/{id}/models";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-providers-test-batch")
.description("Test multiple providers at once")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/providers/test-batch";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-providers-validate")
.description("Validate provider credentials")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/providers/validate";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-providers-client")
.description("Get client-side provider info")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/providers/client";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,88 @@
// AUTO-GENERATED. Do not edit.
import { register_chat } from "./chat.mjs";
import { register_messages } from "./messages.mjs";
import { register_responses } from "./responses.mjs";
import { register_embeddings } from "./embeddings.mjs";
import { register_images } from "./images.mjs";
import { register_audio } from "./audio.mjs";
import { register_moderations } from "./moderations.mjs";
import { register_rerank } from "./rerank.mjs";
import { register_system } from "./system.mjs";
import { register_models } from "./models.mjs";
import { register_providers } from "./providers.mjs";
import { register_provider_nodes } from "./provider-nodes.mjs";
import { register_api_keys } from "./api-keys.mjs";
import { register_combos } from "./combos.mjs";
import { register_settings } from "./settings.mjs";
import { register_compression } from "./compression.mjs";
import { register_usage } from "./usage.mjs";
import { register_pricing } from "./pricing.mjs";
import { register_translator } from "./translator.mjs";
import { register_cli_tools } from "./cli-tools.mjs";
import { register_oauth } from "./oauth.mjs";
import { register_cloud } from "./cloud.mjs";
import { register_fallback } from "./fallback.mjs";
import { register_telemetry } from "./telemetry.mjs";
export const API_TAGS = [
"chat",
"messages",
"responses",
"embeddings",
"images",
"audio",
"moderations",
"rerank",
"system",
"models",
"providers",
"provider-nodes",
"api-keys",
"combos",
"settings",
"compression",
"usage",
"pricing",
"translator",
"cli-tools",
"oauth",
"cloud",
"fallback",
"telemetry",
];
export function registerApiCommands(program) {
const api = program
.command("api")
.description("Direct REST API access (generated from OpenAPI spec)");
api
.command("tags")
.description("List available API tag groups")
.action(() => {
API_TAGS.forEach((t) => console.log(t));
});
register_chat(api);
register_messages(api);
register_responses(api);
register_embeddings(api);
register_images(api);
register_audio(api);
register_moderations(api);
register_rerank(api);
register_system(api);
register_models(api);
register_providers(api);
register_provider_nodes(api);
register_api_keys(api);
register_combos(api);
register_settings(api);
register_compression(api);
register_usage(api);
register_pricing(api);
register_translator(api);
register_cli_tools(api);
register_oauth(api);
register_cloud(api);
register_fallback(api);
register_telemetry(api);
}

View File

@@ -0,0 +1,30 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_rerank(parent) {
const tag = parent.command("rerank").description("Rerank endpoints");
tag
.command("post-api-v1-rerank")
.description("Rerank documents")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/rerank";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,30 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_responses(parent) {
const tag = parent.command("responses").description("Responses endpoints");
tag
.command("post-api-v1-responses")
.description("Create response (OpenAI Responses API)")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1/responses";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,294 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_settings(parent) {
const tag = parent.command("settings").description("Settings endpoints");
tag
.command("get-api-settings")
.description("Get application settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("patch-api-settings")
.description("Update settings")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PATCH",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-settings-payload-rules")
.description("Get payload rules configuration")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/payload-rules";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("put-api-settings-payload-rules")
.description("Update payload rules configuration")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/payload-rules";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PUT",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-settings-combo-defaults")
.description("Get combo default settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/combo-defaults";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-settings-proxy")
.description("Get proxy settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/proxy";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("patch-api-settings-proxy")
.description("Update proxy settings")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/proxy";
const res = await apiFetch(url, {
method: "PATCH",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-settings-proxy-test")
.description("Test proxy connection")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/proxy/test";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-settings-require-login")
.description("Toggle login requirement")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/require-login";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-settings-ip-filter")
.description("Get IP filter configuration")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/ip-filter";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("put-api-settings-ip-filter")
.description("Update IP filter configuration")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/ip-filter";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PUT",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-settings-system-prompt")
.description("Get system prompt configuration")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/system-prompt";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("put-api-settings-system-prompt")
.description("Update system prompt configuration")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/system-prompt";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PUT",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-settings-thinking-budget")
.description("Get thinking budget configuration")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/thinking-budget";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("put-api-settings-thinking-budget")
.description("Update thinking budget configuration")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/settings/thinking-budget";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PUT",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-rate-limit")
.description("Get rate limit configuration")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/rate-limit";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-rate-limit")
.description("Update rate limit configuration")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/rate-limit";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,466 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_system(parent) {
const tag = parent.command("system").description("System endpoints");
tag
.command("get-api-v1")
.description("API v1 root endpoint")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/v1";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-tags")
.description("List Ollama-compatible model tags")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/tags";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-auth-login")
.description("Authenticate user")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/auth/login";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-auth-logout")
.description("Log out")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/auth/logout";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-init")
.description("Initialize application")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/init";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-restart")
.description("Restart the application")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/restart";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-shutdown")
.description("Shutdown the application")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/shutdown";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-db-backups")
.description("List database backups")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/db-backups";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-db-backups")
.description("Create database backup")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/db-backups";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-storage-health")
.description("Check storage health")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/storage/health";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-sync-cloud")
.description("Sync with cloud")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/sync/cloud";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-sync-initialize")
.description("Initialize cloud sync")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/sync/initialize";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-resilience")
.description("Get resilience configuration")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/resilience";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("patch-api-resilience")
.description("Update resilience configuration")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/resilience";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "PATCH",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-resilience-reset")
.description("Reset circuit breakers")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/resilience/reset";
const res = await apiFetch(url, {
method: "POST",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-monitoring-health")
.description("System health check")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/monitoring/health";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-rate-limits")
.description("Get per-account rate limit status")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/rate-limits";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-sessions")
.description("Get active sessions")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/sessions";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cache")
.description("Get cache statistics")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cache";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-cache")
.description("Clear all caches")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cache";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-cache-stats")
.description("Get detailed cache statistics")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cache/stats";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-cache-stats")
.description("Clear cache statistics")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/cache/stats";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-evals")
.description("List eval suites")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/evals";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-evals")
.description("Run evaluation")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/evals";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-evals-suite-id-")
.description("Get eval suite details")
.requiredOption("--suite-id <suiteId>", "")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/evals/{suiteId}";
url = url.replace("{suiteId}", encodeURIComponent(opts.suiteId ?? ""));
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-policies")
.description("List routing policies")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/policies";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-policies")
.description("Create routing policy")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/policies";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("delete-api-policies")
.description("Delete routing policy")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/policies";
const res = await apiFetch(url, {
method: "DELETE",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-compliance-audit-log")
.description("Get compliance audit log")
.option("--limit <limit>", "")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/compliance/audit-log";
const qs = new URLSearchParams();
if (opts.limit != null) qs.set("limit", String(opts.limit));
if (qs.toString()) url += "?" + qs.toString();
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-openapi-spec")
.description("Get OpenAPI specification catalog")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/openapi/spec";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,36 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_telemetry(parent) {
const tag = parent.command("telemetry").description("Telemetry endpoints");
tag
.command("get-api-telemetry-summary")
.description("Get telemetry summary")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/telemetry/summary";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-token-health")
.description("Get token health status")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/token-health";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,88 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_translator(parent) {
const tag = parent.command("translator").description("Translator endpoints");
tag
.command("post-api-translator-detect")
.description("Detect request format")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/translator/detect";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-translator-translate")
.description("Translate between formats")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/translator/translate";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-translator-send")
.description("Send translated request to provider")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/translator/send";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-translator-history")
.description("Get translation history")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/translator/history";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

View File

@@ -0,0 +1,168 @@
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { readFileSync } from "node:fs";
export function register_usage(parent) {
const tag = parent.command("usage").description("Usage endpoints");
tag
.command("get-api-usage-analytics")
.description("Get usage analytics")
.option("--period <period>", "")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/usage/analytics";
const qs = new URLSearchParams();
if (opts.period != null) qs.set("period", String(opts.period));
if (qs.toString()) url += "?" + qs.toString();
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-usage-call-logs")
.description("Get call logs")
.option("--limit <limit>", "")
.option("--offset <offset>", "")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/usage/call-logs";
const qs = new URLSearchParams();
if (opts.limit != null) qs.set("limit", String(opts.limit));
if (opts.offset != null) qs.set("offset", String(opts.offset));
if (qs.toString()) url += "?" + qs.toString();
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-usage-call-logs-id-")
.description("Get a specific call log")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/usage/call-logs/{id}";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-usage-connection-id-")
.description("Get usage for a specific connection")
.requiredOption("--connection-id <connectionId>", "")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/usage/{connectionId}";
url = url.replace("{connectionId}", encodeURIComponent(opts.connectionId ?? ""));
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-usage-history")
.description("Get usage history")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/usage/history";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-usage-logs")
.description("Get usage logs")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/usage/logs";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-usage-proxy-logs")
.description("Get proxy logs")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/usage/proxy-logs";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-usage-request-logs")
.description("Get request logs")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/usage/request-logs";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("get-api-usage-budget")
.description("Get usage budget status")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/usage/budget";
const res = await apiFetch(url, {
method: "GET",
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
tag
.command("post-api-usage-budget")
.description("Configure usage budget")
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
.action(async (opts, cmd) => {
const gOpts = cmd.optsWithGlobals();
let url = "/api/usage/budget";
let body;
if (opts.body) {
body = opts.body.startsWith("@")
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
: JSON.parse(opts.body);
}
const res = await apiFetch(url, {
method: "POST",
body,
baseUrl: gOpts.baseUrl,
apiKey: gOpts.apiKey,
});
const data = res.ok ? await res.json() : await res.text();
emit(data, gOpts);
});
}

245
bin/cli/api.mjs Normal file
View File

@@ -0,0 +1,245 @@
import { setTimeout as sleep } from "node:timers/promises";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { resolveDataDir } from "./data-dir.mjs";
import { getCliToken, CLI_TOKEN_HEADER } from "./utils/cliToken.mjs";
export const RETRY_DEFAULTS = Object.freeze({
maxAttempts: 3,
baseMs: 500,
maxMs: 8000,
jitter: true,
retryableStatuses: [408, 425, 429, 502, 503, 504],
retryableErrorCodes: [
"ECONNRESET",
"ECONNREFUSED",
"ETIMEDOUT",
"ENOTFOUND",
"EAI_AGAIN",
"EPIPE",
],
});
const NON_RETRYABLE_ON_MUTATION = new Set([409, 422, 429]);
const MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
export function getBaseUrl(opts = {}) {
if (opts.baseUrl) return stripTrailingSlash(opts.baseUrl);
const envUrl = process.env.OMNIROUTE_BASE_URL;
if (envUrl) return stripTrailingSlash(envUrl);
try {
const configPath = join(resolveDataDir(), "config.json");
if (existsSync(configPath)) {
const cfg = JSON.parse(readFileSync(configPath, "utf8"));
const profile = cfg.activeProfile && cfg.profiles?.[cfg.activeProfile];
if (profile?.baseUrl) return stripTrailingSlash(profile.baseUrl);
if (cfg.baseUrl) return stripTrailingSlash(cfg.baseUrl);
}
} catch {
// Config read failures are not fatal — fall through to default.
}
const port = process.env.PORT || "20128";
return `http://localhost:${port}`;
}
function stripTrailingSlash(value) {
return String(value).replace(/\/+$/, "");
}
function resolveUrl(path, opts) {
if (/^https?:\/\//i.test(path)) return path;
return `${getBaseUrl(opts)}${path.startsWith("/") ? path : `/${path}`}`;
}
async function buildHeaders(opts) {
const headers = new Headers(opts.headers || {});
if (!headers.has("accept")) headers.set("accept", "application/json");
if (opts.body && !headers.has("content-type") && typeof opts.body !== "string") {
headers.set("content-type", "application/json");
}
const apiKey = opts.apiKey ?? process.env.OMNIROUTE_API_KEY;
if (apiKey && !headers.has("authorization")) {
headers.set("authorization", `Bearer ${apiKey}`);
}
// Inject machine-id derived CLI token; env var override for testing.
const cliToken = opts.cliToken ?? process.env.OMNIROUTE_CLI_TOKEN ?? (await getCliToken());
if (cliToken && !headers.has(CLI_TOKEN_HEADER)) {
headers.set(CLI_TOKEN_HEADER, cliToken);
}
if (opts.idempotencyKey && !headers.has("idempotency-key")) {
headers.set("idempotency-key", opts.idempotencyKey);
}
return headers;
}
function serializeBody(body, headers) {
if (body == null) return undefined;
if (typeof body === "string") return body;
if (body instanceof Buffer) return body;
if (body instanceof URLSearchParams) return body;
if (typeof body.pipe === "function") return body; // stream
if (headers.get("content-type")?.includes("application/json")) return JSON.stringify(body);
return JSON.stringify(body);
}
export function computeBackoff(attempt, retryAfterHeader, defaults = RETRY_DEFAULTS) {
if (retryAfterHeader != null) {
const secs = Number.parseFloat(String(retryAfterHeader));
if (Number.isFinite(secs) && secs >= 0) {
return Math.min(secs * 1000, defaults.maxMs);
}
}
const exp = Math.min(defaults.baseMs * 2 ** (attempt - 1), defaults.maxMs);
if (!defaults.jitter) return exp;
const jitter = exp * 0.25 * (Math.random() * 2 - 1);
return Math.max(0, exp + jitter);
}
export function shouldRetryStatus(status, method, opts = {}) {
if (opts.retry === false) return false;
const list = opts.retryableStatuses || RETRY_DEFAULTS.retryableStatuses;
if (!list.includes(status)) return false;
if (MUTATING_METHODS.has(method) && NON_RETRYABLE_ON_MUTATION.has(status)) {
return status === 429 ? Boolean(opts.retryMutationsOn429) : false;
}
return true;
}
export function shouldRetryError(err, opts = {}) {
if (opts.retry === false) return false;
const codes = opts.retryableErrorCodes || RETRY_DEFAULTS.retryableErrorCodes;
if (err?.code && codes.includes(err.code)) return true;
if (err?.name === "AbortError" || /timeout|abort/i.test(err?.message || "")) return true;
return false;
}
export function statusToExitCode(status) {
if (status >= 200 && status < 300) return 0;
if (status === 408) return 124;
if (status === 401 || status === 403) return 4;
if (status === 429) return 5;
if (status === 400 || status === 404 || status === 422) return 2;
if (status >= 500) return 1;
return 1;
}
export class ApiError extends Error {
constructor(message, { status, code, exitCode } = {}) {
super(message);
this.name = "ApiError";
this.status = status;
this.code = code;
this.exitCode = exitCode ?? (status != null ? statusToExitCode(status) : 1);
}
}
async function readResponseBody(res) {
const ct = res.headers.get("content-type") || "";
try {
if (ct.includes("application/json")) return await res.json();
return await res.text();
} catch {
return null;
}
}
function fetchOnce(url, init, timeoutMs) {
if (!timeoutMs) return fetch(url, init);
const ac = new AbortController();
const t = setTimeout(() => ac.abort(), timeoutMs);
const merged = { ...init, signal: ac.signal };
return fetch(url, merged).finally(() => clearTimeout(t));
}
export async function apiFetch(path, opts = {}) {
const method = String(opts.method || "GET").toUpperCase();
const url = resolveUrl(path, opts);
const headers = await buildHeaders(opts);
const body = serializeBody(opts.body, headers);
const timeout =
opts.timeout ?? (Number.parseInt(process.env.OMNIROUTE_HTTP_TIMEOUT_MS || "", 10) || 30000);
const maxAttempts = opts.retry === false ? 1 : (opts.retryMax ?? RETRY_DEFAULTS.maxAttempts);
const verbose = opts.verbose ?? process.env.OMNIROUTE_VERBOSE === "1";
let lastErr;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const res = await fetchOnce(url, { method, headers, body }, timeout);
if (res.ok) return enrichResponse(res, opts);
if (attempt < maxAttempts && shouldRetryStatus(res.status, method, opts)) {
const delay = computeBackoff(attempt, res.headers.get("retry-after"));
if (verbose) {
process.stderr.write(
`[retry ${attempt}/${maxAttempts - 1}] ${method} ${url} → HTTP ${res.status}; wait ${Math.round(delay)}ms\n`
);
}
await sleep(delay);
continue;
}
return enrichResponse(res, opts);
} catch (err) {
lastErr = err;
if (attempt < maxAttempts && shouldRetryError(err, opts)) {
const delay = computeBackoff(attempt, null);
if (verbose) {
process.stderr.write(
`[retry ${attempt}/${maxAttempts - 1}] ${method} ${url}${err.code || err.message}; wait ${Math.round(delay)}ms\n`
);
}
await sleep(delay);
continue;
}
throw normalizeNetworkError(err);
}
}
throw normalizeNetworkError(lastErr);
}
function enrichResponse(res, opts) {
res.exitCode = statusToExitCode(res.status);
res.json = res.json.bind(res);
res.text = res.text.bind(res);
if (!res.ok && !opts.acceptNotOk) {
res.assertOk = async () => {
const payload = await readResponseBody(res);
const message = extractErrorMessage(payload, res.status);
throw new ApiError(message, { status: res.status });
};
} else {
res.assertOk = async () => res;
}
return res;
}
function extractErrorMessage(payload, status) {
if (payload && typeof payload === "object") {
if (typeof payload.error === "string") return payload.error;
if (payload.error?.message) return String(payload.error.message);
if (payload.message) return String(payload.message);
}
if (typeof payload === "string" && payload.length < 200) return payload;
return `HTTP ${status}`;
}
function normalizeNetworkError(err) {
if (err instanceof ApiError) return err;
const code = err?.code || (err?.name === "AbortError" ? "ETIMEDOUT" : undefined);
const exitCode = code === "ETIMEDOUT" ? 124 : 1;
return new ApiError(err?.message || "network error", { code, exitCode });
}
export async function isServerUp(opts = {}) {
try {
const res = await apiFetch("/api/health", {
...opts,
retry: false,
timeout: opts.timeout ?? 1500,
acceptNotOk: true,
});
return res.ok || res.status < 500;
} catch {
return false;
}
}

View File

@@ -1,47 +0,0 @@
export function parseArgs(argv = []) {
const flags = {};
const positionals = [];
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg.startsWith("-") && !arg.startsWith("--") && arg.length > 1) {
for (const key of arg.slice(1)) {
flags[key] = true;
}
continue;
}
if (!arg.startsWith("--")) {
positionals.push(arg);
continue;
}
const eqIndex = arg.indexOf("=");
if (eqIndex !== -1) {
flags[arg.slice(2, eqIndex)] = arg.slice(eqIndex + 1);
continue;
}
const key = arg.slice(2);
const next = argv[i + 1];
if (next && !next.startsWith("--")) {
flags[key] = next;
i += 1;
} else {
flags[key] = true;
}
}
return { flags, positionals };
}
export function getStringFlag(flags, name, envName = null) {
const value = flags[name] ?? (envName ? process.env[envName] : undefined);
if (typeof value !== "string") return "";
return value.trim();
}
export function hasFlag(flags, name) {
return flags[name] === true;
}

323
bin/cli/commands/a2a.mjs Normal file
View File

@@ -0,0 +1,323 @@
import { readFileSync } from "node:fs";
import { setTimeout as sleep } from "node:timers/promises";
import { apiFetch, isServerUp } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
const A2A_SKILLS = [
{ id: "smart-routing", name: "Smart Request Routing" },
{ id: "quota-management", name: "Quota & Cost Management" },
{ id: "provider-discovery", name: "Provider Discovery" },
{ id: "cost-analysis", name: "Cost Analysis" },
{ id: "health-report", name: "Health Report" },
];
function fmtTs(v) {
if (!v) return "-";
try {
return new Date(v).toLocaleString();
} catch {
return String(v);
}
}
function randomId() {
return Math.random().toString(36).slice(2, 11);
}
async function confirm(q) {
return new Promise((resolve) => {
process.stdout.write(`${q} (yes/no) `);
process.stdin.setEncoding("utf8");
process.stdin.once("data", (c) => resolve(c.toString().trim().toLowerCase().startsWith("y")));
});
}
const taskSchema = [
{ key: "id", header: "Task ID", width: 22 },
{ key: "skill", header: "Skill", width: 22 },
{ key: "status", header: "Status", width: 12 },
{ key: "createdAt", header: "Created", formatter: fmtTs },
{ key: "updatedAt", header: "Updated", formatter: fmtTs },
{ key: "duration", header: "Duration", formatter: (v) => (v != null ? `${v}ms` : "-") },
];
export function registerA2a(program) {
const a2a = program.command("a2a").description("Agent-to-Agent (A2A) server");
a2a
.command("status")
.description("Show A2A server status")
.option("--json", "Output as JSON")
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runA2aStatusCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
a2a
.command("card")
.description("Print the Agent Card JSON")
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runA2aCardCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
// 5.3 — a2a skills + a2a invoke
a2a
.command("skills")
.description(t("a2a.skills.description"))
.action(async (opts, cmd) => {
const res = await apiFetch("/.well-known/agent.json");
if (res.ok) {
const card = await res.json();
emit(card.skills ?? A2A_SKILLS, cmd.optsWithGlobals());
} else {
emit(A2A_SKILLS, cmd.optsWithGlobals());
}
});
a2a
.command("invoke <skill>")
.description(t("a2a.invoke.description"))
.option("--input <json>", t("a2a.invoke.input"))
.option("--input-file <path>", t("a2a.invoke.input_file"))
.option("--wait", t("a2a.invoke.wait"))
.option("--timeout <ms>", t("a2a.invoke.timeout"), parseInt, 60000)
.action(async (skill, opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const input = opts.input
? JSON.parse(opts.input)
: opts.inputFile
? JSON.parse(readFileSync(opts.inputFile, "utf8"))
: {};
const rpcBody = {
jsonrpc: "2.0",
id: randomId(),
method: "tasks.create",
params: {
skill,
input,
messages: [{ role: "user", parts: [{ kind: "data", data: input }] }],
},
};
const res = await apiFetch("/api/a2a/tasks", { method: "POST", body: rpcBody });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const created = await res.json();
const taskId = created.result?.taskId ?? created.taskId ?? created.id;
if (!opts.wait) {
emit({ taskId }, globalOpts);
return;
}
const deadline = Date.now() + (opts.timeout ?? 60000);
while (Date.now() < deadline) {
await sleep(1000);
const taskRes = await apiFetch(`/api/a2a/tasks/${taskId}`);
if (!taskRes.ok) continue;
const task = (await taskRes.json()).result ?? (await taskRes.clone().json());
const state = task.status?.state ?? task.status;
if (["completed", "failed", "cancelled"].includes(state)) {
emit(task, globalOpts);
return;
}
}
process.stderr.write("Timeout waiting for task completion\n");
process.exit(124);
});
// 5.4 — a2a tasks
const tasks = a2a.command("tasks").description(t("a2a.tasks.description"));
tasks
.command("list")
.option("--status <s>", t("a2a.tasks.list.status"))
.option("--skill <s>", t("a2a.tasks.list.skill"))
.option("--limit <n>", parseInt, 50)
.option("--since <ts>")
.action(async (opts, cmd) => {
const params = new URLSearchParams({ limit: String(opts.limit ?? 50) });
if (opts.status) params.set("status", opts.status);
if (opts.skill) params.set("skill", opts.skill);
if (opts.since) params.set("since", opts.since);
const res = await apiFetch(`/api/a2a/tasks?${params}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.tasks ?? data.items ?? data, cmd.optsWithGlobals(), taskSchema);
});
tasks.command("get <id>").action(async (id, opts, cmd) => {
const res = await apiFetch(`/api/a2a/tasks/${id}`);
if (!res.ok) {
process.stderr.write(`Not found: ${id}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
tasks
.command("cancel <id>")
.option("--yes")
.action(async (id, opts, cmd) => {
if (!opts.yes) {
const ok = await confirm(`Cancel task ${id}?`);
if (!ok) return;
}
const res = await apiFetch(`/api/a2a/tasks/${id}/cancel`, { method: "POST" });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
process.stdout.write("Cancelled\n");
});
tasks
.command("watch <id>")
.description(t("a2a.tasks.watch.description"))
.action(async (id, opts, cmd) => {
let lastState = "";
while (true) {
const res = await apiFetch(`/api/a2a/tasks/${id}`);
if (res.ok) {
const data = await res.json();
const state = data.status?.state ?? data.status ?? "";
if (state !== lastState) {
process.stderr.write(`[${new Date().toISOString()}] ${state}\n`);
lastState = state;
}
if (["completed", "failed", "cancelled"].includes(state)) {
emit(data, cmd.optsWithGlobals());
return;
}
}
await sleep(1500);
}
});
tasks
.command("stream <id>")
.description(t("a2a.tasks.stream.description"))
.action(async (id, opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const baseUrl = globalOpts.baseUrl ?? "http://localhost:20128";
const apiKey = globalOpts.apiKey ?? "";
const res = await fetch(`${baseUrl}/api/a2a/tasks/${id}?stream=true`, {
headers: {
Accept: "text/event-stream",
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
},
});
if (!res.ok) {
process.stderr.write(`HTTP ${res.status}\n`);
process.exit(1);
}
const reader = res.body.getReader();
const dec = new TextDecoder();
let buf = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
const lines = buf.split("\n");
buf = lines.pop() ?? "";
for (const line of lines) {
if (line.startsWith("data: ")) {
const raw = line.slice(6).trim();
if (raw && raw !== "[DONE]") process.stdout.write(raw + "\n");
}
}
}
});
tasks
.command("logs <id>")
.description(t("a2a.tasks.logs.description"))
.action(async (id, opts, cmd) => {
const res = await apiFetch(`/api/a2a/tasks/${id}?include=messages,artifacts`);
if (!res.ok) {
process.stderr.write(`Not found: ${id}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.messages ?? data, cmd.optsWithGlobals());
});
}
export async function runA2aStatusCommand(opts = {}) {
const serverUp = await isServerUp();
if (!serverUp) {
console.error(t("common.serverOffline"));
return 1;
}
try {
const res = await apiFetch("/api/a2a/status", {
retry: false,
timeout: 5000,
acceptNotOk: true,
});
if (!res.ok) {
console.log("A2A status not available.");
return 0;
}
const status = await res.json();
if (opts.json || opts.output === "json") {
console.log(JSON.stringify(status, null, 2));
return 0;
}
const running = status.running ? "\x1b[32mrunning\x1b[0m" : "\x1b[31mstopped\x1b[0m";
console.log(` Status: ${running}`);
console.log(` Protocol: ${status.protocol || "JSON-RPC 2.0"}`);
console.log(` Tasks: ${status.activeTasks || 0} active`);
if (status.skills?.length) {
console.log("\n Skills:");
for (const skill of status.skills) {
console.log(`\x1b[2m - ${skill.name}: ${skill.description || "N/A"}\x1b[0m`);
}
}
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runA2aCardCommand(opts = {}) {
const serverUp = await isServerUp();
if (!serverUp) {
console.error(t("common.serverOffline"));
return 1;
}
try {
const res = await apiFetch("/.well-known/agent.json", {
retry: false,
timeout: 5000,
acceptNotOk: true,
});
if (res.ok) {
const card = await res.json();
console.log(JSON.stringify(card, null, 2));
return 0;
}
console.log("Agent card not available.");
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}

203
bin/cli/commands/audit.mjs Normal file
View File

@@ -0,0 +1,203 @@
import { writeFileSync } from "node:fs";
import { setTimeout as sleep } from "node:timers/promises";
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
function truncate(v, len = 40) {
if (v == null) return "-";
const s = String(v);
return s.length > len ? s.slice(0, len - 1) + "…" : s;
}
function fmtTs(v) {
if (!v) return "-";
try {
return new Date(v).toLocaleString();
} catch {
return String(v);
}
}
function maskActor(v) {
if (!v) return "-";
const s = String(v);
if (s.length <= 8) return s;
return `${s.slice(0, 4)}****${s.slice(-4)}`;
}
const auditSchema = [
{ key: "timestamp", header: "Time", width: 22, formatter: fmtTs },
{ key: "source", header: "Source", width: 10 },
{ key: "actor", header: "Actor", width: 16, formatter: maskActor },
{ key: "action", header: "Action", width: 28 },
{ key: "resource", header: "Resource", width: 32, formatter: truncate },
{ key: "result", header: "Result", formatter: (v) => (v === "success" ? "✓" : "✗") },
{ key: "details", header: "Details", formatter: truncate },
];
function endpointFor(source) {
return source === "mcp" ? "/api/mcp/audit" : "/api/compliance/audit-log";
}
async function fetchAuditEntries(sources, params) {
const entries = [];
for (const src of sources) {
const endpoint = endpointFor(src);
const res = await apiFetch(`${endpoint}?${params}`);
if (!res.ok) continue;
const data = await res.json();
for (const e of data.items ?? data) {
entries.push({ ...e, source: src });
}
}
return entries;
}
function resolveSources(source) {
if (source === "all") return ["compliance", "mcp"];
return [source ?? "compliance"];
}
export async function runAuditTail(opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const sources = resolveSources(opts.source);
const params = new URLSearchParams({ limit: String(opts.limit ?? 100) });
const entries = await fetchAuditEntries(sources, params);
entries.sort((a, b) => String(b.timestamp ?? "").localeCompare(String(a.timestamp ?? "")));
emit(entries.slice(0, opts.limit ?? 100), globalOpts, auditSchema);
if (opts.follow) {
process.stderr.write("\n[following — Ctrl+C to exit]\n");
let lastTs = entries[0]?.timestamp ?? new Date().toISOString();
const loop = async () => {
while (true) {
await sleep(2000);
for (const src of sources) {
const endpoint = endpointFor(src);
const res = await apiFetch(`${endpoint}?since=${encodeURIComponent(lastTs)}&limit=50`);
if (!res.ok) continue;
const data = await res.json();
const newEntries = (data.items ?? data)
.map((e) => ({ ...e, source: src }))
.filter((e) => String(e.timestamp ?? "") > String(lastTs));
for (const e of newEntries) {
if (String(e.timestamp ?? "") > String(lastTs)) lastTs = e.timestamp;
emit([e], globalOpts, auditSchema);
}
}
}
};
process.on("SIGINT", () => process.exit(0));
await loop();
}
}
export async function runAuditSearch(query, opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const sources = resolveSources(opts.source);
const params = new URLSearchParams({ q: query, limit: String(opts.limit ?? 200) });
if (opts.since) params.set("since", opts.since);
if (opts.until) params.set("until", opts.until);
if (opts.actor) params.set("actor", opts.actor);
if (opts.action) params.set("action", opts.action);
const entries = await fetchAuditEntries(sources, params);
entries.sort((a, b) => String(b.timestamp ?? "").localeCompare(String(a.timestamp ?? "")));
emit(entries, globalOpts, auditSchema);
}
export async function runAuditExport(file, opts, cmd) {
const sources = resolveSources(opts.source === "all" ? "compliance" : opts.source);
const format = opts.format ?? "jsonl";
const params = new URLSearchParams({ format });
if (opts.since) params.set("since", opts.since);
if (opts.until) params.set("until", opts.until);
const allLines = [];
for (const src of sources) {
const endpoint = endpointFor(src);
const res = await apiFetch(`${endpoint}?${params}`);
if (!res.ok) {
process.stderr.write(`Error fetching ${src}: ${res.status}\n`);
continue;
}
const body = await res.text();
allLines.push(body);
}
const combined = allLines.join("\n");
writeFileSync(file, combined);
process.stdout.write(`Exported to ${file} (${combined.length} bytes)\n`);
}
export async function runAuditStats(opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const source = opts.source ?? "mcp";
const params = new URLSearchParams({ period: opts.period ?? "7d" });
const endpoint = source === "mcp" ? "/api/mcp/audit/stats" : "/api/compliance/audit-log/stats";
const res = await apiFetch(`${endpoint}?${params}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data, globalOpts);
}
export async function runAuditGet(id, opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const source = opts.source ?? "compliance";
const endpoint = endpointFor(source);
const res = await apiFetch(`${endpoint}/${id}`);
if (!res.ok) {
process.stderr.write(`Not found: ${id}\n`);
process.exit(1);
}
const data = await res.json();
emit(data, globalOpts, auditSchema);
}
export function registerAudit(program) {
const audit = program.command("audit").description(t("audit.description"));
audit
.command("tail")
.description(t("audit.tail.description"))
.option("--source <s>", t("audit.source"), "all")
.option("--follow", t("audit.tail.follow"))
.option("--limit <n>", t("audit.tail.limit"), parseInt, 100)
.action(runAuditTail);
audit
.command("search <query>")
.description(t("audit.search.description"))
.option("--source <s>", t("audit.source"), "all")
.option("--since <ts>", t("audit.since"))
.option("--until <ts>", t("audit.until"))
.option("--limit <n>", t("audit.search.limit"), parseInt, 200)
.option("--actor <id>", t("audit.search.actor"))
.option("--action <a>", t("audit.search.action"))
.action(runAuditSearch);
audit
.command("export <file>")
.description(t("audit.export.description"))
.option("--source <s>", t("audit.source"), "all")
.option("--format <f>", t("audit.export.format"), "jsonl")
.option("--since <ts>", t("audit.since"))
.option("--until <ts>", t("audit.until"))
.action(runAuditExport);
audit
.command("stats")
.description(t("audit.stats.description"))
.option("--source <s>", t("audit.source"), "mcp")
.option("--period <p>", t("audit.stats.period"), "7d")
.action(runAuditStats);
audit
.command("get <id>")
.description(t("audit.get.description"))
.option("--source <s>", t("audit.source"), "compliance")
.action(runAuditGet);
}

View File

@@ -0,0 +1,39 @@
import { t } from "../i18n.mjs";
import { emit } from "../output.mjs";
export function registerAutostart(program) {
const cmd = program
.command("autostart")
.description(t("autostart.description") || "Manage OmniRoute autostart at login");
cmd
.command("enable")
.description(t("autostart.enable") || "Enable autostart at login")
.action(async (opts, c) => {
const globalOpts = c.optsWithGlobals();
const { enable } = await import("../tray/autostart.mjs");
const ok = enable();
emit({ enabled: ok }, globalOpts);
if (!ok) process.exit(1);
});
cmd
.command("disable")
.description(t("autostart.disable") || "Disable autostart at login")
.action(async (opts, c) => {
const globalOpts = c.optsWithGlobals();
const { disable } = await import("../tray/autostart.mjs");
const ok = disable();
emit({ disabled: ok }, globalOpts);
if (!ok) process.exit(1);
});
cmd
.command("status")
.description(t("autostart.status") || "Show autostart status")
.action(async (opts, c) => {
const globalOpts = c.optsWithGlobals();
const { isAutostartEnabled } = await import("../tray/autostart.mjs");
emit({ enabled: isAutostartEnabled() }, globalOpts);
});
}

431
bin/cli/commands/backup.mjs Normal file
View File

@@ -0,0 +1,431 @@
import {
copyFileSync,
existsSync,
mkdirSync,
readdirSync,
readFileSync,
writeFileSync,
} from "node:fs";
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto";
import { dirname, join, extname, basename } from "node:path";
import { resolveDataDir } from "../data-dir.mjs";
import { apiFetch, isServerUp } from "../api.mjs";
import { t } from "../i18n.mjs";
function getBackupDir() {
return join(resolveDataDir(), "backups");
}
const FILES_TO_BACKUP = [
{ name: "storage.sqlite" },
{ name: "settings.json" },
{ name: "combos.json" },
{ name: "providers.json" },
];
export function registerBackup(program) {
const backup = program.command("backup").description(t("backup.description"));
backup
.command("create")
.description(t("backup.createDescription"))
.option("--name <name>", t("backup.nameOpt"))
.option("--cloud", t("backup.cloudOpt"))
.option("--encrypt", t("backup.encryptOpt"))
.option("--key-file <path>", t("backup.keyFileOpt"))
.option("--exclude <pattern>", t("backup.excludeOpt"), (v, prev = []) => [...prev, v], [])
.option("--retention <n>", t("backup.retentionOpt"), parseInt)
.action(async (opts) => {
const exitCode = await runBackupCommand(opts);
if (exitCode !== 0) process.exit(exitCode);
});
const auto = backup.command("auto").description(t("backup.auto.title"));
auto
.command("enable")
.description(t("backup.auto.enableDescription"))
.option("--cron <expr>", t("backup.auto.cronOpt"), "0 3 * * *")
.option("--cloud", t("backup.cloudOpt"))
.option("--encrypt", t("backup.encryptOpt"))
.option("--retention <n>", t("backup.retentionOpt"), parseInt)
.action(async (opts) => {
const exitCode = await runBackupAutoEnableCommand(opts);
if (exitCode !== 0) process.exit(exitCode);
});
auto
.command("disable")
.description(t("backup.auto.disableDescription"))
.action(async () => {
const exitCode = await runBackupAutoDisableCommand();
if (exitCode !== 0) process.exit(exitCode);
});
auto
.command("status")
.description(t("backup.auto.statusDescription"))
.action(async () => {
const exitCode = await runBackupAutoStatusCommand();
if (exitCode !== 0) process.exit(exitCode);
});
// Legacy: `omniroute backup` without subcommand still creates a backup
backup.action(async (opts) => {
const exitCode = await runBackupCommand(opts);
if (exitCode !== 0) process.exit(exitCode);
});
backup
.option("--name <name>", t("backup.nameOpt"))
.option("--cloud", t("backup.cloudOpt"))
.option("--encrypt", t("backup.encryptOpt"))
.option("--key-file <path>", t("backup.keyFileOpt"))
.option("--exclude <pattern>", t("backup.excludeOpt"), (v, prev = []) => [...prev, v], [])
.option("--retention <n>", t("backup.retentionOpt"), parseInt);
}
export function registerRestore(program) {
program
.command("restore [backupId]")
.description(t("backup.restoreDescription"))
.option("--list", "List available backups")
.option("--yes", "Skip confirmation")
.action(async (backupId, opts) => {
const exitCode = await runRestoreCommand(backupId, opts);
if (exitCode !== 0) process.exit(exitCode);
});
}
function matchesGlob(fileName, pattern) {
if (!pattern.includes("*")) return fileName === pattern;
const parts = pattern.split("*");
let pos = 0;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (!part) continue;
if (i === 0) {
if (!fileName.startsWith(part)) return false;
pos = part.length;
} else if (i === parts.length - 1) {
if (!fileName.endsWith(part)) return false;
if (fileName.length < pos + part.length) return false;
} else {
const idx = fileName.indexOf(part, pos);
if (idx === -1) return false;
pos = idx + part.length;
}
}
return true;
}
function shouldExclude(fileName, patterns) {
if (!patterns || patterns.length === 0) return false;
return patterns.some((p) => matchesGlob(fileName, p));
}
function encryptFile(srcPath, destPath, passphrase) {
const salt = randomBytes(16);
const iv = randomBytes(12);
const key = scryptSync(passphrase, salt, 32);
const cipher = createCipheriv("aes-256-gcm", key, iv);
const plaintext = readFileSync(srcPath);
const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const authTag = cipher.getAuthTag();
// Format: salt(16) + iv(12) + authTag(16) + ciphertext
writeFileSync(destPath, Buffer.concat([salt, iv, authTag, encrypted]));
}
async function promptPassphrase() {
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
return new Promise((resolve) =>
rl.question(t("backup.passphrasePrompt"), (ans) => {
rl.close();
resolve(ans.trim());
})
);
}
async function pruneBackups(backupDir, retention) {
if (!retention || retention <= 0 || !existsSync(backupDir)) return;
try {
const dirs = readdirSync(backupDir)
.filter((f) => f.startsWith("omniroute-backup-"))
.sort()
.reverse();
for (const old of dirs.slice(retention)) {
const { rmSync } = await import("node:fs");
rmSync(join(backupDir, old), { recursive: true, force: true });
}
} catch {}
}
export async function runBackupCommand(opts = {}) {
const dataDir = resolveDataDir();
const backupDir = getBackupDir();
const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
const safeName = opts.name ? String(opts.name).replace(/[/\\]/g, "_") : null;
const backupName = safeName ? `omniroute-backup-${safeName}` : `omniroute-backup-${timestamp}`;
const backupPath = join(backupDir, backupName);
const excludePatterns = opts.exclude || [];
console.log(t("backup.creating"));
let passphrase = null;
if (opts.encrypt) {
if (opts.keyFile) {
passphrase = readFileSync(opts.keyFile, "utf8").trim();
} else {
passphrase = await promptPassphrase();
if (!passphrase) {
console.error(t("backup.noPassphrase"));
return 1;
}
}
}
try {
if (!existsSync(backupDir)) mkdirSync(backupDir, { recursive: true });
let Database;
try {
Database = (await import("better-sqlite3")).default;
} catch {
Database = null;
}
let backedUp = 0;
let skipped = 0;
for (const file of FILES_TO_BACKUP) {
if (shouldExclude(file.name, excludePatterns)) {
skipped++;
continue;
}
const sourcePath = join(dataDir, file.name);
if (existsSync(sourcePath)) {
const destName = opts.encrypt ? `${file.name}.enc` : file.name;
const destPath = join(backupPath, destName);
mkdirSync(dirname(destPath), { recursive: true });
if (file.name.endsWith(".sqlite") && Database) {
const db = new Database(sourcePath, { readonly: true });
const tmpPath = destPath.replace(/\.enc$/, "");
await db.backup(tmpPath);
db.close();
if (opts.encrypt) {
encryptFile(tmpPath, destPath, passphrase);
const { unlinkSync } = await import("node:fs");
unlinkSync(tmpPath);
}
} else if (opts.encrypt) {
encryptFile(sourcePath, destPath, passphrase);
} else {
copyFileSync(sourcePath, destPath);
}
backedUp++;
} else {
skipped++;
}
}
if (backedUp > 0) {
const info = {
timestamp: new Date().toISOString(),
version: "omniroute-cli-v1",
encrypted: !!opts.encrypt,
files: FILES_TO_BACKUP.filter(
(f) => existsSync(join(dataDir, f.name)) && !shouldExclude(f.name, excludePatterns)
).map((f) => (opts.encrypt ? `${f.name}.enc` : f.name)),
};
writeFileSync(join(backupPath, "backup-info.json"), JSON.stringify(info, null, 2), "utf8");
if (opts.cloud) {
const cloudCode = await _uploadBackupToCloud(backupPath, info);
if (cloudCode !== 0) {
console.warn(t("backup.cloudFailed"));
}
}
if (opts.retention) {
await pruneBackups(backupDir, opts.retention);
}
console.log(t("backup.done", { path: backupPath }));
console.log(
`\x1b[2m ${backedUp} backed up, ${skipped} skipped${opts.encrypt ? " (encrypted)" : ""}\x1b[0m`
);
return 0;
}
console.log(t("backup.noFiles"));
return 0;
} catch (err) {
console.error(t("backup.failed", { error: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
async function _uploadBackupToCloud(backupPath, info) {
const serverUp = await isServerUp();
if (!serverUp) {
console.warn(t("common.serverOffline"));
return 1;
}
try {
// Read files locally and send as base64 — never send local path to server
const files = {};
for (const fname of readdirSync(backupPath)) {
files[fname] = readFileSync(join(backupPath, fname)).toString("base64");
}
const res = await apiFetch("/api/db-backups/cloud", {
method: "POST",
body: { files, info },
retry: false,
timeout: 30000,
acceptNotOk: true,
});
if (res.ok) {
const data = await res.json();
console.log(t("backup.cloudUploaded", { url: data.url || "(stored)" }));
return 0;
}
return 1;
} catch {
return 1;
}
}
function getSchedulePath() {
return join(resolveDataDir(), "backup-schedule.json");
}
export async function runBackupAutoEnableCommand(opts = {}) {
const schedulePath = getSchedulePath();
const schedule = {
enabled: true,
cron: opts.cron || "0 3 * * *",
cloud: !!opts.cloud,
encrypt: !!opts.encrypt,
retention: opts.retention || null,
updatedAt: new Date().toISOString(),
};
mkdirSync(dirname(schedulePath), { recursive: true });
writeFileSync(schedulePath, JSON.stringify(schedule, null, 2), "utf8");
console.log(t("backup.auto.enabled", { cron: schedule.cron }));
console.log(t("backup.auto.hint"));
return 0;
}
export async function runBackupAutoDisableCommand() {
const schedulePath = getSchedulePath();
if (existsSync(schedulePath)) {
const schedule = JSON.parse(readFileSync(schedulePath, "utf8"));
schedule.enabled = false;
schedule.updatedAt = new Date().toISOString();
writeFileSync(schedulePath, JSON.stringify(schedule, null, 2), "utf8");
}
console.log(t("backup.auto.disabled"));
return 0;
}
export async function runBackupAutoStatusCommand() {
const schedulePath = getSchedulePath();
if (!existsSync(schedulePath)) {
console.log(t("backup.auto.notConfigured"));
return 0;
}
const schedule = JSON.parse(readFileSync(schedulePath, "utf8"));
const statusLabel = schedule.enabled ? "\x1b[32m● enabled\x1b[0m" : "\x1b[31m○ disabled\x1b[0m";
console.log(`${t("backup.auto.title")}: ${statusLabel}`);
console.log(` cron: ${schedule.cron}`);
console.log(` cloud: ${schedule.cloud ? "yes" : "no"}`);
console.log(` encrypt: ${schedule.encrypt ? "yes" : "no"}`);
console.log(` retention: ${schedule.retention ?? "unlimited"}`);
return 0;
}
export async function runRestoreCommand(backupId, opts = {}) {
const backupDir = getBackupDir();
if (opts.list || !backupId) {
console.log(`\n\x1b[1m\x1b[36m${t("backup.listTitle")}\x1b[0m\n`);
if (!existsSync(backupDir)) {
console.log(t("backup.noBackups"));
return 0;
}
try {
const dirs = readdirSync(backupDir)
.filter((f) => f.startsWith("omniroute-backup-"))
.sort()
.reverse();
if (dirs.length === 0) {
console.log(t("backup.noBackups"));
return 0;
}
for (const dir of dirs) {
const infoPath = join(backupDir, dir, "backup-info.json");
if (existsSync(infoPath)) {
const info = JSON.parse(readFileSync(infoPath, "utf8"));
const id = dir.replace("omniroute-backup-", "");
const dateStr = new Date(info.timestamp).toLocaleString();
console.log(` ${id}`);
console.log(`\x1b[2m ${dateStr}${info.files?.length || 0} files\x1b[0m`);
} else {
console.log(`\x1b[2m ${dir.replace("omniroute-backup-", "")}\x1b[0m`);
}
}
} catch (err) {
console.error(
t("common.error", { message: err instanceof Error ? err.message : String(err) })
);
return 1;
}
if (!backupId) console.log("\nUsage: omniroute restore <backup-id>");
return 0;
}
const safeBackupId = String(backupId).replace(/[/\\]/g, "_");
const backupPath = join(backupDir, `omniroute-backup-${safeBackupId}`);
if (!existsSync(backupPath)) {
console.error(t("backup.notFound", { name: backupId }));
return 1;
}
const infoPath = join(backupPath, "backup-info.json");
const ts = existsSync(infoPath) ? JSON.parse(readFileSync(infoPath, "utf8")).timestamp : backupId;
if (!opts.yes) {
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((resolve) =>
rl.question(t("backup.confirmRestore", { ts }) + " [y/N] ", resolve)
);
rl.close();
if (!/^y(es)?$/i.test(answer)) {
console.log(t("common.cancelled"));
return 0;
}
}
console.log(t("backup.restoring", { path: backupPath }));
const dataDir = resolveDataDir();
try {
for (const file of FILES_TO_BACKUP) {
const sourcePath = join(backupPath, file.name);
if (existsSync(sourcePath)) {
copyFileSync(sourcePath, join(dataDir, file.name));
console.log(`\x1b[2m Restored: ${file.name}\x1b[0m`);
}
}
console.log(t("backup.restored"));
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}

View File

@@ -0,0 +1,235 @@
import { readFileSync, writeFileSync } from "node:fs";
import { createInterface } from "node:readline";
import { setTimeout as sleep } from "node:timers/promises";
import { apiFetch, getBaseUrl } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
function fmtTs(v) {
if (!v) return "-";
return new Date(typeof v === "number" ? v * 1000 : v).toLocaleString();
}
async function confirm(q) {
const rl = createInterface({ input: process.stdin, output: process.stdout });
return new Promise((resolve) => {
rl.question(`${q} [y/N] `, (a) => {
rl.close();
resolve(a.trim().toLowerCase() === "y");
});
});
}
function authHeaders(opts) {
const h = { accept: "application/json" };
if (opts.apiKey) h["Authorization"] = `Bearer ${opts.apiKey}`;
return h;
}
const batchSchema = [
{ key: "id", header: "Batch ID", width: 28 },
{ key: "status", header: "Status", width: 14 },
{ key: "endpoint", header: "Endpoint", width: 26 },
{
key: "request_counts",
header: "Total",
formatter: (v) => (v?.completed != null ? `${v.completed}/${v.total}` : "-"),
},
{ key: "created_at", header: "Created", formatter: fmtTs },
];
async function uploadFile(filePath, purpose) {
const { fmtBytes } = await import("./files.mjs");
const { statSync, readFileSync: readF } = await import("node:fs");
const { basename } = await import("node:path");
const stat = statSync(filePath);
if (stat.size > 100 * 1024 * 1024) {
process.stderr.write(`Warning: file is ${fmtBytes(stat.size)} (large)\n`);
}
const form = new FormData();
form.append("purpose", purpose);
form.append("file", new Blob([readF(filePath)]), basename(filePath));
const res = await apiFetch("/v1/files", { method: "POST", body: form });
if (!res.ok) {
process.stderr.write(`Upload failed: ${res.status}\n`);
process.exit(1);
}
return res.json();
}
async function fetchFile(fileId, globalOpts = {}) {
const res = await fetch(`${getBaseUrl(globalOpts)}/v1/files/${fileId}/content`, {
headers: authHeaders(globalOpts),
});
if (!res.ok) {
process.stderr.write(`Error fetching file: ${res.status}\n`);
process.exit(1);
}
return res.text();
}
async function waitBatch(id, opts, timeout = 3600000) {
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
const res = await apiFetch(`/v1/batches/${id}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const b = await res.json();
const done = b.request_counts?.completed ?? 0;
const total = b.request_counts?.total ?? "?";
process.stderr.write(`[${b.status}] ${done}/${total}\n`);
if (["completed", "failed", "expired", "cancelled"].includes(b.status)) {
emit(b, opts);
return;
}
await sleep(5000);
}
process.stderr.write("Timeout\n");
process.exit(124);
}
export function registerBatches(program) {
const batches = program.command("batches").description(t("batches.description"));
batches
.command("list")
.option("--status <s>", t("batches.list.status"))
.option("--limit <n>", t("batches.list.limit"), parseInt, 50)
.action(async (opts, cmd) => {
const params = new URLSearchParams({ limit: String(opts.limit) });
if (opts.status) params.set("status", opts.status);
const res = await apiFetch(`/v1/batches?${params}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.data ?? data.items ?? data, cmd.optsWithGlobals(), batchSchema);
});
batches.command("get <batchId>").action(async (id, opts, cmd) => {
const res = await apiFetch(`/v1/batches/${id}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
batches
.command("create")
.description(t("batches.create.description"))
.requiredOption("--input-file <fileId>", t("batches.create.inputFile"))
.option("--endpoint <e>", t("batches.create.endpoint"), "/v1/chat/completions")
.option("--completion-window <w>", t("batches.create.window"), "24h")
.option(
"--metadata <kv>",
t("batches.create.metadata"),
(v, prev = {}) => {
const eq = v.indexOf("=");
if (eq < 0) return prev;
const k = v.slice(0, eq);
const val = v.slice(eq + 1);
return { ...prev, [k]: val };
},
{}
)
.action(async (opts, cmd) => {
const body = {
input_file_id: opts.inputFile,
endpoint: opts.endpoint,
completion_window: opts.completionWindow,
metadata: Object.keys(opts.metadata).length ? opts.metadata : undefined,
};
const res = await apiFetch("/v1/batches", { method: "POST", body });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
batches
.command("submit")
.description(t("batches.submit.description"))
.requiredOption("--jsonl <path>", t("batches.submit.jsonl"))
.option("--endpoint <e>", t("batches.submit.endpoint"), "/v1/chat/completions")
.option("--wait", t("batches.submit.wait"))
.action(async (opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const upload = await uploadFile(opts.jsonl, "batch");
const res = await apiFetch("/v1/batches", {
method: "POST",
body: { input_file_id: upload.id, endpoint: opts.endpoint, completion_window: "24h" },
});
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const batch = await res.json();
emit(batch, globalOpts);
if (opts.wait) await waitBatch(batch.id, globalOpts);
});
batches
.command("cancel <batchId>")
.option("--yes", t("batches.cancel.yes"))
.action(async (id, opts, cmd) => {
if (!opts.yes) {
const ok = await confirm(`Cancel batch ${id}?`);
if (!ok) return;
}
const res = await apiFetch(`/v1/batches/${id}/cancel`, { method: "POST" });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
process.stdout.write("Cancelled\n");
});
batches
.command("wait <batchId>")
.option("--timeout <ms>", t("batches.wait.timeout"), parseInt, 3600000)
.action(async (id, opts, cmd) => waitBatch(id, cmd.optsWithGlobals(), opts.timeout));
batches
.command("output <batchId>")
.option("--out <path>", t("batches.output.out"), "batch-output.jsonl")
.action(async (id, opts, cmd) => {
const res = await apiFetch(`/v1/batches/${id}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const batch = await res.json();
if (!batch.output_file_id) {
process.stderr.write("Not yet completed\n");
process.exit(1);
}
const content = await fetchFile(batch.output_file_id, cmd.optsWithGlobals());
writeFileSync(opts.out, content);
process.stdout.write(`Saved to ${opts.out}\n`);
});
batches
.command("errors <batchId>")
.option("--out <path>", t("batches.errors.out"), "batch-errors.jsonl")
.action(async (id, opts, cmd) => {
const res = await apiFetch(`/v1/batches/${id}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const batch = await res.json();
if (!batch.error_file_id) {
process.stdout.write("No errors\n");
return;
}
const content = await fetchFile(batch.error_file_id, cmd.optsWithGlobals());
writeFileSync(opts.out, content);
process.stdout.write(`Saved to ${opts.out}\n`);
});
}

102
bin/cli/commands/cache.mjs Normal file
View File

@@ -0,0 +1,102 @@
import { apiFetch, isServerUp } from "../api.mjs";
import { t } from "../i18n.mjs";
export function registerCache(program) {
const cache = program.command("cache").description(t("cache.description"));
cache
.command("status")
.alias("stats")
.description("Show cache statistics")
.option("--json", "Output as JSON")
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runCacheStatusCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
cache
.command("clear")
.description("Clear all cached responses")
.option("--yes", "Skip confirmation")
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runCacheClearCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
}
export async function runCacheStatusCommand(opts = {}) {
const serverUp = await isServerUp();
if (!serverUp) {
console.error(t("cache.noServer"));
return 1;
}
try {
const res = await apiFetch("/api/cache/stats", {
retry: false,
timeout: 5000,
acceptNotOk: true,
});
if (!res.ok) {
console.log("Cache stats not available.");
return 0;
}
const stats = await res.json();
if (opts.json || opts.output === "json") {
console.log(JSON.stringify(stats, null, 2));
return 0;
}
console.log(`\n\x1b[1m\x1b[36mCache Status\x1b[0m\n`);
console.log(` Semantic hits: ${stats.semanticHits || 0}`);
console.log(` Signature hits: ${stats.signatureHits || 0}`);
if (stats.size !== undefined) console.log(` Size: ${stats.size}`);
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runCacheClearCommand(opts = {}) {
const serverUp = await isServerUp();
if (!serverUp) {
console.error(t("cache.noServer"));
return 1;
}
if (!opts.yes) {
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((resolve) =>
rl.question("Clear all cached responses? [y/N] ", resolve)
);
rl.close();
if (!/^y(es)?$/i.test(answer)) {
console.log(t("common.cancelled"));
return 0;
}
}
try {
const res = await apiFetch("/api/cache/clear", {
method: "POST",
retry: false,
timeout: 5000,
acceptNotOk: true,
});
if (res.ok) {
console.log(t("cache.cleared"));
return 0;
}
console.error(t("cache.clearFailed"));
return 1;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}

162
bin/cli/commands/chat.mjs Normal file
View File

@@ -0,0 +1,162 @@
import { appendFileSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
import { resolveDataDir } from "../data-dir.mjs";
function resolveHistoryPath() {
return join(resolveDataDir(), "cli-history.jsonl");
}
export function registerChat(program) {
program
.command("chat [prompt]")
.description(t("chat.description"))
.option("--file <path>", t("chat.file"))
.option("--stdin", t("chat.stdin"))
.option("-s, --system <prompt>", t("chat.system"))
.option("-m, --model <id>", t("chat.model"), "auto")
.option("--max-tokens <n>", t("chat.max_tokens"), parseInt)
.option("--temperature <t>", t("chat.temperature"), parseFloat)
.option("--top-p <p>", t("chat.top_p"), parseFloat)
.option("--reasoning-effort <level>", t("chat.reasoning_effort"))
.option("--thinking-budget <tokens>", t("chat.thinking_budget"), parseInt)
.option("--combo <name>", t("chat.combo"))
.option("--responses-api", t("chat.responses_api"))
.option("--stream", t("chat.stream"))
.option("--no-history", t("chat.no_history"))
.action(runChatCommand);
}
export async function runChatCommand(promptArg, opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const prompt = await resolvePrompt(promptArg, opts);
if (!prompt) {
process.stderr.write(t("chat.error.empty_prompt") + "\n");
process.exit(2);
}
const messages = [];
if (opts.system) messages.push({ role: "system", content: opts.system });
messages.push({ role: "user", content: prompt });
const body = {
model: opts.model,
messages,
...(opts.maxTokens && { max_tokens: opts.maxTokens }),
...(opts.temperature != null && { temperature: opts.temperature }),
...(opts.topP != null && { top_p: opts.topP }),
...(opts.reasoningEffort && { reasoning_effort: opts.reasoningEffort }),
...(opts.thinkingBudget && { thinking: { budget_tokens: opts.thinkingBudget } }),
...(opts.combo && { combo: opts.combo }),
stream: !!opts.stream,
};
const endpoint = opts.responsesApi ? "/v1/responses" : "/v1/chat/completions";
const startedAt = Date.now();
const response = await apiFetch(endpoint, {
method: "POST",
body,
acceptNotOk: true,
timeout: globalOpts.timeout,
});
if (!response.ok) {
const errText = await response.text().catch(() => "");
process.stderr.write(`\x1b[31m✖ ${response.status} ${response.statusText}\x1b[0m\n`);
if (errText) process.stderr.write(errText + "\n");
process.exit(1);
}
const latencyMs = Date.now() - startedAt;
if (opts.stream) {
return streamHandle(response, opts.responsesApi);
}
const data = await response.json();
const text = extractText(data, opts.responsesApi);
if (!opts.noHistory) {
appendHistory({ prompt, model: opts.model, latencyMs, usage: data.usage, response: text });
}
if (globalOpts.output === "json") {
emit(data, globalOpts);
} else if (globalOpts.output === "markdown") {
console.log(
`# Response\n\n${text}\n\n## Metadata\n- Model: ${data.model}\n- Latency: ${latencyMs}ms\n- Usage: ${JSON.stringify(data.usage)}\n`
);
} else {
console.log(text);
if (!globalOpts.quiet) {
process.stderr.write(
`\n[${data.model} · ${latencyMs}ms · ${data.usage?.total_tokens ?? "?"} tok]\n`
);
}
}
}
async function resolvePrompt(arg, opts) {
if (opts.file) return readFileSync(opts.file, "utf8").trim();
if (opts.stdin) return readStdin();
return arg?.trim() || "";
}
function readStdin() {
return new Promise((resolve) => {
let buf = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (c) => (buf += c));
process.stdin.on("end", () => resolve(buf.trim()));
});
}
function extractText(data, isResponses) {
if (isResponses) {
return data.output?.[0]?.content?.[0]?.text ?? data.output_text ?? "";
}
return data.choices?.[0]?.message?.content ?? "";
}
async function streamHandle(response, isResponses) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const chunk = line.slice(6).trim();
if (chunk === "[DONE]") {
process.stdout.write("\n");
return;
}
try {
const obj = JSON.parse(chunk);
const content = isResponses ? obj.delta?.content : obj.choices?.[0]?.delta?.content;
if (content) process.stdout.write(content);
} catch {}
}
}
process.stdout.write("\n");
}
function appendHistory(entry) {
try {
appendFileSync(
resolveHistoryPath(),
JSON.stringify({ ts: new Date().toISOString(), ...entry }) + "\n"
);
} catch {
// history write failures are non-fatal
}
}

233
bin/cli/commands/cloud.mjs Normal file
View File

@@ -0,0 +1,233 @@
import { readFileSync } from "node:fs";
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
const AGENTS = ["codex", "devin", "jules"];
function truncate(v, len = 35) {
if (v == null) return "-";
const s = String(v);
return s.length > len ? s.slice(0, len - 1) + "…" : s;
}
function fmtTs(v) {
if (!v) return "-";
try {
return new Date(v).toLocaleString();
} catch {
return String(v);
}
}
function fmtStatus(v) {
if (!v) return "-";
const colors = {
running: "\x1b[33m",
completed: "\x1b[32m",
failed: "\x1b[31m",
cancelled: "\x1b[90m",
};
const c = colors[v] ?? "";
return `${c}${v}\x1b[0m`;
}
const taskSchema = [
{ key: "id", header: "Task ID", width: 22 },
{ key: "agent", header: "Agent", width: 8 },
{ key: "status", header: "Status", width: 14, formatter: fmtStatus },
{ key: "title", header: "Title", width: 35, formatter: truncate },
{ key: "createdAt", header: "Created", formatter: fmtTs },
{ key: "updatedAt", header: "Updated", formatter: fmtTs },
];
async function confirm(q) {
return new Promise((resolve) => {
process.stdout.write(`${q} (yes/no) `);
process.stdin.setEncoding("utf8");
process.stdin.once("data", (c) => resolve(c.toString().trim().toLowerCase().startsWith("y")));
});
}
function registerTaskCommands(parent, agent) {
const task = parent.command("task").description(t("cloud.task.description"));
task
.command("create")
.description(t("cloud.task.create.description"))
.option("--title <t>", t("cloud.task.create.title"))
.option("--prompt <p>", t("cloud.task.create.prompt"))
.option("--prompt-file <path>", t("cloud.task.create.prompt_file"))
.option("--repo <url>", t("cloud.task.create.repo"))
.option("--branch <b>", t("cloud.task.create.branch"))
.option("--metadata <json>", t("cloud.task.create.metadata"))
.action(async (opts, cmd) => {
const prompt =
opts.prompt ?? (opts.promptFile ? readFileSync(opts.promptFile, "utf8") : null);
if (!prompt) {
process.stderr.write("--prompt or --prompt-file required\n");
process.exit(2);
}
const body = {
agent,
title: opts.title ?? prompt.slice(0, 80),
prompt,
...(opts.repo ? { repo: opts.repo } : {}),
...(opts.branch ? { branch: opts.branch } : {}),
...(opts.metadata ? { metadata: JSON.parse(opts.metadata) } : {}),
};
const res = await apiFetch("/api/v1/agents/tasks", { method: "POST", body });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
task
.command("list")
.description(t("cloud.task.list.description"))
.option("--status <s>", t("cloud.task.list.status"))
.option("--limit <n>", t("cloud.task.list.limit"), parseInt, 50)
.action(async (opts, cmd) => {
const params = new URLSearchParams({ agent, limit: String(opts.limit ?? 50) });
if (opts.status) params.set("status", opts.status);
const res = await apiFetch(`/api/v1/agents/tasks?${params}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.items ?? data, cmd.optsWithGlobals(), taskSchema);
});
task
.command("get <taskId>")
.description(t("cloud.task.get.description"))
.action(async (taskId, opts, cmd) => {
const res = await apiFetch(`/api/v1/agents/tasks/${taskId}`);
if (!res.ok) {
process.stderr.write(`Not found: ${taskId}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
task
.command("status <taskId>")
.description(t("cloud.task.status.description"))
.action(async (taskId, opts, cmd) => {
const res = await apiFetch(`/api/v1/agents/tasks/${taskId}`);
if (!res.ok) {
process.stderr.write(`Not found: ${taskId}\n`);
process.exit(1);
}
const data = await res.json();
const globalOpts = cmd.optsWithGlobals();
if (globalOpts.output === "json") {
emit({ status: data.status }, globalOpts);
} else {
process.stdout.write(`${data.status}\n`);
}
});
task
.command("cancel <taskId>")
.description(t("cloud.task.cancel.description"))
.option("--yes", t("cloud.task.cancel.yes"))
.action(async (taskId, opts, cmd) => {
if (!opts.yes) {
const ok = await confirm(`Cancel task ${taskId}?`);
if (!ok) return;
}
const res = await apiFetch(`/api/v1/agents/tasks/${taskId}`, {
method: "POST",
body: { op: "cancel" },
});
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
process.stdout.write("Cancelled\n");
});
task
.command("approve <taskId>")
.description(t("cloud.task.approve.description"))
.action(async (taskId, opts, cmd) => {
const res = await apiFetch(`/api/v1/agents/tasks/${taskId}`, {
method: "POST",
body: { op: "approve_plan" },
});
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
process.stdout.write("Plan approved\n");
});
task
.command("message <taskId> <message>")
.description(t("cloud.task.message.description"))
.action(async (taskId, msg, opts, cmd) => {
const res = await apiFetch(`/api/v1/agents/tasks/${taskId}`, {
method: "POST",
body: { op: "message", message: msg },
});
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
process.stdout.write("Message sent\n");
});
parent
.command("sources <taskId>")
.description(t("cloud.sources.description"))
.action(async (taskId, opts, cmd) => {
const res = await apiFetch(`/api/v1/agents/tasks/${taskId}?op=sources`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.sources ?? data, cmd.optsWithGlobals());
});
}
export function registerCloud(program) {
const cloud = program.command("cloud").description(t("cloud.description"));
cloud
.command("agents")
.description(t("cloud.agents.description"))
.action(async (opts, cmd) => {
const res = await apiFetch("/api/v1/agents/tasks?meta=agents");
if (res.ok) {
const data = await res.json();
emit(data.agents ?? AGENTS.map((id) => ({ id })), cmd.optsWithGlobals());
} else {
emit(
AGENTS.map((id) => ({ id })),
cmd.optsWithGlobals()
);
}
});
for (const agent of AGENTS) {
const agentCmd = cloud
.command(agent)
.description(t("cloud.agent.description").replace("{agent}", agent));
registerTaskCommands(agentCmd, agent);
agentCmd
.command("auth")
.description(t("cloud.agent.auth.description"))
.option("--no-browser", "Skip browser open")
.option("--timeout <ms>", "Auth timeout ms", parseInt, 300000)
.action(async (opts, cmd) => {
const { runOAuthStart } = await import("./oauth.mjs");
await runOAuthStart({ provider: agent, ...opts }, cmd);
});
}
}

361
bin/cli/commands/combo.mjs Normal file
View File

@@ -0,0 +1,361 @@
import { Option } from "commander";
import { printHeading } from "../io.mjs";
import { withRuntime } from "../runtime.mjs";
import { t } from "../i18n.mjs";
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
const VALID_STRATEGIES = [
"priority",
"weighted",
"round-robin",
"p2c",
"random",
"auto",
"lkgp",
"context-optimized",
"context-relay",
"fill-first",
"cost-optimized",
"least-used",
"strict-random",
"reset-aware",
];
const suggestSchema = [
{ key: "rank", header: "#" },
{ key: "name", header: "Combo", width: 24 },
{ key: "strategy", header: "Strategy", width: 16 },
{ key: "score", header: "Score", formatter: (v) => (v != null ? v.toFixed(3) : "-") },
{ key: "latencyP50Ms", header: "Latency P50", formatter: (v) => (v != null ? `${v}ms` : "-") },
{ key: "costPer1k", header: "Cost/1k", formatter: (v) => (v != null ? `$${v.toFixed(5)}` : "-") },
{
key: "rationale",
header: "Rationale",
width: 40,
formatter: (v) => {
if (!v) return "-";
const s = String(v);
return s.length > 40 ? s.slice(0, 39) + "…" : s;
},
},
];
export function extendComboSuggest(combo) {
combo
.command("suggest")
.description(t("combo.suggest.description"))
.requiredOption("--task <description>", t("combo.suggest.task"))
.option("--max-cost <usd>", t("combo.suggest.maxCost"), parseFloat)
.option("--max-latency-ms <ms>", t("combo.suggest.maxLatencyMs"), parseInt)
.option("--weights <json>", t("combo.suggest.weights"))
.option("--top <n>", t("combo.suggest.top"), parseInt, 5)
.option("--explain", t("combo.suggest.explain"))
.option("--switch", t("combo.suggest.switch"))
.action(async (opts, cmd) => {
const body = {
task: opts.task,
constraints: {
maxCostUsd: opts.maxCost,
maxLatencyMs: opts.maxLatencyMs,
},
weights: opts.weights ? JSON.parse(opts.weights) : undefined,
top: opts.top,
};
const res = await apiFetch("/api/mcp/tools/call", {
method: "POST",
body: { name: "omniroute_best_combo_for_task", arguments: body },
});
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
const candidates = data.candidates ?? data;
const rows = (Array.isArray(candidates) ? candidates : []).map((c, i) => ({
rank: i + 1,
...c,
}));
emit(rows, cmd.optsWithGlobals(), suggestSchema);
if (opts.explain && !cmd.optsWithGlobals().quiet) {
process.stderr.write(`\nRationale:\n${data.rationale ?? "(no rationale)"}\n`);
}
if (opts.switch && rows[0]) {
const best = rows[0].name;
const switchRes = await apiFetch("/api/combos/switch", {
method: "POST",
body: { name: best },
});
if (!switchRes.ok) {
process.stderr.write(`Switch failed: ${switchRes.status}\n`);
process.exit(1);
}
process.stderr.write(`\nSwitched to: ${best}\n`);
}
});
}
export function registerCombo(program) {
const combo = program.command("combo").description(t("combo.title"));
combo
.command("list")
.description("List configured routing combos")
.option("--json", "Output as JSON")
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runComboListCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
combo
.command("switch <name>")
.description("Activate a routing combo")
.action(async (name, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runComboSwitchCommand(name, { ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
combo
.command("create <name>")
.description("Create a new routing combo")
.addOption(
new Option("--strategy <strategy>", "Routing strategy")
.choices(VALID_STRATEGIES)
.default("priority")
)
.action(async (name, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runComboCreateCommand(name, opts.strategy, {
...opts,
output: globalOpts.output,
});
if (exitCode !== 0) process.exit(exitCode);
});
combo
.command("delete <name>")
.description("Delete a routing combo")
.option("--yes", "Skip confirmation")
.action(async (name, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runComboDeleteCommand(name, { ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
extendComboSuggest(combo);
}
export async function runComboListCommand(opts = {}) {
try {
return await withRuntime(async ({ kind, api, db }) => {
let combos = [];
let activeCombo = null;
if (kind === "http") {
const [listRes, activeRes] = await Promise.all([
api("/api/combos", { retry: false, timeout: 5000, acceptNotOk: true }),
api("/api/settings", { retry: false, timeout: 3000, acceptNotOk: true }),
]);
if (listRes.ok) {
const data = await listRes.json();
combos = Array.isArray(data) ? data : (data.combos ?? []);
}
if (activeRes.ok) {
const settings = await activeRes.json();
activeCombo = settings?.activeCombo ?? null;
}
} else {
combos = await db.combos.getCombos();
}
if (opts.json || opts.output === "json") {
console.log(JSON.stringify({ combos, active: activeCombo }, null, 2));
return 0;
}
printHeading(t("combo.title"));
if (combos.length === 0) {
console.log(t("combo.noCombos"));
return 0;
}
for (const combo of combos) {
const comboName = combo.name ?? combo.id ?? "?";
const isActive = activeCombo && (comboName === activeCombo || combo.id === activeCombo);
const icon = isActive ? "\x1b[32m●\x1b[0m" : "\x1b[2m○\x1b[0m";
const enabled = combo.enabled !== false;
const status = enabled ? "\x1b[32menabled\x1b[0m" : "\x1b[31mdisabled\x1b[0m";
const strategy = (combo.strategy ?? "priority").padEnd(12);
console.log(` ${icon} ${comboName.padEnd(25)} [${strategy}] ${status}`);
}
return 0;
});
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runComboSwitchCommand(name, opts = {}) {
if (!name) {
console.error("Combo name is required.");
return 1;
}
try {
return await withRuntime(async ({ kind, api, db }) => {
if (kind === "http") {
const listRes = await api("/api/combos", {
retry: false,
timeout: 5000,
acceptNotOk: true,
});
if (!listRes.ok) {
console.error(`Failed to fetch combo list (HTTP ${listRes.status}).`);
return 1;
}
const data = await listRes.json();
const combos = Array.isArray(data) ? data : (data.combos ?? []);
const found = combos.find((c) => c.name === name || c.id === name);
if (!found) {
console.error(`Combo '${name}' not found.`);
return 1;
}
const patchRes = await api("/api/settings", {
method: "PATCH",
body: { activeCombo: name },
retry: false,
acceptNotOk: true,
});
if (!patchRes.ok) {
console.error(`Failed to switch combo (HTTP ${patchRes.status}).`);
return 1;
}
} else {
const combo = await db.combos.getComboByName(name);
if (!combo) {
console.error(`Combo '${name}' not found.`);
return 1;
}
db.combos.setActiveCombo(name);
}
console.log(t("combo.switched", { name }));
return 0;
});
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runComboCreateCommand(name, strategy = "priority", opts = {}) {
if (!name) {
console.error("Combo name is required.");
return 1;
}
if (!VALID_STRATEGIES.includes(strategy)) {
console.error(`Invalid strategy '${strategy}'. Valid: ${VALID_STRATEGIES.join(", ")}`);
return 1;
}
try {
return await withRuntime(async ({ kind, api, db }) => {
if (kind === "http") {
const res = await api("/api/combos", {
method: "POST",
body: { name, strategy, enabled: true, models: [], config: {} },
retry: false,
acceptNotOk: true,
});
if (!res.ok) {
const body = await res.text().catch(() => "");
const msg = body ? `${body}` : "";
console.error(`Failed to create combo (HTTP ${res.status})${msg}`);
return 1;
}
} else {
const existing = await db.combos.getComboByName(name);
if (existing) {
console.error(`Combo '${name}' already exists. Delete it first.`);
return 1;
}
await db.combos.createCombo({ name, strategy, enabled: true, models: [], config: {} });
}
console.log(t("combo.created", { name }));
return 0;
});
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runComboDeleteCommand(name, opts = {}) {
if (!name) {
console.error("Combo name is required.");
return 1;
}
if (!opts.yes) {
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((resolve) =>
rl.question(t("combo.confirmDelete", { name }) + " [y/N] ", resolve)
);
rl.close();
if (!/^y(es)?$/i.test(answer)) {
console.log(t("common.cancelled"));
return 0;
}
}
try {
return await withRuntime(async ({ kind, api, db }) => {
if (kind === "http") {
const listRes = await api("/api/combos", {
retry: false,
timeout: 5000,
acceptNotOk: true,
});
if (!listRes.ok) {
console.error(`Failed to fetch combo list (HTTP ${listRes.status}).`);
return 1;
}
const data = await listRes.json();
const combos = Array.isArray(data) ? data : (data.combos ?? []);
const found = combos.find((c) => c.name === name || c.id === name);
if (!found) {
console.error(`Combo '${name}' not found.`);
return 1;
}
const delRes = await api(`/api/combos/${encodeURIComponent(found.id)}`, {
method: "DELETE",
retry: false,
acceptNotOk: true,
});
if (!delRes.ok) {
console.error(`Failed to delete combo (HTTP ${delRes.status}).`);
return 1;
}
} else {
const deleted = await db.combos.deleteComboByName(name);
if (!deleted) {
console.error(`Combo '${name}' not found.`);
return 1;
}
}
console.log(t("combo.deleted", { name }));
return 0;
});
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}

View File

@@ -0,0 +1,346 @@
import { existsSync, writeFileSync, readFileSync, mkdirSync } from "node:fs";
import { join, dirname } from "node:path";
import { homedir } from "node:os";
import { t } from "../i18n.mjs";
import { apiFetch } from "../api.mjs";
import { resolveDataDir } from "../data-dir.mjs";
const CACHE_TTL_MS = 60 * 60 * 1000; // 1h
function cachePath() {
return join(resolveDataDir(), "completion-cache.json");
}
function readCache() {
try {
const raw = JSON.parse(readFileSync(cachePath(), "utf8"));
if (raw && typeof raw.ts === "number" && Date.now() - raw.ts < CACHE_TTL_MS) return raw;
} catch {}
return null;
}
async function refreshCache(opts = {}) {
let combos = [],
providers = [],
models = [];
try {
const [cr, pr, mr] = await Promise.allSettled([
apiFetch("/api/combos", opts),
apiFetch("/api/providers", opts),
apiFetch("/api/models", opts),
]);
if (cr.status === "fulfilled" && cr.value.ok) {
const j = await cr.value.json();
combos = (j.combos || j.items || []).map((c) => c.name || c.id).filter(Boolean);
}
if (pr.status === "fulfilled" && pr.value.ok) {
const j = await pr.value.json();
providers = (j.providers || j.items || []).map((p) => p.id || p.name).filter(Boolean);
}
if (mr.status === "fulfilled" && mr.value.ok) {
const j = await mr.value.json();
models = (Array.isArray(j) ? j : j.data || []).map((m) => m.id).filter(Boolean);
}
} catch {}
const data = { combos, providers, models, ts: Date.now() };
try {
mkdirSync(dirname(cachePath()), { recursive: true });
writeFileSync(cachePath(), JSON.stringify(data));
} catch {}
return data;
}
function detectShell() {
const shell = process.env.SHELL || "";
if (shell.includes("zsh")) return "zsh";
if (shell.includes("fish")) return "fish";
return "bash";
}
function installPath(shell) {
const home = homedir();
if (shell === "zsh") return join(home, ".zsh", "completions", "_omniroute");
if (shell === "fish") return join(home, ".config", "fish", "completions", "omniroute.fish");
return join(home, ".bash_completion.d", "omniroute");
}
function generateZshScript() {
return `#compdef omniroute
# OmniRoute zsh completion (dynamic)
_omniroute_get_cache() {
local key="$1"
local cache="$HOME/.omniroute/completion-cache.json"
local now=$(date +%s 2>/dev/null || echo 0)
local mtime=0
if [[ -f "$cache" ]]; then
mtime=$(stat -c %Y "$cache" 2>/dev/null || stat -f %m "$cache" 2>/dev/null || echo 0)
fi
if [[ $((now - mtime)) -gt 3600 ]]; then
omniroute completion refresh --quiet >/dev/null 2>&1
fi
if command -v python3 &>/dev/null && [[ -f "$cache" ]]; then
python3 -c "import json,sys;d=json.load(open('$cache'));print(' '.join(d.get('$key',[])))" 2>/dev/null
fi
}
_omniroute() {
local -a commands
commands=(
'serve:Start the OmniRoute server'
'stop:Stop the server'
'restart:Restart the server'
'setup:Configure OmniRoute'
'doctor:Run health diagnostics'
'status:Show server status'
'logs:View application logs'
'providers:Manage providers'
'config:Manage config and contexts'
'keys:Manage API keys'
'models:Browse available models'
'combo:Manage routing combos'
'chat:Send chat completion'
'stream:Stream chat completion'
'dashboard:Open dashboard'
'open:Open UI resource in browser'
'backup:Create a backup'
'restore:Restore from backup'
'health:Show server health'
'quota:Show provider quotas'
'cache:Manage response cache'
'mcp:MCP server management'
'a2a:A2A server management'
'tunnel:Tunnel management'
'env:Environment variables'
'test:Test provider connection'
'update:Check for updates'
'completion:Shell completion'
'memory:Manage memory store'
'skills:Manage skills'
)
_arguments -C \\
'1: :->command' \\
'*:: :->arg' && return 0
case $state in
command) _describe 'command' commands ;;
arg)
case $words[1] in
combo)
case $words[2] in
switch|delete|show)
local -a combos
combos=($(_omniroute_get_cache combos))
_describe 'combo' combos ;;
*) _arguments '1:subcommand:(list switch create delete show suggest)' ;;
esac ;;
providers|keys)
case $words[2] in
add|remove|test)
local -a providers
providers=($(_omniroute_get_cache providers))
_describe 'provider' providers ;;
*) _arguments '1:subcommand:(list add remove test)' ;;
esac ;;
chat|stream)
_arguments \\
'--model[Model ID]:model:->models' \\
'--combo[Combo name]:combo:->combos' \\
'--system[System prompt]:' \\
'--max-tokens[Max tokens]:' ;;
open)
_arguments '1:resource:(combos providers api-manager cli-tools agents settings logs memory skills evals audit cost resilience)' ;;
completion) _arguments '1:subcommand:(zsh bash fish install refresh)' ;;
config) _arguments '1:subcommand:(list get set validate contexts)' ;;
*) ;;
esac
case $state in
models)
local -a models
models=($(_omniroute_get_cache models))
_describe 'model' models ;;
combos)
local -a combos
combos=($(_omniroute_get_cache combos))
_describe 'combo' combos ;;
esac ;;
esac
}
compdef _omniroute omniroute
`;
}
function generateBashScript() {
return `#!/bin/bash
# OmniRoute CLI bash completion (dynamic)
_omniroute_get_cache() {
local key="$1"
local cache="$HOME/.omniroute/completion-cache.json"
local now
now=$(date +%s 2>/dev/null || echo 0)
local mtime=0
[[ -f "$cache" ]] && mtime=$(stat -c %Y "$cache" 2>/dev/null || stat -f %m "$cache" 2>/dev/null || echo 0)
if (( now - mtime > 3600 )); then
omniroute completion refresh --quiet >/dev/null 2>&1
fi
if command -v python3 &>/dev/null && [[ -f "$cache" ]]; then
python3 -c "import json,sys;d=json.load(open('$cache'));print(' '.join(d.get('$key',[])))" 2>/dev/null
fi
}
_omniroute() {
local cur prev cmds
COMPREPLY=()
cur="\${COMP_WORDS[COMP_CWORD]}"
prev="\${COMP_WORDS[COMP_CWORD-1]}"
cmds="setup doctor status logs providers config test update serve stop restart keys models combo chat stream completion dashboard open backup restore health quota cache mcp a2a tunnel env memory skills"
case "\${prev}" in
combo) COMPREPLY=($(compgen -W "list switch create delete show suggest" -- "\${cur}")); return 0 ;;
keys) COMPREPLY=($(compgen -W "add list remove regenerate revoke reveal usage" -- "\${cur}")); return 0 ;;
providers) COMPREPLY=($(compgen -W "available list test test-all" -- "\${cur}")); return 0 ;;
config) COMPREPLY=($(compgen -W "list get set validate contexts" -- "\${cur}")); return 0 ;;
completion) COMPREPLY=($(compgen -W "zsh bash fish install refresh" -- "\${cur}")); return 0 ;;
open) COMPREPLY=($(compgen -W "combos providers api-manager cli-tools agents settings logs memory skills evals audit cost resilience" -- "\${cur}")); return 0 ;;
--model)
local models
models=$(_omniroute_get_cache models)
COMPREPLY=($(compgen -W "\${models}" -- "\${cur}")); return 0 ;;
--combo)
local combos
combos=$(_omniroute_get_cache combos)
COMPREPLY=($(compgen -W "\${combos}" -- "\${cur}")); return 0 ;;
switch|delete)
local combos
combos=$(_omniroute_get_cache combos)
COMPREPLY=($(compgen -W "\${combos}" -- "\${cur}")); return 0 ;;
*)
COMPREPLY=($(compgen -W "\${cmds} --help --version --output --quiet" -- "\${cur}")); return 0 ;;
esac
}
complete -F _omniroute omniroute
`;
}
function generateFishScript() {
return `# OmniRoute CLI fish completion (dynamic)
complete -c omniroute -f
set -l commands serve stop restart setup doctor status logs providers config keys models combo chat stream completion dashboard open backup restore health quota cache mcp a2a tunnel env memory skills update test
for cmd in $commands
complete -c omniroute -n '__fish_is_nth_token 1' -a $cmd
end
# Subcommands
complete -c omniroute -n '__fish_seen_subcommand_from combo' -a 'list switch create delete show suggest'
complete -c omniroute -n '__fish_seen_subcommand_from keys' -a 'add list remove regenerate revoke reveal usage'
complete -c omniroute -n '__fish_seen_subcommand_from providers' -a 'available list test test-all'
complete -c omniroute -n '__fish_seen_subcommand_from config' -a 'list get set validate contexts'
complete -c omniroute -n '__fish_seen_subcommand_from completion' -a 'zsh bash fish install refresh'
complete -c omniroute -n '__fish_seen_subcommand_from open' -a 'combos providers api-manager cli-tools agents settings logs memory skills evals audit cost resilience'
# Dynamic completions from cache (requires python3)
function __omniroute_cache_get
set -l key $argv[1]
set -l cache "$HOME/.omniroute/completion-cache.json"
set -l now (date +%s 2>/dev/null; or echo 0)
set -l mtime 0
test -f $cache; and set mtime (stat -c %Y $cache 2>/dev/null; or stat -f %m $cache 2>/dev/null; or echo 0)
if test (math $now - $mtime) -gt 3600
omniroute completion refresh --quiet >/dev/null 2>&1
end
if command -q python3; and test -f $cache
python3 -c "import json,sys;d=json.load(open('$cache'));print('\\n'.join(d.get('$key',[])))" 2>/dev/null
end
end
complete -c omniroute -n '__fish_seen_subcommand_from combo; and __fish_seen_subcommand_from switch delete' -a '(__omniroute_cache_get combos)'
complete -c omniroute -l model -a '(__omniroute_cache_get models)'
complete -c omniroute -l combo -a '(__omniroute_cache_get combos)'
`;
}
const generators = { zsh: generateZshScript, bash: generateBashScript, fish: generateFishScript };
export function registerCompletion(program) {
const comp = program
.command("completion")
.description(t("completion.description") || "Generate or install shell completion scripts");
comp
.command("zsh")
.description(t("completion.zsh") || "Print zsh completion script")
.action(async () => process.stdout.write(generateZshScript()));
comp
.command("bash")
.description(t("completion.bash") || "Print bash completion script")
.action(async () => process.stdout.write(generateBashScript()));
comp
.command("fish")
.description(t("completion.fish") || "Print fish completion script")
.action(async () => process.stdout.write(generateFishScript()));
comp
.command("install [shell]")
.description(t("completion.install") || "Install completion script globally for detected shell")
.action(async (shell, opts, cmd) => {
const target = shell || detectShell();
const gen = generators[target];
if (!gen) {
process.stderr.write(`Unknown shell: ${target}. Valid: bash, zsh, fish\n`);
process.exit(2);
}
const dest = installPath(target);
mkdirSync(dirname(dest), { recursive: true });
writeFileSync(dest, gen());
process.stdout.write(
`Installed ${target} completion at ${dest}\nRestart your shell or source the file.\n`
);
});
comp
.command("refresh")
.description(t("completion.refresh") || "Refresh cache of combos/providers/models")
.option("--quiet", "Suppress output")
.action(async (opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const data = await refreshCache(globalOpts);
if (!opts.quiet && !globalOpts.quiet) {
process.stdout.write(
`Cached: ${data.combos.length} combos, ${data.providers.length} providers, ${data.models.length} models\n`
);
}
});
// Backward-compat: `omniroute completion <shell>` (positional arg form)
comp
.command("<shell>")
.description("Print completion script for shell (bash, zsh, fish)")
.allowUnknownOption(false)
.action(async (shell) => {
const gen = generators[shell];
if (!gen) {
process.stderr.write(`Unknown shell: ${shell}. Valid: bash, zsh, fish\n`);
process.exit(1);
}
process.stdout.write(gen());
});
}
// Legacy export for backward compatibility
export async function runCompletionCommand(shell) {
const gen = generators[shell];
if (!gen) {
process.stderr.write(`Unknown shell: ${shell}. Valid: bash, zsh, fish\n`);
return 1;
}
process.stdout.write(gen());
return 0;
}

View File

@@ -0,0 +1,167 @@
import { readFileSync } from "node:fs";
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
const VALID_ENGINES = ["caveman", "rtk", "hybrid", "none"];
async function mcpCall(name, args) {
const res = await apiFetch("/api/mcp/tools/call", {
method: "POST",
body: { name, arguments: args },
});
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
return res.json();
}
async function confirm(q) {
return new Promise((resolve) => {
process.stdout.write(`${q} (yes/no) `);
process.stdin.setEncoding("utf8");
process.stdin.once("data", (c) => resolve(c.toString().trim().toLowerCase().startsWith("y")));
});
}
export async function runCompressionStatus(opts, cmd) {
const data = await mcpCall("omniroute_compression_status", {});
emit(data, cmd.optsWithGlobals());
}
export async function runCompressionConfigure(opts, cmd) {
const config = {};
if (opts.engine) config.engine = opts.engine;
if (opts.cavemanAggressiveness !== undefined)
config.caveman = { aggressiveness: opts.cavemanAggressiveness };
if (opts.rtkBudget !== undefined) config.rtk = { tokenBudget: opts.rtkBudget };
if (opts.languagePack) config.languagePack = opts.languagePack;
const data = await mcpCall("omniroute_compression_configure", config);
emit(data, cmd.optsWithGlobals());
}
export async function runCompressionEngineSet(name, opts, cmd) {
if (!VALID_ENGINES.includes(name)) {
process.stderr.write(`Unknown engine: ${name}. Valid: ${VALID_ENGINES.join(", ")}\n`);
process.exit(2);
}
await mcpCall("omniroute_set_compression_engine", { engine: name });
process.stdout.write(`Engine: ${name}\n`);
}
export async function runCompressionPreview(opts, cmd) {
const body = JSON.parse(readFileSync(opts.file, "utf8"));
const res = await apiFetch("/api/compression/preview", { method: "POST", body });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data, cmd.optsWithGlobals());
if (cmd.optsWithGlobals().output !== "json") {
process.stderr.write(
`\nOriginal: ${data.beforeTokens ?? "?"} tok → After: ${data.afterTokens ?? "?"} tok (${data.savingsPct ?? "?"}%)\n`
);
}
}
export function registerCompression(program) {
const cmp = program.command("compression").description(t("compression.description"));
cmp
.command("status")
.description(t("compression.status.description"))
.action(runCompressionStatus);
cmp
.command("configure")
.description(t("compression.configure.description"))
.option("--engine <e>", t("compression.configure.engine"))
.option("--caveman-aggressiveness <n>", t("compression.configure.caveman_agg"), parseFloat)
.option("--rtk-budget <n>", t("compression.configure.rtk_budget"), parseInt)
.option("--language-pack <p>", t("compression.configure.language_pack"))
.action(runCompressionConfigure);
const engine = cmp.command("engine").description(t("compression.engine.description"));
engine.command("set <name>").action(runCompressionEngineSet);
engine.command("get").action(async (opts, cmd) => {
const data = await mcpCall("omniroute_compression_status", {});
process.stdout.write(`${data.engine ?? "(default)"}\n`);
});
const combos = cmp.command("combos").description(t("compression.combos.description"));
combos.command("list").action(async (opts, cmd) => {
const data = await mcpCall("omniroute_list_compression_combos", {});
emit(data.combos ?? data, cmd.optsWithGlobals());
});
combos
.command("stats")
.option("--period <p>", null, "7d")
.action(async (opts, cmd) => {
const data = await mcpCall("omniroute_compression_combo_stats", {
period: opts.period ?? "7d",
});
emit(data, cmd.optsWithGlobals());
});
const rules = cmp.command("rules").description(t("compression.rules.description"));
rules.command("list").action(async (opts, cmd) => {
const res = await apiFetch("/api/compression/rules");
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
rules
.command("add")
.requiredOption("--pattern <p>", t("compression.rules.add.pattern"))
.requiredOption("--action <a>", t("compression.rules.add.action"))
.option("--replacement <r>")
.action(async (opts, cmd) => {
const body = { pattern: opts.pattern, action: opts.action };
if (opts.replacement) body.replacement = opts.replacement;
const res = await apiFetch("/api/compression/rules", { method: "POST", body });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
rules
.command("remove <id>")
.option("--yes")
.action(async (id, opts, cmd) => {
if (!opts.yes) {
const ok = await confirm(`Remove rule ${id}?`);
if (!ok) return;
}
const res = await apiFetch(`/api/compression/rules?id=${encodeURIComponent(id)}`, {
method: "DELETE",
});
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
process.stdout.write("Removed\n");
});
cmp
.command("language-packs")
.description(t("compression.language_packs.description"))
.action(async (opts, cmd) => {
const res = await apiFetch("/api/compression/language-packs");
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
cmp
.command("preview")
.description(t("compression.preview.description"))
.requiredOption("--file <path>", t("compression.preview.file"))
.action(runCompressionPreview);
}

View File

@@ -1,29 +1,10 @@
import { parseArgs, getStringFlag, hasFlag } from "../args.mjs";
import { printHeading, printInfo, printSuccess, printError } from "../io.mjs";
import { resolveDataDir } from "../data-dir.mjs";
import { t } from "../i18n.mjs";
import path from "node:path";
import fs from "node:fs";
function printConfigHelp() {
console.log(`
Usage:
omniroute config list List all CLI tools and config status
omniroute config get <tool> Show current config for a tool
omniroute config set <tool> [options] Write config for a tool
omniroute config validate <tool> Validate config format without writing
Options:
--base-url <url> OmniRoute API base URL (default: http://localhost:20128/v1)
--api-key <key> API key for the tool
--model <model> Model identifier (where applicable)
--json Output as JSON
--non-interactive Do not prompt for confirmation
--yes Skip confirmation prompt
--help Show this help
Tools: claude, codex, opencode, cline, kilocode, continue
`);
}
import { fileURLToPath } from "node:url";
import { resolveDataDir } from "../data-dir.mjs";
import { registerContexts } from "./contexts.mjs";
function ensureBackup(configPath) {
if (!fs.existsSync(configPath)) return;
@@ -34,149 +15,312 @@ function ensureBackup(configPath) {
return backupPath;
}
export async function runConfigCommand(argv) {
const { flags, positionals } = parseArgs(argv);
async function runConfigListCommand(opts = {}) {
const { detectAllTools } = await import("../../../src/lib/cli-helper/tool-detector.js");
const tools = await detectAllTools();
if (hasFlag(flags, "help") || hasFlag(flags, "h") || positionals.length === 0) {
printConfigHelp();
return 0;
if (opts.json) {
console.log(JSON.stringify(tools, null, 2));
} else {
printHeading("CLI Tool Configuration Status");
for (const t of tools) {
const status = t.configured
? "✓ Configured"
: t.installed
? "✗ Not configured"
: "✗ Not installed";
console.log(` ${t.name.padEnd(14)} ${status}`);
if (t.version) console.log(` version: ${t.version}`);
console.log(` config: ${t.configPath}`);
}
}
return 0;
}
const subcommand = positionals[0];
const toolId = positionals[1];
if (subcommand === "list") {
const { detectAllTools } = await import("../../../src/lib/cli-helper/tool-detector.js");
const tools = await detectAllTools();
if (hasFlag(flags, "json")) {
console.log(JSON.stringify(tools, null, 2));
} else {
printHeading("CLI Tool Configuration Status");
for (const t of tools) {
const status = t.configured
? "✓ Configured"
: t.installed
? "✗ Not configured"
: "✗ Not installed";
console.log(` ${t.name.padEnd(14)} ${status}`);
if (t.version) console.log(` version: ${t.version}`);
console.log(` config: ${t.configPath}`);
}
async function runConfigGetCommand(toolId, opts = {}) {
if (!toolId) {
printError("Tool ID required. Usage: omniroute config get <tool>");
return 1;
}
const { detectTool } = await import("../../../src/lib/cli-helper/tool-detector.js");
const tool = await detectTool(toolId);
if (!tool) {
printError(`Unknown tool: ${toolId}`);
return 1;
}
if (opts.json) {
console.log(JSON.stringify(tool, null, 2));
} else {
printHeading(`${tool.name} Configuration`);
console.log(` Installed: ${tool.installed ? "Yes" : "No"}`);
console.log(` Configured: ${tool.configured ? "Yes" : "No"}`);
console.log(` Config: ${tool.configPath}`);
if (tool.version) console.log(` Version: ${tool.version}`);
if (tool.configContents) {
console.log(`\n Contents:`);
console.log(tool.configContents);
}
return 0;
}
return 0;
}
async function runConfigSetCommand(toolId, opts = {}) {
if (!toolId) {
printError("Tool ID required. Usage: omniroute config set <tool> [options]");
return 1;
}
const baseUrl = opts.baseUrl || "http://localhost:20128/v1";
const apiKey = opts.apiKey;
const model = opts.model;
if (!apiKey) {
printError("API key required. Use --api-key or set OMNIROUTE_API_KEY.");
return 1;
}
if (subcommand === "get") {
if (!toolId) {
printError("Tool ID required. Usage: omniroute config get <tool>");
return 1;
}
const { detectTool } = await import("../../../src/lib/cli-helper/tool-detector.js");
const tool = await detectTool(toolId);
if (!tool) {
printError(`Unknown tool: ${toolId}`);
return 1;
}
if (hasFlag(flags, "json")) {
console.log(JSON.stringify(tool, null, 2));
} else {
printHeading(`${tool.name} Configuration`);
console.log(` Installed: ${tool.installed ? "Yes" : "No"}`);
console.log(` Configured: ${tool.configured ? "Yes" : "No"}`);
console.log(` Config: ${tool.configPath}`);
if (tool.version) console.log(` Version: ${tool.version}`);
if (tool.configContents) {
console.log(`\n Contents:`);
console.log(tool.configContents);
}
}
return 0;
const { generateConfig } = await import("../../../src/lib/cli-helper/config-generator/index.js");
const result = await generateConfig(toolId, { baseUrl, apiKey, model });
if (!result.success) {
printError(result.error || "Failed to generate config");
return 1;
}
if (subcommand === "set") {
if (!toolId) {
printError("Tool ID required. Usage: omniroute config set <tool> [options]");
return 1;
}
const nonInteractive = opts.nonInteractive || opts.yes;
if (!nonInteractive) {
console.log(`\n About to write config to: ${result.configPath}`);
console.log(` Content preview:\n`);
console.log(result.content);
console.log("");
const baseUrl =
getStringFlag(flags, "base-url", "OMNIROUTE_BASE_URL") || "http://localhost:20128/v1";
const apiKey = getStringFlag(flags, "api-key", "OMNIROUTE_API_KEY");
const model = getStringFlag(flags, "model");
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((resolve) => rl.question("Proceed? [y/N] ", resolve));
rl.close();
if (!apiKey) {
printError("API key required. Use --api-key or set OMNIROUTE_API_KEY.");
return 1;
if (!/^y(es)?$/i.test(answer)) {
console.log("Aborted.");
return 0;
}
}
const { generateConfig } =
await import("../../../src/lib/cli-helper/config-generator/index.js");
const result = await generateConfig(toolId, { baseUrl, apiKey, model });
const dir = path.dirname(result.configPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
if (!result.success) {
printError(result.error || "Failed to generate config");
return 1;
}
const backupPath = ensureBackup(result.configPath);
if (backupPath) printInfo(`Backup saved to: ${backupPath}`);
const nonInteractive = hasFlag(flags, "non-interactive") || hasFlag(flags, "yes");
fs.writeFileSync(result.configPath, result.content, "utf-8");
printSuccess(`Config written to ${result.configPath}`);
return 0;
}
if (!nonInteractive) {
console.log(`\n About to write config to: ${result.configPath}`);
console.log(` Content preview:\n`);
console.log(result.content);
console.log("");
async function runConfigValidateCommand(toolId, opts = {}) {
if (!toolId) {
printError("Tool ID required. Usage: omniroute config validate <tool>");
return 1;
}
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((resolve) => rl.question("Proceed? [y/N] ", resolve));
rl.close();
const baseUrl = opts.baseUrl || "http://localhost:20128/v1";
const apiKey = opts.apiKey || "test-key";
const model = opts.model;
if (!/^y(es)?$/i.test(answer)) {
console.log("Aborted.");
return 0;
}
}
const { generateConfig } = await import("../../../src/lib/cli-helper/config-generator/index.js");
const result = await generateConfig(toolId, { baseUrl, apiKey, model });
const dir = path.dirname(result.configPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
if (!result.success) {
printError(`Validation failed: ${result.error}`);
return 1;
}
const backupPath = ensureBackup(result.configPath);
if (backupPath) printInfo(`Backup saved to: ${backupPath}`);
printSuccess(`Config for ${toolId} is valid`);
if (opts.json) {
console.log(JSON.stringify({ valid: true, content: result.content }, null, 2));
}
return 0;
}
fs.writeFileSync(result.configPath, result.content, "utf-8");
printSuccess(`Config written to ${result.configPath}`);
return 0;
function loadI18nLocales() {
const cfgPath = path.join(
path.dirname(path.dirname(path.dirname(path.dirname(fileURLToPath(import.meta.url))))),
"config",
"i18n.json"
);
try {
return JSON.parse(fs.readFileSync(cfgPath, "utf8")).locales || [];
} catch {
return [];
}
}
if (subcommand === "validate") {
if (!toolId) {
printError("Tool ID required. Usage: omniroute config validate <tool>");
return 1;
}
function getCliEnvPath() {
return path.join(resolveDataDir(), ".env");
}
const baseUrl =
getStringFlag(flags, "base-url", "OMNIROUTE_BASE_URL") || "http://localhost:20128/v1";
const apiKey = getStringFlag(flags, "api-key", "OMNIROUTE_API_KEY") || "test-key";
const model = getStringFlag(flags, "model");
function upsertEnvLine(envPath, key, value) {
let content = "";
if (fs.existsSync(envPath)) content = fs.readFileSync(envPath, "utf8");
const lines = content.split("\n");
const idx = lines.findIndex((l) => l.trimStart().startsWith(`${key}=`));
const newLine = `${key}=${value}`;
if (idx >= 0) {
lines[idx] = newLine;
} else {
if (content && !content.endsWith("\n")) lines.push("");
lines.push(newLine);
}
const dir = path.dirname(envPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const tmp = `${envPath}.tmp`;
fs.writeFileSync(tmp, lines.join("\n"), "utf8");
fs.renameSync(tmp, envPath);
}
const { generateConfig } =
await import("../../../src/lib/cli-helper/config-generator/index.js");
const result = await generateConfig(toolId, { baseUrl, apiKey, model });
export async function runConfigLangGetCommand(opts = {}) {
const { getLocale } = await import("../i18n.mjs");
const code = getLocale();
const locales = loadI18nLocales();
const entry = locales.find((l) => l.code === code);
const name = entry ? entry.english : code;
if (opts.output === "json" || opts.json) {
console.log(JSON.stringify({ code, name }, null, 2));
} else {
console.log(t("config.lang.current", { code, name }));
}
return 0;
}
if (!result.success) {
printError(`Validation failed: ${result.error}`);
return 1;
}
export async function runConfigLangSetCommand(code, opts = {}) {
if (!code) {
console.error(t("config.lang.noCode"));
return 1;
}
const locales = loadI18nLocales();
const entry = locales.find((l) => l.code === code);
if (!entry) {
console.error(t("config.lang.unknown", { code }));
return 1;
}
const { getLocale, setLocale } = await import("../i18n.mjs");
const current = getLocale();
if (current === code && !opts.force) {
console.log(t("config.lang.alreadySet", { code }));
return 0;
}
const envPath = getCliEnvPath();
upsertEnvLine(envPath, "OMNIROUTE_LANG", code);
setLocale(code);
console.log(t("config.lang.saved", { code, name: entry.english }));
console.log(t("config.lang.envHint", { code }));
return 0;
}
printSuccess(`Config for ${toolId} is valid`);
if (hasFlag(flags, "json")) {
console.log(JSON.stringify({ valid: true, content: result.content }, null, 2));
}
export async function runConfigLangListCommand(opts = {}) {
const { getLocale } = await import("../i18n.mjs");
const current = getLocale();
const locales = loadI18nLocales();
if (opts.output === "json" || opts.json) {
console.log(
JSON.stringify(
locales.map((l) => ({ ...l, active: l.code === current })),
null,
2
)
);
return 0;
}
console.log(`\n\x1b[1m\x1b[36m${t("config.lang.listTitle")}\x1b[0m\n`);
for (const loc of locales) {
const active = loc.code === current ? " \x1b[32m◀ active\x1b[0m" : "";
console.log(
` ${loc.flag} ${loc.code.padEnd(8)} ${loc.english.padEnd(28)} ${loc.native}${active}`
);
}
console.log("");
return 0;
}
export function registerConfig(program) {
const config = program.command("config").description("Show or update CLI tool configuration");
config
.command("list")
.description("List all CLI tools and config status")
.option("--json", "Output as JSON")
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runConfigListCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
config
.command("get <tool>")
.description("Show current config for a tool")
.option("--json", "Output as JSON")
.action(async (tool, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runConfigGetCommand(tool, { ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
config
.command("set <tool>")
.description("Write config for a tool")
.option("--base-url <url>", "OmniRoute API base URL", "http://localhost:20128/v1")
.option("--api-key <key>", "API key for the tool")
.option("--model <model>", "Model identifier (where applicable)")
.option("--non-interactive", "Do not prompt for confirmation")
.option("--yes", "Skip confirmation prompt")
.action(async (tool, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runConfigSetCommand(tool, { ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
config
.command("validate <tool>")
.description("Validate config format without writing")
.option("--base-url <url>", "OmniRoute API base URL", "http://localhost:20128/v1")
.option("--api-key <key>", "API key for the tool")
.option("--model <model>", "Model identifier (where applicable)")
.option("--json", "Output as JSON")
.action(async (tool, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runConfigValidateCommand(tool, { ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
// lang subgroup
const lang = config.command("lang").description(t("config.lang.description"));
lang
.command("get")
.description(t("config.lang.getDescription"))
.option("--json", t("common.jsonOpt"))
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.parent.optsWithGlobals();
const exitCode = await runConfigLangGetCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
lang
.command("set <code>")
.description(t("config.lang.setDescription"))
.option("--force", "Set even if already active")
.action(async (code, opts, cmd) => {
const exitCode = await runConfigLangSetCommand(code, opts);
if (exitCode !== 0) process.exit(exitCode);
});
lang
.command("list")
.description(t("config.lang.listDescription"))
.option("--json", t("common.jsonOpt"))
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.parent.optsWithGlobals();
const exitCode = await runConfigLangListCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
printError(`Unknown subcommand: ${subcommand}`);
printConfigHelp();
return 1;
// Register contexts/profiles CRUD as a subgroup of config.
registerContexts(config);
}

View File

@@ -0,0 +1,182 @@
import { readFileSync } from "node:fs";
import { createInterface } from "node:readline";
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
async function confirm(q) {
const rl = createInterface({ input: process.stdin, output: process.stdout });
return new Promise((resolve) => {
rl.question(`${q} [y/N] `, (a) => {
rl.close();
resolve(a.trim().toLowerCase() === "y");
});
});
}
export function registerContextEng(program) {
const ctx = program.command("context-eng").alias("ctx").description(t("context.description"));
ctx
.command("analytics")
.option("--period <p>", t("context.analytics.period"), "7d")
.action(async (opts, cmd) => {
const res = await apiFetch(`/api/context/analytics?period=${opts.period}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
const caveman = ctx.command("caveman").description(t("context.caveman.description"));
const cmCfg = caveman.command("config").description(t("context.caveman.config.description"));
cmCfg.command("show").action(async (opts, cmd) => {
const res = await apiFetch("/api/context/caveman/config");
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
cmCfg
.command("set")
.option("--aggressiveness <n>", t("context.caveman.config.aggressiveness"), parseFloat)
.option("--max-shrink-pct <n>", t("context.caveman.config.maxShrinkPct"), parseInt)
.option("--preserve-tags <list>", t("context.caveman.config.preserveTags"), (v) => v.split(","))
.action(async (opts, cmd) => {
const body = {};
if (opts.aggressiveness !== undefined) body.aggressiveness = opts.aggressiveness;
if (opts.maxShrinkPct !== undefined) body.maxShrinkPct = opts.maxShrinkPct;
if (opts.preserveTags) body.preserveTags = opts.preserveTags;
const res = await apiFetch("/api/context/caveman/config", { method: "PUT", body });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
const rtk = ctx.command("rtk").description(t("context.rtk.description"));
const rtkCfg = rtk.command("config").description(t("context.rtk.config.description"));
rtkCfg.command("show").action(async (opts, cmd) => {
const res = await apiFetch("/api/context/rtk/config");
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
rtkCfg
.command("set")
.option("--token-budget <n>", t("context.rtk.config.tokenBudget"), parseInt)
.option("--reserve-pct <n>", t("context.rtk.config.reservePct"), parseInt)
.action(async (opts, cmd) => {
const body = {};
if (opts.tokenBudget) body.tokenBudget = opts.tokenBudget;
if (opts.reservePct) body.reservePct = opts.reservePct;
const res = await apiFetch("/api/context/rtk/config", { method: "PUT", body });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
const filters = rtk.command("filters").description(t("context.rtk.filters.description"));
filters.command("list").action(async (opts, cmd) => {
const res = await apiFetch("/api/context/rtk/filters");
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
filters
.command("add")
.requiredOption("--pattern <p>", t("context.rtk.filters.pattern"))
.option("--priority <n>", t("context.rtk.filters.priority"), parseInt, 100)
.option("--action <a>", t("context.rtk.filters.action"), "drop")
.action(async (opts, cmd) => {
const body = { pattern: opts.pattern, priority: opts.priority, action: opts.action };
const res = await apiFetch("/api/context/rtk/filters", { method: "POST", body });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
filters
.command("remove <id>")
.option("--yes", t("context.rtk.filters.yes"))
.action(async (id, opts, cmd) => {
if (!opts.yes) {
const ok = await confirm(`Remove filter ${id}?`);
if (!ok) return;
}
const res = await apiFetch(`/api/context/rtk/filters/${id}`, { method: "DELETE" });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
process.stdout.write("Removed\n");
});
rtk
.command("test")
.requiredOption("--file <path>", t("context.rtk.test.file"))
.action(async (opts, cmd) => {
const body = JSON.parse(readFileSync(opts.file, "utf8"));
const res = await apiFetch("/api/context/rtk/test", { method: "POST", body });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
rtk.command("raw-output <id>").action(async (id, opts, cmd) => {
const res = await apiFetch(`/api/context/rtk/raw-output/${id}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
const combos = ctx.command("combos").description(t("context.combos.description"));
combos.command("list").action(async (opts, cmd) => {
const res = await apiFetch("/api/context/combos");
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
combos.command("get <id>").action(async (id, opts, cmd) => {
const res = await apiFetch(`/api/context/combos/${id}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
combos.command("assignments <id>").action(async (id, opts, cmd) => {
const res = await apiFetch(`/api/context/combos/${id}/assignments`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
}

View File

@@ -0,0 +1,223 @@
import { t } from "../i18n.mjs";
import { emit } from "../output.mjs";
import { loadContexts, saveContexts, configPath } from "../contexts.mjs";
async function confirm(msg) {
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((r) => rl.question(`${msg} [y/N] `, r));
rl.close();
return /^y(es)?$/i.test(answer);
}
function maskKey(k) {
if (!k) return null;
if (k.length <= 8) return "***";
return `${k.slice(0, 6)}***${k.slice(-4)}`;
}
export function registerContexts(program) {
const ctx = program
.command("contexts")
.description(t("config.contexts.description") || "Manage server contexts/profiles");
ctx
.command("list")
.description("List all contexts")
.action(async (opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const cfg = loadContexts();
const rows = Object.entries(cfg.contexts || {}).map(([name, c]) => ({
active: name === (cfg.currentContext || "default") ? "●" : "",
name,
baseUrl: c.baseUrl || "",
auth: c.apiKey ? "✓" : "✗",
description: c.description || "",
}));
emit(rows, globalOpts, [
{ key: "active", header: "" },
{ key: "name", header: "Name" },
{ key: "baseUrl", header: "Base URL" },
{ key: "auth", header: "Auth" },
{ key: "description", header: "Description" },
]);
});
ctx
.command("add <name>")
.description("Add a new context")
.requiredOption("--url <u>", "Base URL")
.option("--api-key <k>", "API key")
.option("--api-key-stdin", "Read API key from stdin")
.option("--description <d>", "Context description")
.action(async (name, opts) => {
const cfg = loadContexts();
if (cfg.contexts?.[name]) {
process.stderr.write(`Context '${name}' already exists. Remove or rename first.\n`);
process.exit(2);
}
let apiKey = opts.apiKey || null;
if (opts.apiKeyStdin) {
const chunks = [];
for await (const c of process.stdin) chunks.push(c);
apiKey = chunks.join("").trim() || null;
}
cfg.contexts = cfg.contexts || {};
cfg.contexts[name] = {
baseUrl: opts.url,
apiKey,
description: opts.description || undefined,
};
saveContexts(cfg);
process.stdout.write(`Added context '${name}'\n`);
});
ctx
.command("use <name>")
.description("Switch active context")
.action((name) => {
const cfg = loadContexts();
if (!cfg.contexts?.[name]) {
process.stderr.write(`No such context: ${name}\n`);
process.exit(2);
}
cfg.currentContext = name;
saveContexts(cfg);
process.stdout.write(`Active context: ${name}\n`);
});
ctx
.command("current")
.description("Show current active context name")
.action(() => {
const cfg = loadContexts();
process.stdout.write(`${cfg.currentContext || "default"}\n`);
});
ctx
.command("show <name>")
.description("Show context details")
.action((name, opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const cfg = loadContexts();
const c = cfg.contexts?.[name];
if (!c) {
process.stderr.write(`No such context: ${name}\n`);
process.exit(2);
}
const display = {
name,
baseUrl: c.baseUrl,
apiKey: maskKey(c.apiKey),
description: c.description,
};
emit(display, globalOpts);
});
ctx
.command("remove <name>")
.description("Remove a context")
.option("--yes", "Skip confirmation")
.action(async (name, opts) => {
if (!opts.yes) {
const ok = await confirm(`Remove context '${name}'?`);
if (!ok) {
process.stdout.write("Cancelled.\n");
return;
}
}
const cfg = loadContexts();
if (!cfg.contexts?.[name]) {
process.stderr.write(`No such context: ${name}\n`);
process.exit(2);
}
if (name === "default") {
process.stderr.write("Cannot remove default context.\n");
process.exit(2);
}
delete cfg.contexts[name];
if (cfg.currentContext === name) cfg.currentContext = "default";
saveContexts(cfg);
process.stdout.write(`Removed context '${name}'\n`);
});
ctx
.command("rename <old> <new>")
.description("Rename a context")
.action((oldName, newName) => {
const cfg = loadContexts();
if (!cfg.contexts?.[oldName]) {
process.stderr.write(`No such context: ${oldName}\n`);
process.exit(2);
}
if (cfg.contexts[newName]) {
process.stderr.write(`Context '${newName}' already exists.\n`);
process.exit(2);
}
cfg.contexts[newName] = cfg.contexts[oldName];
delete cfg.contexts[oldName];
if (cfg.currentContext === oldName) cfg.currentContext = newName;
saveContexts(cfg);
process.stdout.write(`Renamed '${oldName}' → '${newName}'\n`);
});
ctx
.command("export")
.description("Export contexts to JSON")
.option("--out <path>", "Output file path (default: stdout)")
.option("--no-secrets", "Omit API keys from export")
.action(async (opts, cmd) => {
const cfg = loadContexts();
const out = JSON.parse(JSON.stringify(cfg));
if (opts.noSecrets) {
for (const c of Object.values(out.contexts || {})) {
c.apiKey = null;
}
}
const json = JSON.stringify(out, null, 2);
if (opts.out) {
const { writeFileSync } = await import("node:fs");
writeFileSync(opts.out, json);
process.stdout.write(`Exported to ${opts.out}\n`);
} else {
process.stdout.write(json + "\n");
}
});
ctx
.command("import <file>")
.description("Import contexts from a JSON file")
.option("--merge", "Merge with existing contexts (default: overwrite)")
.action(async (file, opts) => {
const { readFileSync } = await import("node:fs");
let imported;
try {
imported = JSON.parse(readFileSync(file, "utf8"));
} catch (e) {
process.stderr.write(
`Cannot read ${file}: ${e instanceof Error ? e.message : String(e)}\n`
);
process.exit(1);
}
const cfg = opts.merge
? loadContexts()
: { version: 1, currentContext: "default", contexts: {} };
const incoming = imported.contexts || {};
let count = 0;
for (const [name, raw] of Object.entries(incoming)) {
if (typeof name !== "string" || !name) continue;
const c = raw && typeof raw === "object" ? /** @type {Record<string,unknown>} */ (raw) : {};
cfg.contexts[name] = {
baseUrl: typeof c.baseUrl === "string" ? c.baseUrl : "http://localhost:20128",
apiKey: typeof c.apiKey === "string" ? c.apiKey : null,
description: typeof c.description === "string" ? c.description : undefined,
};
count++;
}
if (!opts.merge && typeof imported.currentContext === "string") {
cfg.currentContext = imported.currentContext;
}
saveContexts(cfg);
process.stdout.write(`Imported ${count} context(s)\n`);
});
}

144
bin/cli/commands/cost.mjs Normal file
View File

@@ -0,0 +1,144 @@
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
const costSchema = [
{ key: "group", header: "Group", width: 30 },
{ key: "requests", header: "Reqs", formatter: (v) => (v != null ? v.toLocaleString() : "0") },
{ key: "tokensIn", header: "Tokens In", formatter: fmtTokens },
{ key: "tokensOut", header: "Tokens Out", formatter: fmtTokens },
{ key: "costUsd", header: "Cost (USD)", formatter: (v) => (v ? `$${v.toFixed(4)}` : "$0.0000") },
{
key: "costPct",
header: "% of Total",
formatter: (v) => (v != null ? `${v.toFixed(1)}%` : "-"),
},
];
function fmtTokens(v) {
if (!v) return "0";
if (v > 1e6) return `${(v / 1e6).toFixed(1)}M`;
if (v > 1e3) return `${(v / 1e3).toFixed(1)}K`;
return String(v);
}
export function registerCost(program) {
program
.command("cost")
.description(t("cost.description"))
.option("--period <range>", t("cost.period"), "30d")
.option("--since <date>", t("cost.since"))
.option("--until <date>", t("cost.until"))
.option("--group-by <field>", t("cost.group_by"), "provider")
.option("--api-key <key>", t("cost.api_key_filter"))
.option("--limit <n>", t("cost.limit"), parseInt, 100)
.action(runCostCommand);
}
export async function runCostCommand(opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const params = buildParams(opts);
const res = await apiFetch(`/api/usage/analytics?${params}`, {
timeout: globalOpts.timeout,
acceptNotOk: true,
});
if (!res.ok) {
if (res.status === 401 || res.status === 403) {
process.stderr.write(t("common.authRequired") + "\n");
} else if (res.status >= 500) {
process.stderr.write(t("common.serverOffline") + "\n");
} else {
process.stderr.write(t("common.error", { message: `HTTP ${res.status}` }) + "\n");
}
process.exit(res.exitCode ?? 1);
}
const data = await res.json();
const rows = aggregateByGroup(data, opts.groupBy ?? "provider", opts.limit ?? 100);
emit(rows, globalOpts, costSchema);
if (!globalOpts.quiet && globalOpts.output !== "json" && globalOpts.output !== "jsonl") {
const total = rows.reduce((s, r) => s + (r.costUsd ?? 0), 0);
process.stderr.write(
`\nTotal: $${total.toFixed(4)} across ${rows.length} ${opts.groupBy ?? "provider"}(s)\n`
);
}
}
function buildParams(opts) {
const p = new URLSearchParams();
if (opts.since || opts.until) {
if (opts.since) p.set("startDate", opts.since);
if (opts.until) p.set("endDate", opts.until);
} else {
p.set("range", opts.period ?? "30d");
}
if (opts.apiKey) p.set("apiKeyIds", opts.apiKey);
return p.toString();
}
function aggregateByGroup(data, groupBy, limit) {
const source = pickSource(data, groupBy);
if (!Array.isArray(source)) return [];
const totalCost = source.reduce((s, r) => s + toNum(r.totalCost ?? r.cost ?? r.costUsd), 0);
const rows = source.map((r) => {
const costUsd = toNum(r.totalCost ?? r.cost ?? r.costUsd);
return {
group: groupLabel(r, groupBy),
requests: toNum(r.totalRequests ?? r.requests ?? r.count),
tokensIn: toNum(r.totalTokensIn ?? r.tokensIn ?? r.promptTokens),
tokensOut: toNum(r.totalTokensOut ?? r.tokensOut ?? r.completionTokens),
costUsd,
costPct: totalCost > 0 ? (costUsd / totalCost) * 100 : 0,
};
});
rows.sort((a, b) => b.costUsd - a.costUsd);
return rows.slice(0, limit);
}
function pickSource(data, groupBy) {
switch (groupBy) {
case "model":
return data.byModel ?? data.models ?? [];
case "combo":
return data.byCombo ?? data.combos ?? [];
case "api-key":
case "apiKey":
return data.byApiKey ?? data.apiKeys ?? [];
case "day":
return data.byDay ?? data.daily ?? data.trend ?? [];
default:
return data.byProvider ?? data.providers ?? [];
}
}
function groupLabel(row, groupBy) {
switch (groupBy) {
case "model":
return row.model ?? row.modelId ?? String(row.group ?? "");
case "combo":
return row.comboName ?? row.combo ?? row.name ?? String(row.group ?? "");
case "api-key":
case "apiKey":
return row.keyName ?? row.apiKey ?? row.label ?? String(row.group ?? "");
case "day":
return row.date ?? row.day ?? String(row.group ?? "");
default:
return row.provider ?? row.providerId ?? String(row.group ?? "");
}
}
function toNum(v) {
if (typeof v === "number" && Number.isFinite(v)) return v;
if (typeof v === "string") {
const n = Number(v);
return Number.isFinite(n) ? n : 0;
}
return 0;
}

View File

@@ -0,0 +1,65 @@
import { execFile } from "node:child_process";
import { t } from "../i18n.mjs";
export function registerDashboard(program) {
program
.command("dashboard")
.description(t("dashboard.description"))
.option("--url", t("dashboard.urlOnly"))
.option("--port <port>", "Port the server is running on", "20128")
.option("--tui", t("dashboard.tui") || "Open interactive TUI dashboard (terminal UI)")
.action(async (opts, cmd) => {
if (opts.tui) {
const globalOpts = cmd.optsWithGlobals();
const port = opts.port ? parseInt(String(opts.port), 10) : 20128;
const baseUrl = globalOpts.baseUrl ?? `http://localhost:${port}`;
const apiKey = globalOpts.apiKey ?? null;
const { startInteractiveTui } = await import("../tui/Dashboard.jsx");
await startInteractiveTui({ port, baseUrl, apiKey });
return;
}
const exitCode = await runDashboardCommand(opts);
if (exitCode !== 0) process.exit(exitCode);
});
}
export async function runDashboardCommand(opts = {}) {
const port = opts.port ? parseInt(String(opts.port), 10) : 20128;
const dashboardUrl = `http://localhost:${port}`;
if (opts.url) {
console.log(dashboardUrl);
return 0;
}
console.log(t("dashboard.opening", { url: dashboardUrl }));
try {
const open = await import("open");
await open.default(dashboardUrl);
} catch {
await openFallback(dashboardUrl);
}
return 0;
}
function openFallback(url) {
return new Promise((resolve) => {
const { platform } = process;
let cmd, args;
if (platform === "darwin") {
cmd = "open";
args = [url];
} else if (platform === "win32") {
cmd = "cmd";
args = ["/c", "start", "", url];
} else {
cmd = "xdg-open";
args = [url];
}
execFile(cmd, args, { stdio: "ignore" }, () => resolve());
});
}

View File

@@ -4,9 +4,9 @@ import os from "node:os";
import path from "node:path";
import { createDecipheriv, scryptSync } from "node:crypto";
import { pathToFileURL } from "node:url";
import { parseArgs, getStringFlag, hasFlag } from "../args.mjs";
import { resolveDataDir, resolveStoragePath } from "../data-dir.mjs";
import { printHeading } from "../io.mjs";
import { t } from "../i18n.mjs";
const STATIC_SALT = "omniroute-field-encryption-v1";
const KEY_LENGTH = 32;
@@ -181,8 +181,11 @@ function decryptCredentialSample(value, key) {
const [ivHex, encryptedHex, authTagHex] = body.split(":");
if (!ivHex || !encryptedHex || !authTagHex) throw new Error("Malformed encrypted value");
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(ivHex, "hex"));
decipher.setAuthTag(Buffer.from(authTagHex, "hex"));
const authTagBuf = Buffer.from(authTagHex, "hex");
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(ivHex, "hex"), {
authTagLength: authTagBuf.length,
});
decipher.setAuthTag(authTagBuf);
let decrypted = decipher.update(encryptedHex, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
@@ -360,7 +363,7 @@ async function checkNativeBinary(rootDir) {
try {
const { isNativeBinaryCompatible } = await import(
pathToFileURL(path.join(rootDir, "scripts", "native-binary-compat.mjs")).href
pathToFileURL(path.join(rootDir, "scripts", "build", "native-binary-compat.mjs")).href
);
const compatible = isNativeBinaryCompatible(binaryPath);
if (!compatible) {
@@ -487,25 +490,6 @@ export async function collectDoctorChecks(context = {}, options = {}) {
};
}
function printDoctorHelp() {
console.log(`
Usage:
omniroute doctor
omniroute doctor --json
omniroute doctor --no-liveness
omniroute doctor --host 0.0.0.0
Options:
--json Print machine-readable JSON
--no-liveness Skip HTTP health endpoint probing
--host <host> Host for server liveness probing (default: 127.0.0.1)
--liveness-url <url> Full health endpoint URL override
Checks:
config, database, storage/encryption, ports, Node runtime, native binary, memory, server liveness, CLI tools
`);
}
function printCheck(check) {
const label = check.status.toUpperCase().padEnd(4);
const color =
@@ -513,20 +497,31 @@ function printCheck(check) {
console.log(`${color}${label}\x1b[0m ${check.name}: ${check.message}`);
}
export async function runDoctorCommand(argv, context = {}) {
const { flags } = parseArgs(argv);
if (hasFlag(flags, "help") || hasFlag(flags, "h")) {
printDoctorHelp();
return 0;
}
export function registerDoctor(program) {
program
.command("doctor")
.description(t("doctor.title"))
.option("--no-liveness", "Skip HTTP health endpoint probing")
.option("--host <host>", "Host for server liveness probing", "127.0.0.1")
.option("--liveness-url <url>", "Full health endpoint URL override")
.action(async (opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const exitCode = await runDoctorCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
}
export async function runDoctorCommand(opts = {}, context = {}) {
const isJson = (opts.output ?? "table") === "json";
const skipLiveness = !(opts.liveness ?? true);
const result = await collectDoctorChecks(context, {
skipLiveness: hasFlag(flags, "no-liveness"),
livenessHost: getStringFlag(flags, "host"),
livenessUrl: getStringFlag(flags, "liveness-url"),
skipLiveness,
livenessHost: opts.host,
livenessUrl: opts.livenessUrl,
});
if (hasFlag(flags, "json")) {
if (isJson) {
console.log(JSON.stringify(result, null, 2));
} else {
printHeading("OmniRoute Doctor");

100
bin/cli/commands/env.mjs Normal file
View File

@@ -0,0 +1,100 @@
import { t } from "../i18n.mjs";
const OMNIROUTE_ENV_VARS = [
"PORT",
"API_PORT",
"DASHBOARD_PORT",
"DATA_DIR",
"REQUIRE_API_KEY",
"LOG_LEVEL",
"NODE_ENV",
"REQUEST_TIMEOUT_MS",
"ENABLE_SOCKS5_PROXY",
"OMNIROUTE_API_KEY",
"OMNIROUTE_BASE_URL",
"OMNIROUTE_HTTP_TIMEOUT_MS",
];
const ENV_DEFAULTS = {
PORT: "20128",
DASHBOARD_PORT: "20128",
DATA_DIR: "~/.omniroute",
NODE_ENV: "production",
};
export function registerEnv(program) {
const env = program.command("env").description("Show and manage environment variables");
env
.command("show")
.alias("list")
.description("Show current environment variables")
.option("--json", "Output as JSON")
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
await runEnvShowCommand({ ...opts, output: globalOpts.output });
});
env
.command("get <key>")
.description("Get a single environment variable")
.action(async (key) => {
await runEnvGetCommand(key);
});
env
.command("set <key> <value>")
.description("Set an environment variable (current session only)")
.action(async (key, value) => {
await runEnvSetCommand(key, value);
});
}
export async function runEnvShowCommand(opts = {}) {
const current = {};
for (const key of OMNIROUTE_ENV_VARS) {
if (process.env[key] !== undefined) current[key] = process.env[key];
}
if (opts.json || opts.output === "json") {
console.log(JSON.stringify({ current, defaults: ENV_DEFAULTS }, null, 2));
return 0;
}
console.log("\n\x1b[1m\x1b[36mEnvironment Variables\x1b[0m\n");
console.log(" Current:");
if (Object.keys(current).length === 0) {
console.log("\x1b[2m (none set)\x1b[0m");
} else {
for (const [key, value] of Object.entries(current)) {
const display = key.includes("KEY") || key.includes("SECRET") ? "***" : value;
console.log(`\x1b[2m ${key.padEnd(28)} ${display}\x1b[0m`);
}
}
console.log("\n Defaults:");
for (const [key, value] of Object.entries(ENV_DEFAULTS)) {
console.log(` ${key.padEnd(28)} ${value}`);
}
return 0;
}
export async function runEnvGetCommand(key) {
if (!key) {
console.error("Key is required. Usage: omniroute env get <key>");
return 1;
}
console.log(process.env[key] || "");
return 0;
}
export async function runEnvSetCommand(key, value) {
if (!key || value === undefined) {
console.error("Usage: omniroute env set <key> <value>");
return 1;
}
process.env[key] = String(value);
console.log(`\x1b[33m ${key}=${value} (temporary — current session only)\x1b[0m`);
return 0;
}

278
bin/cli/commands/eval.mjs Normal file
View File

@@ -0,0 +1,278 @@
import { readFileSync } from "node:fs";
import { setTimeout as sleep } from "node:timers/promises";
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
function truncate(v, len = 30) {
if (v == null) return "-";
const s = String(v);
return s.length > len ? s.slice(0, len - 1) + "…" : s;
}
function fmtTs(v) {
if (!v) return "-";
try {
return new Date(v).toLocaleString();
} catch {
return String(v);
}
}
const suiteSchema = [
{ key: "id", header: "Suite ID", width: 22 },
{ key: "name", header: "Name", width: 30 },
{ key: "samples", header: "Samples" },
{ key: "rubric", header: "Rubric", width: 16 },
{ key: "updatedAt", header: "Updated", formatter: fmtTs },
];
const runSchema = [
{ key: "id", header: "Run ID", width: 22 },
{ key: "suiteId", header: "Suite", width: 18 },
{ key: "status", header: "Status", width: 12 },
{ key: "model", header: "Model", width: 25 },
{ key: "score", header: "Score", formatter: (v) => (v != null ? v.toFixed(3) : "-") },
{
key: "duration",
header: "Duration",
formatter: (v) => (v != null ? `${(v / 1000).toFixed(1)}s` : "-"),
},
{ key: "startedAt", header: "Started", formatter: fmtTs },
];
const sampleSchema = [
{ key: "id", header: "Sample", width: 14 },
{ key: "score", header: "Score", formatter: (v) => (v != null ? v.toFixed(2) : "-") },
{ key: "passed", header: "✓", formatter: (v) => (v ? "✓" : "✗") },
{ key: "input", header: "Input", width: 30, formatter: truncate },
{ key: "output", header: "Output", width: 30, formatter: truncate },
];
async function confirm(q) {
return new Promise((resolve) => {
process.stdout.write(`${q} (yes/no) `);
process.stdin.setEncoding("utf8");
process.stdin.once("data", (c) => resolve(c.toString().trim().toLowerCase().startsWith("y")));
});
}
async function watchRun(runId, globalOpts) {
let lastStatus = "";
while (true) {
await sleep(3000);
const res = await apiFetch(`/api/evals/${runId}`);
if (!res.ok) continue;
const r = await res.json();
if (r.status !== lastStatus) {
const done = r.progress?.completed ?? 0;
const total = r.progress?.total ?? "?";
process.stderr.write(`[${new Date().toISOString()}] ${r.status}${done}/${total}\n`);
lastStatus = r.status;
}
if (["completed", "failed", "cancelled"].includes(r.status)) {
emit(r, globalOpts, runSchema);
return;
}
}
}
function renderScorecard(data) {
const score = data.score ?? data.overallScore ?? null;
const passed = data.passed ?? data.summary?.passed ?? null;
const total = data.total ?? data.summary?.total ?? null;
process.stdout.write("\n=== Scorecard ===\n");
if (score != null) process.stdout.write(`Overall score: ${(score * 100).toFixed(1)}%\n`);
if (passed != null && total != null) {
process.stdout.write(`Passed: ${passed}/${total}\n`);
const bar = "█".repeat(Math.round((passed / total) * 20)).padEnd(20, "░");
process.stdout.write(`[${bar}] ${((passed / total) * 100).toFixed(0)}%\n`);
}
const metrics = data.metrics ?? data.breakdown ?? {};
for (const [k, v] of Object.entries(metrics)) {
process.stdout.write(` ${k}: ${typeof v === "number" ? v.toFixed(3) : v}\n`);
}
process.stdout.write("\n");
}
export async function runEvalSuitesList(opts, cmd) {
const res = await apiFetch("/api/evals/suites");
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.items ?? data, cmd.optsWithGlobals(), suiteSchema);
}
export async function runEvalSuitesGet(id, opts, cmd) {
const res = await apiFetch(`/api/evals/suites/${id}`);
if (!res.ok) {
process.stderr.write(`Not found: ${id}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
}
export async function runEvalSuitesCreate(opts, cmd) {
if (!opts.file) {
process.stderr.write("--file required\n");
process.exit(2);
}
const body = JSON.parse(readFileSync(opts.file, "utf8"));
const res = await apiFetch("/api/evals/suites", { method: "POST", body });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
}
export async function runEvalRun(suiteId, opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const body = {
suiteId,
model: opts.model ?? "auto",
...(opts.combo ? { combo: opts.combo } : {}),
concurrency: opts.concurrency ?? 4,
...(opts.tag ? { tag: opts.tag } : {}),
};
const res = await apiFetch("/api/evals", { method: "POST", body });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const run = await res.json();
emit(run, globalOpts, runSchema);
if (opts.watch) {
if (process.stdout.isTTY) {
const { startEvalWatchTui } = await import("../tui/EvalWatch.jsx");
await startEvalWatchTui({
runId: run.id,
suiteId: opts.suite,
baseUrl: globalOpts.baseUrl ?? "http://localhost:20128",
apiKey: globalOpts.apiKey ?? process.env.OMNIROUTE_API_KEY,
});
} else {
process.stderr.write("\nWatching run... (Ctrl+C to detach)\n");
await watchRun(run.id, globalOpts);
}
}
}
export async function runEvalList(opts, cmd) {
const params = new URLSearchParams({ limit: String(opts.limit ?? 50) });
if (opts.suite) params.set("suiteId", opts.suite);
if (opts.status) params.set("status", opts.status);
if (opts.since) params.set("since", opts.since);
const res = await apiFetch(`/api/evals?${params}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.items ?? data, cmd.optsWithGlobals(), runSchema);
}
export async function runEvalGet(id, opts, cmd) {
const res = await apiFetch(`/api/evals/${id}`);
if (!res.ok) {
process.stderr.write(`Not found: ${id}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
}
export async function runEvalResults(id, opts, cmd) {
const params = new URLSearchParams();
if (opts.failed) params.set("filter", "failed");
const res = await apiFetch(`/api/evals/${id}?${params}`);
if (!res.ok) {
process.stderr.write(`Not found: ${id}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.samples ?? data.results ?? [], cmd.optsWithGlobals(), sampleSchema);
}
export async function runEvalCancel(id, opts, cmd) {
if (!opts.yes) {
const ok = await confirm(`Cancel run ${id}?`);
if (!ok) return;
}
const res = await apiFetch(`/api/evals/${id}`, { method: "POST", body: { op: "cancel" } });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
process.stdout.write("Cancelled\n");
}
export async function runEvalScorecard(id, opts, cmd) {
const res = await apiFetch(`/api/evals/${id}?scorecard=true`);
if (!res.ok) {
process.stderr.write(`Not found: ${id}\n`);
process.exit(1);
}
const data = await res.json();
const globalOpts = cmd.optsWithGlobals();
if (globalOpts.output === "json") {
emit(data, globalOpts);
} else {
renderScorecard(data);
}
}
export function registerEval(program) {
const evalCmd = program.command("eval").description(t("eval.description"));
const suites = evalCmd.command("suites").description(t("eval.suites.description"));
suites.command("list").description(t("eval.suites.list.description")).action(runEvalSuitesList);
suites
.command("get <suiteId>")
.description(t("eval.suites.get.description"))
.action(runEvalSuitesGet);
suites
.command("create")
.description(t("eval.suites.create.description"))
.option("--file <path>", t("eval.suites.create.file"))
.action(runEvalSuitesCreate);
evalCmd
.command("run <suiteId>")
.description(t("eval.run.description"))
.option("-m, --model <id>", t("eval.run.model"), "auto")
.option("--combo <name>", t("eval.run.combo"))
.option("--concurrency <n>", t("eval.run.concurrency"), parseInt, 4)
.option("--tag <tag>", t("eval.run.tag"))
.option("--watch", t("eval.run.watch"))
.action(runEvalRun);
evalCmd
.command("list")
.description(t("eval.list.description"))
.option("--suite <id>", t("eval.list.suite"))
.option("--status <s>", t("eval.list.status"))
.option("--since <ts>", t("eval.list.since"))
.option("--limit <n>", t("eval.list.limit"), parseInt, 50)
.action(runEvalList);
evalCmd.command("get <runId>").description(t("eval.get.description")).action(runEvalGet);
evalCmd
.command("results <runId>")
.description(t("eval.results.description"))
.option("--failed", t("eval.results.failed"))
.action(runEvalResults);
evalCmd
.command("cancel <runId>")
.description(t("eval.cancel.description"))
.option("--yes", t("eval.cancel.yes"))
.action(runEvalCancel);
evalCmd
.command("scorecard <runId>")
.description(t("eval.scorecard.description"))
.action(runEvalScorecard);
}

144
bin/cli/commands/files.mjs Normal file
View File

@@ -0,0 +1,144 @@
import { createReadStream, readFileSync, statSync, writeFileSync } from "node:fs";
import { basename } from "node:path";
import { createInterface } from "node:readline";
import { apiFetch, getBaseUrl } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
function fmtTs(v) {
if (!v) return "-";
return new Date(typeof v === "number" ? v * 1000 : v).toLocaleString();
}
function fmtBytes(n) {
if (n == null) return "-";
if (n < 1024) return `${n} B`;
if (n < 1024 ** 2) return `${(n / 1024).toFixed(1)} KB`;
if (n < 1024 ** 3) return `${(n / 1024 ** 2).toFixed(1)} MB`;
return `${(n / 1024 ** 3).toFixed(2)} GB`;
}
async function confirm(q) {
const rl = createInterface({ input: process.stdin, output: process.stdout });
return new Promise((resolve) => {
rl.question(`${q} [y/N] `, (a) => {
rl.close();
resolve(a.trim().toLowerCase() === "y");
});
});
}
function authHeaders(opts) {
const h = { accept: "application/json" };
if (opts.apiKey) h["Authorization"] = `Bearer ${opts.apiKey}`;
return h;
}
const fileSchema = [
{ key: "id", header: "File ID", width: 30 },
{ key: "filename", header: "Filename", width: 35 },
{ key: "purpose", header: "Purpose", width: 14 },
{ key: "bytes", header: "Bytes", formatter: fmtBytes },
{ key: "created_at", header: "Created", formatter: fmtTs },
{ key: "status", header: "Status" },
];
export function registerFiles(program) {
const files = program.command("files").description(t("files.description"));
files
.command("list")
.option("--purpose <p>", t("files.list.purpose"))
.option("--limit <n>", t("files.list.limit"), parseInt, 100)
.action(async (opts, cmd) => {
const params = new URLSearchParams({ limit: String(opts.limit) });
if (opts.purpose) params.set("purpose", opts.purpose);
const res = await apiFetch(`/v1/files?${params}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.data ?? data.items ?? data, cmd.optsWithGlobals(), fileSchema);
});
files
.command("get <fileId>")
.description(t("files.get.description"))
.action(async (id, opts, cmd) => {
const res = await apiFetch(`/v1/files/${id}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
files
.command("upload <path>")
.description(t("files.upload.description"))
.requiredOption("--purpose <p>", t("files.upload.purpose"))
.action(async (filePath, opts, cmd) => {
const stat = statSync(filePath);
if (stat.size > 100 * 1024 * 1024) {
process.stderr.write(
`Warning: file is ${fmtBytes(stat.size)} (${stat.size > 500e6 ? "very " : ""}large)\n`
);
}
const globalOpts = cmd.optsWithGlobals();
const form = new FormData();
form.append("purpose", opts.purpose);
form.append("file", new Blob([readFileSync(filePath)]), basename(filePath));
const res = await fetch(`${getBaseUrl(globalOpts)}/v1/files`, {
method: "POST",
headers: authHeaders(globalOpts),
body: form,
});
if (!res.ok) {
process.stderr.write(`Upload failed: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), globalOpts);
});
files
.command("content <fileId>")
.description(t("files.content.description"))
.option("--out <path>", t("files.content.out"))
.action(async (id, opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const res = await fetch(`${getBaseUrl(globalOpts)}/v1/files/${id}/content`, {
headers: authHeaders(globalOpts),
});
if (!res.ok) {
process.stderr.write(`HTTP ${res.status}\n`);
process.exit(1);
}
if (opts.out) {
const buf = Buffer.from(await res.arrayBuffer());
writeFileSync(opts.out, buf);
process.stdout.write(`Saved ${buf.length} bytes to ${opts.out}\n`);
} else {
process.stdout.write(await res.text());
}
});
files
.command("delete <fileId>")
.option("--yes", t("files.delete.yes"))
.action(async (id, opts, cmd) => {
if (!opts.yes) {
const ok = await confirm(`Delete file ${id}?`);
if (!ok) return;
}
const res = await apiFetch(`/v1/files/${id}`, { method: "DELETE" });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
process.stdout.write("Deleted\n");
});
}
export { fmtBytes };

123
bin/cli/commands/health.mjs Normal file
View File

@@ -0,0 +1,123 @@
import { apiFetch, isServerUp } from "../api.mjs";
import { t } from "../i18n.mjs";
export function registerHealth(program) {
const health = program
.command("health")
.description(t("health.description"))
.option("-v, --verbose", "Show extended info (memory, breakers)")
.option("--json", "Output as JSON")
.option("--alerts-only", "Show only components with alerts")
.action(async (opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const exitCode = await runHealthCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
health
.command("components")
.description("List health components and their status")
.option("--alerts-only", "Show only components with alerts")
.action(async (opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const exitCode = await runHealthComponentsCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
health
.command("watch")
.description("Live dashboard — refresh every N seconds")
.option("--interval <s>", "Refresh interval in seconds", "5")
.action(async (opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const interval = parseInt(opts.interval, 10) * 1000;
process.stdout.write("\x1B[2J\x1B[0f");
while (true) {
process.stdout.write("\x1B[0f");
await runHealthCommand({ ...globalOpts, verbose: true });
await new Promise((r) => setTimeout(r, interval));
}
});
}
export async function runHealthCommand(opts = {}) {
const serverUp = await isServerUp();
if (!serverUp) {
console.error(t("health.noServer"));
return 1;
}
try {
const res = await apiFetch("/api/health", { retry: false, timeout: 5000, acceptNotOk: true });
if (!res.ok) {
console.error(t("common.error", { message: `HTTP ${res.status}` }));
return 1;
}
const health = await res.json();
if (opts.json || opts.output === "json") {
console.log(JSON.stringify(health, null, 2));
return 0;
}
console.log(`\n\x1b[1m\x1b[36m${t("health.title")}\x1b[0m\n`);
console.log(t("health.status", { status: "\x1b[32mhealthy\x1b[0m" }));
if (health.uptime) console.log(t("health.uptime", { uptime: health.uptime }));
if (health.version) console.log(` Version: ${health.version}`);
if (health.requests !== undefined) {
console.log(t("health.requests", { count: health.requests }));
}
if (health.breakers && opts.verbose) {
console.log("\n \x1b[1mCircuit Breakers\x1b[0m");
for (const [name, status] of Object.entries(health.breakers)) {
const state =
status.state === "closed" ? "\x1b[32m● closed\x1b[0m" : "\x1b[33m○ open\x1b[0m";
console.log(` ${name.padEnd(20)} ${state}`);
}
}
if (health.cache && opts.verbose) {
console.log("\n \x1b[1mCache\x1b[0m");
console.log(` Semantic hits: ${health.cache.semanticHits || 0}`);
console.log(` Signature hits: ${health.cache.signatureHits || 0}`);
}
if (opts.verbose && health.memory) {
console.log("\n \x1b[1mMemory\x1b[0m");
console.log(` RSS: ${health.memory.rss || "N/A"}`);
console.log(` Heap used: ${health.memory.heapUsed || "N/A"}`);
}
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runHealthComponentsCommand(opts = {}) {
try {
const res = await apiFetch("/api/health", { retry: false, timeout: 5000, acceptNotOk: true });
if (!res.ok) {
console.error(`HTTP ${res.status}`);
return 1;
}
const health = await res.json();
const components = health.components || health.breakers || {};
for (const [name, info] of Object.entries(components)) {
const status =
typeof info === "object" ? info.state || info.status || "unknown" : String(info);
const isAlert = status !== "closed" && status !== "ok" && status !== "healthy";
if (opts.alertsOnly && !isAlert) continue;
const icon = isAlert ? "\x1b[33m⚠\x1b[0m" : "\x1b[32m✓\x1b[0m";
console.log(` ${icon} ${name.padEnd(24)} ${status}`);
}
return 0;
} catch (err) {
console.error(err instanceof Error ? err.message : String(err));
return 1;
}
}

599
bin/cli/commands/keys.mjs Normal file
View File

@@ -0,0 +1,599 @@
import { printHeading } from "../io.mjs";
import {
ensureProviderSchema,
getProviderApiKey,
listProviderConnections,
removeProviderConnectionByProvider,
upsertApiKeyProviderConnection,
} from "../provider-store.mjs";
import { openOmniRouteDb } from "../sqlite.mjs";
import { loadAvailableProviders } from "../provider-catalog.mjs";
import { apiFetch, isServerUp } from "../api.mjs";
import { t } from "../i18n.mjs";
function getValidProviderIds() {
try {
return new Set(loadAvailableProviders().map((p) => p.id));
} catch {
return null;
}
}
function maskKey(raw) {
if (!raw || raw.length <= 8) return "***";
return raw.slice(0, 6) + "***" + raw.slice(-4);
}
export function registerKeys(program) {
const keys = program.command("keys").description(t("keys.title"));
keys
.command("add <provider> [apiKey]")
.description(t("keys.addDescription"))
.option("--stdin", t("keys.stdinOpt"))
.action(async (provider, apiKey, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runKeysAddCommand(provider, apiKey, { ...opts, ...globalOpts });
if (exitCode !== 0) process.exit(exitCode);
});
keys
.command("list")
.description(t("keys.listDescription"))
.option("--json", t("common.jsonOpt"))
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runKeysListCommand({ ...opts, ...globalOpts });
if (exitCode !== 0) process.exit(exitCode);
});
keys
.command("remove <provider>")
.description(t("keys.removeDescription"))
.option("--yes", t("common.yesOpt"))
.action(async (provider, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runKeysRemoveCommand(provider, { ...opts, ...globalOpts });
if (exitCode !== 0) process.exit(exitCode);
});
keys
.command("regenerate <id>")
.description(t("keys.regenerateDescription"))
.option("--yes", t("common.yesOpt"))
.action(async (id, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runKeysRegenerateCommand(id, { ...opts, ...globalOpts });
if (exitCode !== 0) process.exit(exitCode);
});
keys
.command("revoke <id>")
.description(t("keys.revokeDescription"))
.option("--yes", t("common.yesOpt"))
.action(async (id, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runKeysRevokeCommand(id, { ...opts, ...globalOpts });
if (exitCode !== 0) process.exit(exitCode);
});
keys
.command("reveal <id>")
.description(t("keys.revealDescription"))
.action(async (id, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runKeysRevealCommand(id, { ...opts, ...globalOpts });
if (exitCode !== 0) process.exit(exitCode);
});
keys
.command("usage <id>")
.description(t("keys.usageDescription"))
.option("--limit <n>", t("keys.usageLimitOpt"), "20")
.action(async (id, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runKeysUsageCommand(id, { ...opts, ...globalOpts });
if (exitCode !== 0) process.exit(exitCode);
});
const policy = keys.command("policy").description(t("keys.policy.title"));
policy
.command("show <id>")
.description(t("keys.policy.showDescription"))
.action(async (id, opts, cmd) => {
const globalOpts = cmd.parent.parent.optsWithGlobals();
const exitCode = await runKeysPolicyShowCommand(id, { ...opts, ...globalOpts });
if (exitCode !== 0) process.exit(exitCode);
});
policy
.command("set <id>")
.description(t("keys.policy.setDescription"))
.option("--rate-limit <n>", t("keys.policy.rateLimitOpt"), parseInt)
.option("--max-cost <n>", t("keys.policy.maxCostOpt"), parseFloat)
.option("--allowed-models <list>", t("keys.policy.allowedModelsOpt"))
.action(async (id, opts, cmd) => {
const globalOpts = cmd.parent.parent.optsWithGlobals();
const exitCode = await runKeysPolicySetCommand(id, { ...opts, ...globalOpts });
if (exitCode !== 0) process.exit(exitCode);
});
const expiration = keys.command("expiration").description(t("keys.expiration.title"));
expiration
.command("list")
.description(t("keys.expiration.listDescription"))
.option("--days <n>", t("keys.expiration.daysOpt"), "30")
.option("--json", t("common.jsonOpt"))
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.parent.optsWithGlobals();
const exitCode = await runKeysExpirationListCommand({ ...opts, ...globalOpts });
if (exitCode !== 0) process.exit(exitCode);
});
keys
.command("rotate <id>")
.description(t("keys.rotateDescription"))
.option("--grace-period <ms>", t("keys.graceOpt"), "60000")
.option("--yes", t("common.yesOpt"))
.action(async (id, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runKeysRotateCommand(id, { ...opts, ...globalOpts });
if (exitCode !== 0) process.exit(exitCode);
});
}
export async function runKeysAddCommand(provider, apiKey, opts = {}) {
if (!provider) {
console.error(t("keys.providerRequired"));
return 1;
}
let key = apiKey;
if (opts.stdin) {
key = await readStdin();
if (!key) {
console.error(t("keys.stdinEmpty"));
return 1;
}
}
if (!key) {
console.error(t("keys.keyRequired"));
return 1;
}
const providerLower = provider.toLowerCase();
const validIds = getValidProviderIds();
if (validIds && !validIds.has(providerLower)) {
console.error(t("keys.unknownProvider", { provider: providerLower }));
return 1;
}
const serverUp = await isServerUp();
if (serverUp) {
try {
const res = await apiFetch("/api/v1/providers/keys", {
method: "POST",
body: { provider: providerLower, apiKey: key },
retry: false,
acceptNotOk: true,
});
if (res.ok) {
console.log(t("keys.added", { provider: providerLower }));
return 0;
}
if (res.status >= 400 && res.status < 500) {
console.error(t("common.error", { message: `HTTP ${res.status}` }));
return 1;
}
} catch {}
}
const { db } = await openOmniRouteDb();
try {
const existing = listProviderConnections(db).find(
(c) => c.provider === providerLower && c.authType === "apikey"
);
upsertApiKeyProviderConnection(db, {
provider: providerLower,
name: existing?.name || providerLower,
apiKey: key,
});
console.log(t("keys.added", { provider: providerLower }));
return 0;
} finally {
db.close();
}
}
export async function runKeysListCommand(opts = {}) {
const serverUp = await isServerUp();
if (serverUp) {
try {
const res = await apiFetch("/api/v1/providers/keys", { retry: false, acceptNotOk: true });
if (res.ok) {
const data = await res.json();
const connections = data.keys || data.connections || data.items || data;
if (Array.isArray(connections)) {
return _printKeysList(connections, opts);
}
}
} catch {}
}
const { db } = await openOmniRouteDb();
try {
ensureProviderSchema(db);
const connections = listProviderConnections(db).filter(
(c) => c.authType === "apikey" && c.apiKey
);
return _printKeysList(connections, opts);
} finally {
db.close();
}
}
function _printKeysList(connections, opts) {
if (opts.json || opts.output === "json") {
const rows = connections.map((c) => ({
id: c.id,
provider: c.provider,
name: c.name,
isActive: c.isActive !== false,
maskedKey: maskKey(c.apiKey || c.maskedKey || ""),
}));
console.log(JSON.stringify({ keys: rows }, null, 2));
return 0;
}
printHeading(t("keys.title"));
if (connections.length === 0) {
console.log(t("keys.noKeys"));
return 0;
}
for (const c of connections) {
let masked = c.maskedKey || "";
if (!masked && c.apiKey) {
try {
masked = maskKey(getProviderApiKey(c));
} catch {
masked = maskKey(c.apiKey);
}
}
const status = c.isActive !== false ? "\x1b[32m● enabled\x1b[0m" : "\x1b[33m○ disabled\x1b[0m";
console.log(` ${(c.provider || "").padEnd(20)} ${masked.padEnd(22)} ${status}`);
}
console.log(`\n${t("keys.listed", { count: connections.length })}`);
return 0;
}
export async function runKeysRemoveCommand(provider, opts = {}) {
if (!provider) {
console.error(t("keys.providerRequired"));
return 1;
}
const providerLower = provider.toLowerCase();
if (!opts.yes) {
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((resolve) =>
rl.question(t("keys.confirmRemove", { id: providerLower }) + " [y/N] ", resolve)
);
rl.close();
if (!/^y(es)?$/i.test(answer)) {
console.log(t("common.cancelled"));
return 0;
}
}
const serverUp = await isServerUp();
if (serverUp) {
try {
const res = await apiFetch(`/api/v1/providers/keys/${encodeURIComponent(providerLower)}`, {
method: "DELETE",
retry: false,
acceptNotOk: true,
});
if (res.ok) {
console.log(t("keys.removed"));
return 0;
}
} catch {}
}
const { db } = await openOmniRouteDb();
try {
const changes = removeProviderConnectionByProvider(db, providerLower);
if (changes > 0) {
console.log(t("keys.removed"));
return 0;
}
console.log(t("keys.noKeys"));
return 0;
} finally {
db.close();
}
}
async function readStdin() {
return new Promise((resolve) => {
let data = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => (data += chunk));
process.stdin.on("end", () => resolve(data.trim()));
});
}
export async function runKeysRegenerateCommand(id, opts = {}) {
if (!opts.yes) {
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((r) =>
rl.question(t("keys.confirmRegenerate", { id }) + " [y/N] ", r)
);
rl.close();
if (!/^y(es)?$/i.test(answer)) {
console.log(t("common.cancelled"));
return 0;
}
}
if (!(await isServerUp())) {
console.error(t("common.serverOffline"));
return 1;
}
try {
const res = await apiFetch(`/api/v1/registered-keys/${encodeURIComponent(id)}/regenerate`, {
method: "POST",
retry: false,
});
if (!res.ok) {
console.error(t("common.error", { message: `HTTP ${res.status}` }));
return 1;
}
const data = await res.json();
console.log(t("keys.regenerated", { key: data.key || data.apiKey || "(see dashboard)" }));
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runKeysRevokeCommand(id, opts = {}) {
if (!opts.yes) {
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((r) =>
rl.question(t("keys.confirmRevoke", { id }) + " [y/N] ", r)
);
rl.close();
if (!/^y(es)?$/i.test(answer)) {
console.log(t("common.cancelled"));
return 0;
}
}
if (!(await isServerUp())) {
console.error(t("common.serverOffline"));
return 1;
}
try {
const res = await apiFetch(`/api/v1/registered-keys/${encodeURIComponent(id)}/revoke`, {
method: "POST",
retry: false,
});
if (!res.ok) {
console.error(t("common.error", { message: `HTTP ${res.status}` }));
return 1;
}
console.log(t("keys.revoked", { id }));
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runKeysRevealCommand(id, opts = {}) {
process.stderr.write(t("keys.revealWarning") + "\n");
if (!(await isServerUp())) {
console.error(t("common.serverOffline"));
return 1;
}
try {
const res = await apiFetch(`/api/v1/registered-keys/${encodeURIComponent(id)}/reveal`, {
retry: false,
});
if (!res.ok) {
console.error(t("common.error", { message: `HTTP ${res.status}` }));
return 1;
}
const data = await res.json();
console.log(data.key || data.apiKey || "(not available)");
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runKeysUsageCommand(id, opts = {}) {
if (!(await isServerUp())) {
console.error(t("common.serverOffline"));
return 1;
}
const limit = opts.limit || "20";
try {
const res = await apiFetch(
`/api/v1/registered-keys/${encodeURIComponent(id)}/usage?limit=${limit}`,
{ retry: false }
);
if (!res.ok) {
console.error(t("common.error", { message: `HTTP ${res.status}` }));
return 1;
}
const data = await res.json();
const rows = data.usage || data.requests || data.items || [];
if (rows.length === 0) {
console.log(t("keys.noUsage"));
return 0;
}
for (const r of rows) {
const ts = r.timestamp || r.createdAt || "";
const path = r.path || r.endpoint || "";
const status = r.status || r.statusCode || "";
console.log(` ${ts} ${String(status).padEnd(4)} ${path}`);
}
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runKeysPolicyShowCommand(id, opts = {}) {
if (!(await isServerUp())) {
console.error(t("common.serverOffline"));
return 1;
}
try {
const res = await apiFetch(`/api/v1/registered-keys/${encodeURIComponent(id)}/policy`, {
acceptNotOk: true,
retry: false,
});
if (!res.ok) {
console.error(t("common.error", { message: `HTTP ${res.status}` }));
return 1;
}
const data = await res.json();
if (opts.output === "json" || opts.json) {
console.log(JSON.stringify(data, null, 2));
return 0;
}
console.log(t("keys.policy.title") + ` (${id}):`);
console.log(` rate_limit: ${data.rateLimit ?? data.rate_limit ?? "(unset)"}`);
console.log(` max_cost: ${data.maxCost ?? data.max_cost ?? "(unset)"}`);
console.log(
` allowed_models: ${(data.allowedModels ?? data.allowed_models ?? []).join(", ") || "(all)"}`
);
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runKeysPolicySetCommand(id, opts = {}) {
const body = {};
if (opts.rateLimit != null) body.rateLimit = Number(opts.rateLimit);
if (opts.maxCost != null) body.maxCost = Number(opts.maxCost);
if (opts.allowedModels) body.allowedModels = opts.allowedModels.split(",").map((s) => s.trim());
if (Object.keys(body).length === 0) {
console.error(t("keys.policy.nothingToSet"));
return 1;
}
if (!(await isServerUp())) {
console.error(t("common.serverOffline"));
return 1;
}
try {
const res = await apiFetch(`/api/v1/registered-keys/${encodeURIComponent(id)}/policy`, {
method: "PATCH",
body,
acceptNotOk: true,
retry: false,
});
if (!res.ok) {
console.error(t("common.error", { message: `HTTP ${res.status}` }));
return 1;
}
console.log(t("keys.policy.updated"));
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runKeysExpirationListCommand(opts = {}) {
if (!(await isServerUp())) {
console.error(t("common.serverOffline"));
return 1;
}
const days = Number(opts.days || 30);
try {
const res = await apiFetch(`/api/v1/registered-keys?expiring=true&days=${days}`, {
acceptNotOk: true,
retry: false,
});
if (!res.ok) {
console.error(t("common.error", { message: `HTTP ${res.status}` }));
return 1;
}
const data = await res.json();
const rows = data.keys || data.items || data;
if (!Array.isArray(rows) || rows.length === 0) {
console.log(t("keys.expiration.none", { days }));
return 0;
}
if (opts.json || opts.output === "json") {
console.log(JSON.stringify(rows, null, 2));
return 0;
}
console.log(t("keys.expiration.listTitle", { days }));
for (const k of rows) {
const exp = k.expiresAt || k.expires_at || "(unknown)";
console.log(` ${(k.id || "").padEnd(24)} ${(k.name || "").padEnd(20)} expires: ${exp}`);
}
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runKeysRotateCommand(id, opts = {}) {
if (!opts.yes) {
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((r) =>
rl.question(t("keys.confirmRotate", { id }) + " [y/N] ", r)
);
rl.close();
if (!/^y(es)?$/i.test(answer)) {
console.log(t("common.cancelled"));
return 0;
}
}
if (!(await isServerUp())) {
console.error(t("common.serverOffline"));
return 1;
}
const gracePeriod = Number(opts.gracePeriod || 60000);
try {
const res = await apiFetch(`/api/v1/registered-keys/${encodeURIComponent(id)}/rotate`, {
method: "POST",
body: { gracePeriodMs: gracePeriod },
acceptNotOk: true,
retry: false,
});
if (!res.ok) {
console.error(t("common.error", { message: `HTTP ${res.status}` }));
return 1;
}
const data = await res.json();
const newId = data.newKeyId || data.id || "(see dashboard)";
console.log(t("keys.rotated", { id, newId }));
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}

View File

@@ -1,40 +1,89 @@
import { parseArgs, getStringFlag, hasFlag } from "../args.mjs";
import { printHeading, printInfo, printError } from "../io.mjs";
import { writeFileSync, appendFileSync, existsSync, unlinkSync } from "node:fs";
import { t } from "../i18n.mjs";
function printLogsHelp() {
console.log(`
Usage:
omniroute logs [options]
Options:
--follow Stream logs in real-time
--filter <level> Filter by level (error, warn, info) — comma-separated
--lines <n> Number of lines to fetch (default: 100)
--timeout <ms> Connection timeout in ms (default: 30000)
--base-url <url> OmniRoute API base URL (default: http://localhost:20128)
--json Output as JSON
--help Show this help
`);
export function registerLogs(program) {
program
.command("logs")
.description(t("logs.description"))
.option("--follow", t("logs.follow"))
.option("--filter <level>", t("logs.filter"))
.option("--lines <n>", t("logs.lines"), "100")
.option("--timeout <ms>", t("logs.timeout"), "30000")
.option("--base-url <url>", t("logs.baseUrl"), "http://localhost:20128")
.option("--request-id <id>", t("logs.requestId"))
.option("--api-key <key>", t("logs.apiKey"))
.option("--combo <name>", t("logs.combo"))
.option("--status <code>", t("logs.status"))
.option("--duration-min <ms>", t("logs.durationMin"), parseInt)
.option("--duration-max <ms>", t("logs.durationMax"), parseInt)
.option("--export <path>", t("logs.export"))
.action(async (opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const exitCode = await runLogsCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
}
export async function runLogsCommand(argv) {
const { flags } = parseArgs(argv);
function buildLogFilter(opts) {
const levelFilters = opts.filter ? opts.filter.split(",").map((f) => f.trim()) : [];
const requestId = opts.requestId;
const apiKey = opts.apiKey;
const combo = opts.combo;
const statusFilter = opts.status != null ? String(opts.status) : null;
const durationMin = opts.durationMin != null ? Number(opts.durationMin) : null;
const durationMax = opts.durationMax != null ? Number(opts.durationMax) : null;
if (hasFlag(flags, "help") || hasFlag(flags, "h")) {
printLogsHelp();
return 0;
return function matchesLog(parsed) {
if (levelFilters.length > 0) {
const level = String(parsed.level || "info").toLowerCase();
if (!levelFilters.includes(level)) return false;
}
if (requestId) {
const rid = String(parsed.requestId || parsed.request_id || "");
if (!rid.includes(requestId)) return false;
}
if (apiKey) {
const key = String(parsed.apiKey || parsed.api_key || parsed.key || "");
if (!key.includes(apiKey)) return false;
}
if (combo) {
const c = String(parsed.combo || parsed.comboName || parsed.combo_name || "");
if (!c.includes(combo)) return false;
}
if (statusFilter) {
const s = String(parsed.status || parsed.statusCode || parsed.status_code || "");
if (!s.startsWith(statusFilter)) return false;
}
if (durationMin != null) {
const d = Number(parsed.duration || parsed.durationMs || parsed.latency || 0);
if (d < durationMin) return false;
}
if (durationMax != null) {
const d = Number(parsed.duration || parsed.durationMs || parsed.latency || 0);
if (d > durationMax) return false;
}
return true;
};
}
export async function runLogsCommand(opts = {}) {
const baseUrl = opts.baseUrl || opts["base-url"] || "http://localhost:20128";
const follow = opts.follow ?? false;
const timeout = parseInt(String(opts.timeout || "30000"), 10);
const isJson = opts.output === "json";
const exportPath = opts.export;
// Prepare export file
if (exportPath && existsSync(exportPath)) {
unlinkSync(exportPath);
}
const baseUrl = getStringFlag(flags, "base-url") || "http://localhost:20128";
const follow = hasFlag(flags, "follow");
const filter = getStringFlag(flags, "filter");
const lines = getStringFlag(flags, "lines") || "100";
const timeout = parseInt(getStringFlag(flags, "timeout") || "30000", 10);
const filters = filter ? filter.split(",").map((f) => f.trim()) : [];
const matchesLog = buildLogFilter(opts);
// Pass only level filters to the stream (server-side); other filters are client-side
const levelFilters = opts.filter ? opts.filter.split(",").map((f) => f.trim()) : [];
const { createLogStream } = await import("../../../src/lib/cli-helper/log-streamer.js");
const { stream, stop } = createLogStream({ baseUrl, filters, follow, timeout });
const { stream, stop } = createLogStream({ baseUrl, filters: levelFilters, follow, timeout });
const reader = stream.getReader();
const decoder = new TextDecoder();
@@ -42,21 +91,43 @@ export async function runLogsCommand(argv) {
const processLine = (line) => {
if (!line.trim()) return;
if (hasFlag(flags, "json")) {
console.log(line);
let parsed = null;
try {
parsed = JSON.parse(line);
} catch {
// Non-JSON line: only include if no structured filters active
if (
opts.requestId ||
opts.apiKey ||
opts.combo ||
opts.status ||
opts.durationMin != null ||
opts.durationMax != null
)
return;
if (exportPath) appendFileSync(exportPath, line + "\n", "utf8");
else console.log(line);
return;
}
try {
const parsed = JSON.parse(line);
const level = parsed.level || "info";
const ts = parsed.timestamp || new Date().toISOString();
const msg = parsed.message || JSON.stringify(parsed);
const prefix =
{ error: "\x1b[31m[ERR]", warn: "\x1b[33m[WRN]", info: "\x1b[36m[INF]" }[level] || "[INF]";
console.log(`${prefix}\x1b[0m ${ts} ${msg}`);
} catch {
console.log(line);
if (!matchesLog(parsed)) return;
if (exportPath) {
appendFileSync(exportPath, JSON.stringify(parsed) + "\n", "utf8");
return;
}
if (isJson) {
console.log(JSON.stringify(parsed));
return;
}
const level = parsed.level || "info";
const ts = parsed.timestamp || new Date().toISOString();
const msg = parsed.message || JSON.stringify(parsed);
const prefix =
{ error: "\x1b[31m[ERR]", warn: "\x1b[33m[WRN]", info: "\x1b[36m[INF]" }[level] || "[INF]";
console.log(`${prefix}\x1b[0m ${ts} ${msg}`);
};
try {
@@ -64,16 +135,21 @@ export async function runLogsCommand(argv) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) processLine(line);
const parts = buffer.split("\n");
buffer = parts.pop() || "";
for (const line of parts) processLine(line);
}
if (buffer) processLine(buffer);
if (exportPath) console.log(t("logs.exported", { path: exportPath }));
} catch (err) {
if (err.name === "AbortError") {
printInfo("Log stream stopped.");
console.log(t("logs.stopped"));
} else {
printError(`Log stream error: ${err.message}`);
console.error(
t("logs.streamError", {
message: (err instanceof Error ? err.message : String(err)).slice(0, 100),
})
);
}
} finally {
stop();

273
bin/cli/commands/mcp.mjs Normal file
View File

@@ -0,0 +1,273 @@
import { readFileSync } from "node:fs";
import { apiFetch, isServerUp } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
function truncate(v, len = 60) {
if (v == null) return "-";
const s = String(v);
return s.length > len ? s.slice(0, len - 1) + "…" : s;
}
const mcpToolSchema = [
{ key: "name", header: "Tool", width: 36 },
{
key: "scopes",
header: "Scopes",
formatter: (v) => (Array.isArray(v) ? v.join(",") : (v ?? "-")),
},
{ key: "auditLevel", header: "Audit", width: 10 },
{ key: "phase", header: "Phase", width: 6 },
{ key: "description", header: "Description", formatter: truncate },
];
export function registerMcp(program) {
const mcp = program.command("mcp").description(t("mcp.title"));
mcp
.command("status")
.description("Show MCP server status")
.option("--json", "Output as JSON")
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runMcpStatusCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
mcp
.command("restart")
.description("Restart the MCP server")
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runMcpRestartCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
// 5.1 — mcp call + mcp scopes
mcp
.command("call <tool> [argsJson]")
.description(t("mcp.call.description"))
.option("--args <json>", t("mcp.call.args"))
.option("--args-file <path>", t("mcp.call.args_file"))
.option("--stream", t("mcp.call.stream"))
.option("--scope <s>", t("mcp.call.scope"), (v, prev = []) => [...prev, v], [])
.action(async (tool, argsPositional, opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const args = opts.args
? JSON.parse(opts.args)
: opts.argsFile
? JSON.parse(readFileSync(opts.argsFile, "utf8"))
: argsPositional
? JSON.parse(argsPositional)
: {};
if (opts.stream) {
await runMcpStream(tool, args, globalOpts);
return;
}
const extraHeaders = opts.scope?.length ? { "X-MCP-Scopes": opts.scope.join(",") } : {};
const res = await apiFetch("/api/mcp/tools/call", {
method: "POST",
body: { name: tool, arguments: args },
headers: extraHeaders,
});
if (res.status === 403) {
process.stderr.write("Scope denied\n");
process.exit(4);
}
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data, globalOpts);
});
mcp
.command("scopes")
.description(t("mcp.scopes.description"))
.option("--tool <name>", t("mcp.scopes.tool"))
.action(async (opts, cmd) => {
const params = new URLSearchParams({ meta: "scopes" });
if (opts.tool) params.set("tool", opts.tool);
const res = await apiFetch(`/api/mcp/tools?${params}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.scopes ?? data, cmd.optsWithGlobals());
});
// 5.2 — mcp tools + mcp audit
const tools = mcp.command("tools").description(t("mcp.tools.description"));
tools
.command("list")
.description(t("mcp.tools.list.description"))
.option("--scope <s>", t("mcp.tools.list.scope"))
.action(async (opts, cmd) => {
const params = new URLSearchParams();
if (opts.scope) params.set("scope", opts.scope);
const res = await apiFetch(`/api/mcp/tools?${params}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.tools ?? data, cmd.optsWithGlobals(), mcpToolSchema);
});
tools
.command("info <name>")
.description(t("mcp.tools.info.description"))
.action(async (name, opts, cmd) => {
const res = await apiFetch(`/api/mcp/tools?name=${encodeURIComponent(name)}`);
if (!res.ok) {
process.stderr.write(`Not found: ${name}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
tools
.command("schema <name>")
.description(t("mcp.tools.schema.description"))
.option("--io <kind>", t("mcp.tools.schema.io"), "input")
.action(async (name, opts, cmd) => {
const res = await apiFetch(`/api/mcp/tools?name=${encodeURIComponent(name)}&io=${opts.io}`);
if (!res.ok) {
process.stderr.write(`Not found: ${name}\n`);
process.exit(1);
}
const data = await res.json();
const globalOpts = cmd.optsWithGlobals();
if (globalOpts.output === "json") {
process.stdout.write(JSON.stringify(data.schema ?? data, null, 2) + "\n");
} else {
emit(data.schema ?? data, globalOpts);
}
});
const audit = mcp.command("audit").description(t("mcp.audit.description"));
audit
.command("tail")
.option("--follow", t("audit.tail.follow"))
.option("--limit <n>", t("audit.tail.limit"), parseInt, 100)
.action(async (opts, cmd) => {
const { runAuditTail } = await import("./audit.mjs");
await runAuditTail({ ...opts, source: "mcp" }, cmd);
});
audit
.command("stats")
.option("--period <p>", t("audit.stats.period"), "7d")
.action(async (opts, cmd) => {
const res = await apiFetch(`/api/mcp/audit/stats?period=${opts.period}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
emit(await res.json(), cmd.optsWithGlobals());
});
}
async function runMcpStream(tool, args, globalOpts) {
const baseUrl = globalOpts.baseUrl ?? "http://localhost:20128";
const apiKey = globalOpts.apiKey ?? "";
const res = await fetch(`${baseUrl}/api/mcp/stream`, {
method: "POST",
headers: {
"Content-Type": "application/json",
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
},
body: JSON.stringify({ name: tool, arguments: args }),
});
if (!res.ok) {
process.stderr.write(`HTTP ${res.status}\n`);
process.exit(1);
}
const reader = res.body.getReader();
const dec = new TextDecoder();
let buf = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
const lines = buf.split("\n");
buf = lines.pop() ?? "";
for (const line of lines) {
if (line.startsWith("data: ")) {
const raw = line.slice(6).trim();
if (raw && raw !== "[DONE]") process.stdout.write(raw + "\n");
}
}
}
}
export async function runMcpStatusCommand(opts = {}) {
const serverUp = await isServerUp();
if (!serverUp) {
console.error(t("common.serverOffline"));
return 1;
}
try {
const res = await apiFetch("/api/mcp/status", {
retry: false,
timeout: 5000,
acceptNotOk: true,
});
if (!res.ok) {
console.log(t("mcp.stopped"));
return 0;
}
const status = await res.json();
if (opts.json || opts.output === "json") {
console.log(JSON.stringify(status, null, 2));
return 0;
}
const transport = status.transport || "stdio";
console.log(status.running ? t("mcp.running", { transport }) : t("mcp.stopped"));
if (status.toolsCount !== undefined) console.log(` Tools: ${status.toolsCount}`);
if (status.scopes?.length) {
console.log(" Scopes:");
for (const scope of status.scopes) console.log(` - ${scope}`);
}
return 0;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}
export async function runMcpRestartCommand(opts = {}) {
const serverUp = await isServerUp();
if (!serverUp) {
console.error(t("common.serverOffline"));
return 1;
}
try {
const res = await apiFetch("/api/mcp/restart", {
method: "POST",
retry: false,
timeout: 10000,
acceptNotOk: true,
});
if (res.ok) {
console.log(t("mcp.restarted"));
return 0;
}
console.error(t("common.error", { message: `HTTP ${res.status}` }));
return 1;
} catch (err) {
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
return 1;
}
}

210
bin/cli/commands/memory.mjs Normal file
View File

@@ -0,0 +1,210 @@
import { readFileSync } from "node:fs";
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
const VALID_TYPES = ["user", "feedback", "project", "reference"];
function truncate(v, len = 60) {
if (v == null) return "-";
const s = String(v);
return s.length > len ? s.slice(0, len - 1) + "…" : s;
}
function fmtTs(v) {
if (!v) return "-";
try {
return new Date(v).toLocaleString();
} catch {
return String(v);
}
}
const memorySchema = [
{ key: "id", header: "ID", width: 14 },
{ key: "type", header: "Type", width: 12 },
{ key: "content", header: "Content", width: 60, formatter: truncate },
{ key: "score", header: "Score", formatter: (v) => (v != null ? v.toFixed(3) : "-") },
{ key: "createdAt", header: "Created", formatter: fmtTs },
];
function parseDuration(s) {
const m = String(s).match(/^(\d+)(d|m|y)$/i);
if (!m) return null;
const n = parseInt(m[1], 10);
const unit = m[2].toLowerCase();
const now = Date.now();
if (unit === "d") return new Date(now - n * 86400000).toISOString();
if (unit === "m") return new Date(now - n * 30 * 86400000).toISOString();
if (unit === "y") return new Date(now - n * 365 * 86400000).toISOString();
return null;
}
async function confirm(question) {
return new Promise((resolve) => {
process.stdout.write(`${question} (yes/no) `);
process.stdin.setEncoding("utf8");
process.stdin.once("data", (chunk) => {
resolve(chunk.toString().trim().toLowerCase().startsWith("y"));
});
});
}
export async function runMemorySearch(query, opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const params = new URLSearchParams({ q: query, limit: String(opts.limit ?? 20) });
if (opts.type) params.set("type", opts.type);
if (opts.apiKey) params.set("apiKey", opts.apiKey);
if (opts.tokenBudget) params.set("tokenBudget", String(opts.tokenBudget));
const res = await apiFetch(`/api/memory?${params}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.items ?? data, globalOpts, memorySchema);
}
export async function runMemoryAdd(opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const content = opts.content ?? (opts.file ? readFileSync(opts.file, "utf8") : null);
if (!content) {
process.stderr.write("--content or --file required\n");
process.exit(2);
}
const body = {
content,
type: opts.type ?? "user",
...(opts.metadata ? { metadata: JSON.parse(opts.metadata) } : {}),
...(opts.apiKey ? { apiKey: opts.apiKey } : {}),
};
const res = await apiFetch("/api/memory", { method: "POST", body });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const created = await res.json();
emit(created, globalOpts, memorySchema);
}
export async function runMemoryClear(opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
if (!opts.yes) {
const ok = await confirm("This will delete memories. Continue?");
if (!ok) process.exit(0);
}
const params = new URLSearchParams();
if (opts.type) params.set("type", opts.type);
if (opts.olderThan) {
const iso = parseDuration(opts.olderThan);
if (!iso) {
process.stderr.write(`Invalid --older-than value: ${opts.olderThan}\n`);
process.exit(2);
}
params.set("olderThan", iso);
}
if (opts.apiKey) params.set("apiKey", opts.apiKey);
const res = await apiFetch(`/api/memory?${params}`, { method: "DELETE" });
const data = await res.json();
emit(data, globalOpts);
}
export async function runMemoryList(opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const params = new URLSearchParams({ limit: String(opts.limit ?? 100) });
if (opts.type) params.set("type", opts.type);
if (opts.apiKey) params.set("apiKey", opts.apiKey);
const res = await apiFetch(`/api/memory?${params}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data.items ?? data, globalOpts, memorySchema);
}
export async function runMemoryGet(id, opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const res = await apiFetch(`/api/memory/${id}`);
if (!res.ok) {
process.stderr.write(`Not found: ${id}\n`);
process.exit(1);
}
const data = await res.json();
emit(data, globalOpts, memorySchema);
}
export async function runMemoryDelete(id, opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
if (!opts.yes) {
const ok = await confirm(`Delete memory ${id}?`);
if (!ok) process.exit(0);
}
const res = await apiFetch(`/api/memory/${id}`, { method: "DELETE" });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
process.stdout.write(`Deleted: ${id}\n`);
}
export async function runMemoryHealth(opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const res = await apiFetch("/api/memory/health");
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
emit(data, globalOpts);
}
export function registerMemory(program) {
const memory = program.command("memory").description(t("memory.description"));
memory
.command("search <query>")
.description(t("memory.search.description"))
.option("--type <type>", t("memory.search.type"))
.option("--limit <n>", t("memory.search.limit"), parseInt, 20)
.option("--api-key <key>", t("memory.search.api_key"))
.option("--token-budget <n>", t("memory.search.token_budget"), parseInt)
.action(runMemorySearch);
memory
.command("add")
.description(t("memory.add.description"))
.option("--content <text>", t("memory.add.content"))
.option("--file <path>", t("memory.add.file"))
.option("--type <type>", t("memory.add.type"))
.option("--metadata <json>", t("memory.add.metadata"))
.option("--api-key <key>", t("memory.add.api_key"))
.action(runMemoryAdd);
memory
.command("clear")
.description(t("memory.clear.description"))
.option("--type <type>", t("memory.clear.type"))
.option("--older-than <duration>", t("memory.clear.older"))
.option("--api-key <key>", t("memory.clear.api_key"))
.option("--yes", t("memory.clear.yes"))
.action(runMemoryClear);
memory
.command("list")
.description(t("memory.list.description"))
.option("--type <type>", t("memory.list.type"))
.option("--limit <n>", t("memory.list.limit"), parseInt, 100)
.option("--api-key <key>", t("memory.list.api_key"))
.action(runMemoryList);
memory.command("get <id>").description(t("memory.get.description")).action(runMemoryGet);
memory
.command("delete <id>")
.description(t("memory.delete.description"))
.option("--yes", t("memory.delete.yes"))
.action(runMemoryDelete);
memory.command("health").description(t("memory.health.description")).action(runMemoryHealth);
}

View File

@@ -0,0 +1,92 @@
import { apiFetch, isServerUp } from "../api.mjs";
import { emit } from "../output.mjs";
import { modelListSchema } from "../schemas/output-schemas.mjs";
import { t } from "../i18n.mjs";
export function registerModels(program) {
program
.command("models [provider]")
.description(t("models.description"))
.option("--search <query>", t("models.search"))
.option("--json", "Output as JSON")
.action(async (provider, opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const exitCode = await runModelsCommand(provider, { ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
}
export async function runModelsCommand(provider, opts = {}) {
const serverUp = await isServerUp();
if (!serverUp) {
console.error(t("models.noServer"));
return 1;
}
let models = [];
try {
const res = await apiFetch("/api/models", { retry: false, timeout: 5000, acceptNotOk: true });
if (res.ok) {
const data = await res.json();
models = Array.isArray(data) ? data : data.models || [];
}
} catch {}
if (models.length === 0) {
try {
const res = await apiFetch("/api/v1/models", {
retry: false,
timeout: 5000,
acceptNotOk: true,
});
if (res.ok) {
const data = await res.json();
models = Array.isArray(data) ? data : data.data || [];
}
} catch {}
}
if (provider) {
const filter = provider.toLowerCase();
models = models.filter(
(m) =>
(m.provider && m.provider.toLowerCase().includes(filter)) ||
(m.id && m.id.toLowerCase().startsWith(filter)) ||
(m.name && m.name.toLowerCase().includes(filter))
);
}
if (opts.search) {
const search = opts.search.toLowerCase();
models = models.filter(
(m) =>
(m.id && m.id.toLowerCase().includes(search)) ||
(m.name && m.name.toLowerCase().includes(search)) ||
(m.provider && m.provider.toLowerCase().includes(search)) ||
(m.description && m.description.toLowerCase().includes(search))
);
}
if (models.length === 0) {
console.log(t("models.noModels"));
return 0;
}
const normalized = models.map((m) => ({
id: m.id || m.name || "unknown",
provider: m.provider || "unknown",
contextWindow: String(m.context_length || m.max_tokens || m.contextWindow || "-"),
}));
const display = normalized.slice(0, 50);
emit(display, opts, modelListSchema);
if (models.length > 50) {
console.log(
`\x1b[2m ... and ${models.length - 50} more. Use --output json for full list.\x1b[0m`
);
}
return 0;
}

Some files were not shown because too many files have changed in this diff Show More