mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-11-24 12:20:35 +00:00
Compare commits
1 Commits
fix/pre-co
...
fix/codeql
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0eb6aa9f9e |
19
.env.example
19
.env.example
@@ -1540,10 +1540,6 @@ PROVIDER_LIMITS_SYNC_SPACING_MS=1500
|
||||
# Used only by: scripts/ad-hoc/video-live-isolation.ts (not normal server startup).
|
||||
# OMNIROUTE_VIDEO_LIVE_SOURCE_DIR=
|
||||
|
||||
# Flush pooled upstream connections once after the host resumes from sleep (opt-in).
|
||||
# A 5 s heartbeat compares wall-clock time; a gap above 30 s counts as a wake.
|
||||
# OMNIROUTE_WAKE_RECOVERY=false
|
||||
|
||||
# Headless mode (R0.1): boot only the proxy engine (/v1/*, /api/monitoring/health,
|
||||
# auth). Optional boot subsystems are skipped and /dashboard + /home answer 404.
|
||||
# Same as `omniroute serve --headless`. See docs/guides/HEADLESS.md.
|
||||
@@ -3311,21 +3307,6 @@ APP_LOG_TO_FILE=true
|
||||
# Used by: src/lib/tokenHealthCheck.ts. Default: 20 (Issue #7875, regression of #7719).
|
||||
# HEALTHCHECK_BATCH_SIZE=20
|
||||
|
||||
# Set to 1 to scale each token-refresh retry delay by 75-125 percent, derived from the account id and attempt, so different accounts spread their retries. Off by default.
|
||||
# Used by: open-sse/services/tokenRefresh/circuitBreaker.ts. Default: off.
|
||||
# TOKEN_REFRESH_RETRY_JITTER=
|
||||
# Base gap in ms between background token refreshes of Google OAuth accounts (antigravity, agy, gemini); each refresh start also gets up to one third of the base as jitter. Unset or 0 keeps today's behaviour (no spacing); 12000 gives a 12 s gap plus up to 4 s jitter.
|
||||
# Used by: src/lib/tokenHealthGoogleGap.ts. Default: off.
|
||||
# BG_REFRESH_GOOGLE_DELAY_MS=
|
||||
# Opt-in cap on proactive token refreshes in flight per provider during the healthcheck
|
||||
# sweep, so an account sweep does not hammer one identity endpoint. 0, unset or invalid
|
||||
# (default) = no cap, the sweep keeps its batch concurrency.
|
||||
# Used by: src/lib/tokenHealthCheck.ts.
|
||||
# HEALTHCHECK_PER_PROVIDER_CONCURRENCY=0
|
||||
# Caps the Retry-After header sent to clients on error responses (4xx and 5xx), in seconds. Seconds and HTTP-date values both count. The account rest the gateway computes from the upstream header is not changed. Unset or invalid keeps today's behaviour.
|
||||
# Used by: src/shared/middleware/clientRetryAfterCap.ts. Default: unset.
|
||||
# CLIENT_RETRY_AFTER_MAX_SECONDS=
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# 22. DEBUGGING
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
42
.github/workflows/quality.yml
vendored
42
.github/workflows/quality.yml
vendored
@@ -165,14 +165,6 @@ jobs:
|
||||
# With this pinned, USE_VPS_RUNNER governs ONLY build-like jobs — one variable, one coherent
|
||||
# purpose. That is what gap 19 asked for; a second variable turned out to be unnecessary.
|
||||
runs-on: ubuntu-latest
|
||||
# Hard ceiling. Without it a stuck step holds the hosted runner until GitHub's 360 min
|
||||
# default: on 2026-11-20 check:cycles printed its verdict and its node process never
|
||||
# exited (run 44821771451, 118 min until it was cancelled by hand). The longest job this
|
||||
# limit must leave room for is the merge queue's base check: an omni-queue/** base-check
|
||||
# candidate runs the whole unsharded unit suite in this job (94 min measured on
|
||||
# basecheck-07a790f5c158), so 150 leaves about 50% headroom and stays below the queue's
|
||||
# checksTimeoutMinutes (240, config/merge-queue/config.json).
|
||||
timeout-minutes: 150
|
||||
# tsx gates (known-symbols, route-guard-membership) import modules that open
|
||||
# SQLite on load; provide DB env so a fresh CI DB initializes cleanly.
|
||||
env:
|
||||
@@ -309,24 +301,6 @@ jobs:
|
||||
ratchet_gates=(
|
||||
secrets vuln-ratchet workflows openapi-breaking cycles boundary
|
||||
)
|
||||
# Wall-clock limit per gate. A gate that finished its work can still fail to exit:
|
||||
# in run 44821771451 check:cycles printed "RATCHET OK" and its node process was still
|
||||
# alive 113 min later, when the run was cancelled by hand. The slowest gate takes about
|
||||
# 90 s and the whole loop under 10 min. `timeout` (GNU, or the uutils one Ubuntu 26.04
|
||||
# ships: same contract) signals the whole process group (npm, sh, node) and sends KILL
|
||||
# 30 s after TERM. A gate cut by the limit runs once more: the known case is a hang
|
||||
# after a green verdict, and a second timeout counts as a failed gate.
|
||||
GATE_TIMEOUT=10m
|
||||
run_gate() {
|
||||
local rc=0
|
||||
timeout --kill-after=30s "$GATE_TIMEOUT" "$@" || rc=$?
|
||||
if [ "$rc" -eq 124 ] || [ "$rc" -eq 137 ]; then
|
||||
echo "::warning::gate hit the $GATE_TIMEOUT limit and was terminated (exit $rc), retrying once: $*"
|
||||
rc=0
|
||||
timeout --kill-after=30s "$GATE_TIMEOUT" "$@" || rc=$?
|
||||
fi
|
||||
return "$rc"
|
||||
}
|
||||
failed=()
|
||||
for g in "${gates[@]}"; do
|
||||
echo "::group::check:$g"
|
||||
@@ -339,9 +313,9 @@ jobs:
|
||||
# release. See scripts/check/newCodeMode.mjs.
|
||||
case "$g" in file-size|complexity-ratchets|dead-code) NEW_CODE=1 ;; *) NEW_CODE= ;; esac
|
||||
if [ -n "$NEW_CODE" ] && [ -n "${PR_BASE_SHA:-}" ]; then
|
||||
run_gate npm run "check:$g" -- --base-ref "$PR_BASE_SHA" || failed+=("$g")
|
||||
npm run "check:$g" -- --base-ref "$PR_BASE_SHA" || failed+=("$g")
|
||||
else
|
||||
run_gate npm run "check:$g" || failed+=("$g")
|
||||
npm run "check:$g" || failed+=("$g")
|
||||
fi
|
||||
echo "::endgroup::"
|
||||
done
|
||||
@@ -353,20 +327,20 @@ jobs:
|
||||
# PR adds block. workflow_dispatch (no PR base) keeps the absolute ceiling.
|
||||
case "$g" in boundary) BASE_RELATIVE=1 ;; *) BASE_RELATIVE= ;; esac
|
||||
if [ -n "$BASE_RELATIVE" ] && [ -n "${PR_BASE_SHA:-}" ]; then
|
||||
run_gate npm run "check:$g" -- --ratchet --base-ref "$PR_BASE_SHA" || failed+=("$g")
|
||||
npm run "check:$g" -- --ratchet --base-ref "$PR_BASE_SHA" || failed+=("$g")
|
||||
else
|
||||
run_gate npm run "check:$g" -- --ratchet || failed+=("$g")
|
||||
npm run "check:$g" -- --ratchet || failed+=("$g")
|
||||
fi
|
||||
echo "::endgroup::"
|
||||
done
|
||||
echo "::group::typecheck:core"
|
||||
run_gate npm run typecheck:core || failed+=("typecheck:core")
|
||||
npm run typecheck:core || failed+=("typecheck:core")
|
||||
echo "::endgroup::"
|
||||
echo "::group::check:dashboard-typecheck"
|
||||
run_gate npm run check:dashboard-typecheck || failed+=("check:dashboard-typecheck")
|
||||
npm run check:dashboard-typecheck || failed+=("check:dashboard-typecheck")
|
||||
echo "::endgroup::"
|
||||
echo "::group::check:build-typecheck"
|
||||
run_gate npm run check:build-typecheck || failed+=("check:build-typecheck")
|
||||
npm run check:build-typecheck || failed+=("check:build-typecheck")
|
||||
echo "::endgroup::"
|
||||
# #10134: TS7 zero-new-diagnostics ratchet — folded into this non-fail-fast
|
||||
# loop (never a separate blocking step) so an earlier red gate cannot abort
|
||||
@@ -374,7 +348,7 @@ jobs:
|
||||
# the base-relative comparison needs a base SHA (empty on workflow_dispatch).
|
||||
if [ -n "${PR_BASE_SHA:-}" ]; then
|
||||
echo "::group::check:ts7-diagnostics-ratchet"
|
||||
run_gate npm run check:ts7-diagnostics-ratchet -- --base-ref "$PR_BASE_SHA" || failed+=("ts7-diagnostics-ratchet")
|
||||
npm run check:ts7-diagnostics-ratchet -- --base-ref "$PR_BASE_SHA" || failed+=("ts7-diagnostics-ratchet")
|
||||
echo "::endgroup::"
|
||||
fi
|
||||
# A failed gate named in EXTERNAL_STATE_GATES (filled on an omni-queue candidate only)
|
||||
|
||||
@@ -9,12 +9,6 @@ fi
|
||||
# Cheap, deterministic local gates (re-enabled). Slower checks (i18n drift,
|
||||
# openapi coverage/security-tiers, env-doc sync) run in CI to keep commits fast.
|
||||
sh scripts/check/check-git-identity.sh
|
||||
# Migration names (#20578): only when the commit touches src/lib/db/migrations/. The
|
||||
# assignment aborts the hook if git fails. Names only; the comparison with the base stays in CI.
|
||||
staged_migrations=$(git diff --cached --name-only --diff-filter=ACMRD -- src/lib/db/migrations/)
|
||||
if [ -n "$staged_migrations" ]; then
|
||||
GITHUB_EVENT_NAME= MIGRATION_BASE_REF= node scripts/check/check-migration-numbering.mjs
|
||||
fi
|
||||
# The stash is shared by every worktree. Never let a local hook stash another
|
||||
# session's changes, and never download a missing tool during a commit.
|
||||
npx --no-install lint-staged --no-stash
|
||||
|
||||
33
AGENTS.md
33
AGENTS.md
@@ -290,7 +290,7 @@ git push -u origin feat/your-feature
|
||||
|
||||
**Husky hooks**:
|
||||
|
||||
- **pre-commit**: lint-staged + `check-docs-sync` + `check:any-budget:t11` + `check:tracked-artifacts` + `check:migration-numbering` (only when the commit stages a file under `src/lib/db/migrations/`; names only, the comparison with the base stays in CI)
|
||||
- **pre-commit**: lint-staged + `check-docs-sync` + `check:any-budget:t11` + `check:tracked-artifacts`
|
||||
- **commit-msg**: `check:ai-attribution` — rejects AI/bot `Co-Authored-By` trailers and AI-generation footers in the message (Hard Rule #16; human co-authors allowed; also in the `quality.yml` fast-gates loop (PR→`release/**`) and a PR-only `ci.yml` lint step (PR→`main`) — #14436)
|
||||
- **pre-push**: intentionally light (PATH/npm sanity only) — `any-budget` + `tracked-artifacts` already run on pre-commit and CI still enforces both; re-running them per push was pure double-pay (was Fase 6A.12 full pre-push gate; folded into pre-commit in #6716).
|
||||
|
||||
@@ -326,33 +326,12 @@ If red: never treat or "fix" the inherited failures in your branch (a base-red f
|
||||
freeze-gated `fix/release-vX.Y.Z-basereds` PR); a PR opened anyway carries
|
||||
`⚠️ base-red inherited: #<issue>` in its body. Full procedure: `docs/ops/WORKTREE_ISOLATION.md`.
|
||||
|
||||
### Landing on a release branch: omni-queue
|
||||
### Sync-back landings are fast-forward, never squash
|
||||
|
||||
`release/vX.Y.Z` branches are served by the project's merge queue (runbook:
|
||||
[`docs/ops/OMNI_QUEUE.md`](docs/ops/OMNI_QUEUE.md)). Read its `mode` in
|
||||
`config/merge-queue/config.json` on the default branch before landing anything:
|
||||
|
||||
- **`shadow`** — the queue tests but lands nothing; merges are manual. Green checks on a PR head
|
||||
prove the PR against the base they ran on, not against today's base, so before a manual merge
|
||||
apply the `omni-queue` label at the PR's final head and wait for the queue's verdict on that
|
||||
head (`npm run queue -- why <PR>`, `npm run queue -- history --base <branch>`): `would-land` →
|
||||
merge; `culprit-found` / `would-dequeue` → do not merge, fix first. A merge train whose full CI
|
||||
is green on the current base tip, or a head that already contains the base tip, needs no
|
||||
separate verdict.
|
||||
- **`live`** — the `omni-queue` label is the landing. Never run a merge command or push against
|
||||
the branch: its ruleset refuses both.
|
||||
|
||||
Apply the label only to a PR the owner authorized you to land; a PR that touches a protected path
|
||||
also needs `protected-approved`, which is the owner's decision per PR. Never push to
|
||||
`omni-queue-state` or `omni-queue/**`.
|
||||
|
||||
### Sync-back landings are merge commits, never squash
|
||||
|
||||
A `main → release/vX+1` sync-back lands through a pull request merged with a merge commit
|
||||
(`scripts/release/sync-next-cycle.mjs` opens it; the default branch refuses a direct push), never
|
||||
squashed — a squash drops `main` from the release ancestry and the next sync-back re-conflicts on
|
||||
every file (551 on v3.8.50 → v3.8.51). After landing,
|
||||
`git merge-base --is-ancestor origin/main origin/release/vX+1` must be true.
|
||||
A `main → release/vX+1` sync-back lands as the merge commit it already is
|
||||
(`git push origin <head>:refs/heads/release/vX+1`), never squashed — a squash drops `main` from
|
||||
the release ancestry and the next sync-back re-conflicts on every file (551 on v3.8.50 → v3.8.51).
|
||||
After landing, `git merge-base --is-ancestor origin/main origin/release/vX+1` must be true.
|
||||
Steps + baseline-freeze check: `docs/ops/WORKTREE_ISOLATION.md` → "Sync-back landings".
|
||||
|
||||
---
|
||||
|
||||
@@ -117,30 +117,50 @@ FROM runner-base AS runner-web
|
||||
|
||||
USER root
|
||||
|
||||
# Chromium comes from Playwright, exactly as in the Node runner-web (Dockerfile), not
|
||||
# from apt:
|
||||
# - Playwright's own chromium.launch() looks for its managed build under
|
||||
# PLAYWRIGHT_BROWSERS_PATH. The apt `chromium` left that path empty, so in
|
||||
# 3.8.54-web-bun every provider that launches through Playwright without an
|
||||
# explicit executablePath failed with "Executable doesn't exist at
|
||||
# /home/bun/.cache/ms-playwright/…".
|
||||
# - The Debian chromium, chromium-common and chromium-driver packages carried ~720
|
||||
# HIGH scanner findings with no Debian fix; chromium-driver was never used.
|
||||
# The browser version follows the bundled playwright package (Dependabot npm group),
|
||||
# not Debian's chromium.
|
||||
# xvfb (#15300): zai-web needs a headed Chromium and the browser pool starts a private
|
||||
# Xvfb when the container has no DISPLAY.
|
||||
# /usr/bin/chromium stays, as a symlink to Playwright's build, for the code paths that
|
||||
# look for a system browser there (ChatGPT Web, Codex Web, Adobe Firefly login).
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH=/home/bun/.cache/ms-playwright
|
||||
RUN apt-get update \
|
||||
&& bun node_modules/playwright/cli.js install chromium --with-deps \
|
||||
&& apt-get install -y --no-install-recommends xvfb \
|
||||
&& ln -sf "$(bun -e 'process.stdout.write(require("playwright-core").chromium.executablePath())')" /usr/bin/chromium \
|
||||
&& /usr/bin/chromium --version \
|
||||
&& chown -R bun:bun /home/bun/.cache \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
chromium \
|
||||
chromium-driver \
|
||||
fonts-liberation \
|
||||
libasound2t64 \
|
||||
libatk-bridge2.0-0 \
|
||||
libatk1.0-0 \
|
||||
libc6 \
|
||||
libcairo2 \
|
||||
libcups2 \
|
||||
libdbus-1-3 \
|
||||
libexpat1 \
|
||||
libfontconfig1 \
|
||||
libgbm1 \
|
||||
libgcc-s1 \
|
||||
libglib2.0-0 \
|
||||
libgtk-3-0 \
|
||||
libnspr4 \
|
||||
libnss3 \
|
||||
libpango-1.0-0 \
|
||||
libpangocairo-1.0-0 \
|
||||
libstdc++6 \
|
||||
libx11-6 \
|
||||
libx11-xcb1 \
|
||||
libxcb1 \
|
||||
libxcomposite1 \
|
||||
libxcursor1 \
|
||||
libxdamage1 \
|
||||
libxext6 \
|
||||
libxfixes3 \
|
||||
libxi6 \
|
||||
libxrandr2 \
|
||||
libxrender1 \
|
||||
libxss1 \
|
||||
libxtst6 \
|
||||
ca-certificates \
|
||||
fonts-gargi \
|
||||
fonts-ipafont-gothic \
|
||||
fonts-thai-tlwg \
|
||||
fonts-wqy-zenhei \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
|
||||
ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
|
||||
|
||||
# Drop back to default non-root user
|
||||
|
||||
@@ -2,29 +2,22 @@ import {
|
||||
copyFileSync,
|
||||
createReadStream,
|
||||
createWriteStream,
|
||||
closeSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
openSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
readSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
unlinkSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, extname, basename, resolve } from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { resolveDataDir } from "../data-dir.mjs";
|
||||
import { getBaseUrl, isServerUp } from "../api.mjs";
|
||||
import { t } from "../i18n.mjs";
|
||||
import { backupSqliteFile, withReadonlySqlite } from "../sqlite.mjs";
|
||||
import { backupSqliteFile } from "../sqlite.mjs";
|
||||
import { CLI_TOKEN_HEADER, getCliToken } from "../utils/cliToken.mjs";
|
||||
|
||||
function getBackupDir() {
|
||||
@@ -103,7 +96,6 @@ export function registerRestore(program) {
|
||||
.description(t("backup.restoreDescription"))
|
||||
.option("--list", "List available backups")
|
||||
.option("--yes", "Skip confirmation")
|
||||
.option("--key-file <path>", t("backup.keyFileOpt"))
|
||||
.action(async (backupId, opts) => {
|
||||
const exitCode = await runRestoreCommand(backupId, opts);
|
||||
if (exitCode !== 0) process.exit(exitCode);
|
||||
@@ -162,56 +154,15 @@ async function encryptFile(srcPath, destPath, passphrase) {
|
||||
}
|
||||
}
|
||||
|
||||
// Inverse of encryptFile. A wrong passphrase or a damaged file fails the GCM tag check and rejects.
|
||||
async function decryptFile(srcPath, destPath, passphrase) {
|
||||
const header = Buffer.alloc(44); // salt(16) + iv(12) + authTag(16)
|
||||
const fd = openSync(srcPath, "r");
|
||||
let read;
|
||||
try {
|
||||
read = readSync(fd, header, 0, header.length, 0);
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
if (read < header.length) throw new Error("encrypted file is truncated");
|
||||
const key = scryptSync(passphrase, header.subarray(0, 16), 32);
|
||||
const decipher = createDecipheriv("aes-256-gcm", key, header.subarray(16, 28));
|
||||
decipher.setAuthTag(header.subarray(28, 44));
|
||||
await pipeline(
|
||||
createReadStream(srcPath, { start: header.length }),
|
||||
decipher,
|
||||
createWriteStream(destPath)
|
||||
);
|
||||
}
|
||||
|
||||
// Stage the backup database next to the live one first, so a failed copy (disk full, I/O
|
||||
// error) leaves the live file and its WAL untouched. Only then drop the sidecars (a leftover WAL
|
||||
// or journal would replay the old database over the restored file) and swap the copy in.
|
||||
function installRestoredSqlite(sourcePath, destPath) {
|
||||
const staged = `${destPath}.restore-tmp`;
|
||||
try {
|
||||
copyFileSync(sourcePath, staged);
|
||||
} catch (err) {
|
||||
try {
|
||||
rmSync(staged, { force: true });
|
||||
} catch {}
|
||||
throw err;
|
||||
}
|
||||
for (const suffix of ["-wal", "-shm", "-journal"])
|
||||
rmSync(`${destPath}${suffix}`, { force: true });
|
||||
renameSync(staged, destPath);
|
||||
}
|
||||
|
||||
async function promptPassphrase() {
|
||||
const readline = await import("node:readline");
|
||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
return new Promise((resolve) => {
|
||||
// End of input (no TTY, closed pipe) answers with an empty passphrase instead of hanging.
|
||||
rl.once("close", () => resolve(""));
|
||||
return new Promise((resolve) =>
|
||||
rl.question(t("backup.passphrasePrompt"), (ans) => {
|
||||
resolve(ans.trim());
|
||||
rl.close();
|
||||
});
|
||||
});
|
||||
resolve(ans.trim());
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async function pruneBackups(backupDir, retention) {
|
||||
@@ -513,20 +464,20 @@ export async function runRestoreCommand(backupId, opts = {}) {
|
||||
const infoPath = join(backupPath, "backup-info.json");
|
||||
const info = existsSync(infoPath) ? JSON.parse(readFileSync(infoPath, "utf8")) : null;
|
||||
const ts = info ? info.timestamp : backupId;
|
||||
// `backup create --encrypt` writes `<name>.enc` payloads instead of plain names.
|
||||
const encrypted = FILES_TO_BACKUP.some((f) => existsSync(join(backupPath, `${f.name}.enc`)));
|
||||
|
||||
// A running server holds storage.sqlite open and keeps its WAL. Restore only while it is stopped.
|
||||
async function restoreBlockedByServer() {
|
||||
if (!(await isServerUp())) return false;
|
||||
// restore has no passphrase option, so it cannot read `.enc` payloads. Refuse before
|
||||
// asking to overwrite anything. shortcut: no decryption here; add a --key-file option
|
||||
// that decrypts every file to a temp dir first if restoring encrypted backups is needed.
|
||||
if (
|
||||
info?.encrypted === true ||
|
||||
FILES_TO_BACKUP.some((f) => existsSync(join(backupPath, `${f.name}.enc`)))
|
||||
) {
|
||||
console.error(
|
||||
`A server answers at ${getBaseUrl()}. Stop it (omniroute stop) before restore; nothing was changed.`
|
||||
`Backup ${backupId} is encrypted. restore cannot decrypt it; nothing was changed.`
|
||||
);
|
||||
return true;
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (await restoreBlockedByServer()) return 1;
|
||||
|
||||
if (!opts.yes) {
|
||||
const readline = await import("node:readline");
|
||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
@@ -538,60 +489,17 @@ export async function runRestoreCommand(backupId, opts = {}) {
|
||||
console.log(t("common.cancelled"));
|
||||
return 0;
|
||||
}
|
||||
// The server can start while the prompt is open.
|
||||
if (await restoreBlockedByServer()) return 1;
|
||||
}
|
||||
|
||||
// Decrypt every payload before touching live files. GCM rejects wrong keys and damaged data.
|
||||
let sourceDir = backupPath;
|
||||
let tempDir = null;
|
||||
console.log(t("backup.restoring", { path: backupPath }));
|
||||
|
||||
const dataDir = resolveDataDir();
|
||||
try {
|
||||
if (encrypted) {
|
||||
let passphrase = opts.keyFile ? readFileSync(opts.keyFile, "utf8").trim() : null;
|
||||
if (passphrase === null) passphrase = await promptPassphrase();
|
||||
if (!passphrase) {
|
||||
console.error(t("backup.noPassphrase"));
|
||||
return 1;
|
||||
}
|
||||
tempDir = mkdtempSync(join(tmpdir(), "omniroute-restore-")); // mode 0700
|
||||
try {
|
||||
for (const file of FILES_TO_BACKUP) {
|
||||
const encPath = join(backupPath, `${file.name}.enc`);
|
||||
if (existsSync(encPath)) await decryptFile(encPath, join(tempDir, file.name), passphrase);
|
||||
}
|
||||
} catch {
|
||||
console.error(t("backup.restoreDecryptFailed", { name: backupId }));
|
||||
return 1;
|
||||
}
|
||||
sourceDir = tempDir;
|
||||
}
|
||||
|
||||
// Check the database inside the backup before the live files are touched.
|
||||
const backupSqlite = join(sourceDir, "storage.sqlite");
|
||||
if (existsSync(backupSqlite)) {
|
||||
try {
|
||||
const row = await withReadonlySqlite(backupSqlite, (db) =>
|
||||
db.prepare("PRAGMA integrity_check").get()
|
||||
);
|
||||
if (Object.values(row || {})[0] !== "ok") throw new Error("integrity check failed");
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`Backup ${backupId} has a damaged database (${err instanceof Error ? err.message : String(err)}); nothing was changed.`
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(t("backup.restoring", { path: backupPath }));
|
||||
|
||||
const dataDir = resolveDataDir();
|
||||
let restored = 0;
|
||||
for (const file of FILES_TO_BACKUP) {
|
||||
const sourcePath = join(sourceDir, file.name);
|
||||
const sourcePath = join(backupPath, file.name);
|
||||
if (existsSync(sourcePath)) {
|
||||
if (file.name === "storage.sqlite")
|
||||
installRestoredSqlite(sourcePath, join(dataDir, file.name));
|
||||
else copyFileSync(sourcePath, join(dataDir, file.name));
|
||||
copyFileSync(sourcePath, join(dataDir, file.name));
|
||||
restored++;
|
||||
console.log(`\x1b[2m Restored: ${file.name}\x1b[0m`);
|
||||
}
|
||||
@@ -605,7 +513,5 @@ export async function runRestoreCommand(backupId, opts = {}) {
|
||||
} catch (err) {
|
||||
console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
|
||||
return 1;
|
||||
} finally {
|
||||
if (tempDir) rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,7 +287,6 @@
|
||||
"retentionOpt": "Keep only the last N backups",
|
||||
"passphrasePrompt": "Encryption passphrase: ",
|
||||
"noPassphrase": "Passphrase is required for encrypted backup.",
|
||||
"restoreDecryptFailed": "Backup {name} could not be decrypted (wrong passphrase or damaged file); nothing was changed.",
|
||||
"cloudFailed": "Warning: cloud upload failed. Local backup was saved.",
|
||||
"cloudUploaded": "Cloud backup uploaded: {url}",
|
||||
"auto": {
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
- **feat(resilience):** opt-in `CLIENT_RETRY_AFTER_MAX_SECONDS` caps the Retry-After header sent to clients on error responses, while the account rest stays full length, so clients with fallback chains do not wait hours (off by default).
|
||||
@@ -1 +0,0 @@
|
||||
- **feat(cliproxy):** the CLIProxyAPI account health card falls back to the v8 management route (`/v8/management/credentials`) when the deprecated v0 route returns 404.
|
||||
@@ -1 +0,0 @@
|
||||
- **feat(oauth):** opt-in `BG_REFRESH_GOOGLE_DELAY_MS` spaces background token refreshes of Google OAuth accounts (antigravity, agy, gemini) by a base gap plus jitter, to avoid anti-abuse limits (off by default).
|
||||
@@ -1 +0,0 @@
|
||||
- **feat(auth):** Opt-in `HEALTHCHECK_PER_PROVIDER_CONCURRENCY` caps proactive token refreshes in flight per provider during the healthcheck sweep, so a large account sweep does not hammer one identity endpoint.
|
||||
@@ -1 +0,0 @@
|
||||
- **feat(oauth):** opt-in `TOKEN_REFRESH_RETRY_JITTER=1` spreads token-refresh retry delays by 75-125% per account, so different accounts spread their retries (off by default).
|
||||
@@ -1 +0,0 @@
|
||||
- **feat(network):** Opt-in `OMNIROUTE_WAKE_RECOVERY=1` flushes pooled upstream connections once after the host wakes from sleep, so the first requests after resume do not reuse dead sockets.
|
||||
@@ -1 +0,0 @@
|
||||
- fix(claude): stop routing to an extra-usage-enabled Claude account whose plan windows and monthly spend cap are both exhausted (#18059)
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(cli):** `omniroute restore` refuses to run while the server is up or when the backup database is damaged, and it removes the old WAL files so they cannot replay over the restored database. ([#19633](https://github.com/cheaper-inference/OmniRoute/pull/19633))
|
||||
@@ -1,2 +0,0 @@
|
||||
- **fix(cli-tools):** Apply and `omniroute config set` keep unrelated settings in existing Claude, Cline, Kilo and Continue config files instead of replacing the whole file. ([#19633](https://github.com/cheaper-inference/OmniRoute/pull/19633))
|
||||
- **fix(cli-tools):** `POST /api/cli-tools/apply` and `omniroute config set` no longer replace an existing Claude, Cline, Kilo, or Continue config file that fails to parse. Fix or move the file before retrying. ([#19633](https://github.com/cheaper-inference/OmniRoute/pull/19633))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(cli):** Restore decrypts archives made by `backup create --encrypt` with `--key-file` or a passphrase prompt. All payloads authenticate and the database passes its integrity check before live files change; wrong keys and damaged ciphertext fail without changing live files. ([#19633](https://github.com/cheaper-inference/OmniRoute/pull/19633))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(codex):** applying or removing OmniRoute settings in Codex no longer deletes a root `openai_base_url` that you set yourself; only the URL OmniRoute wrote is removed. ([#19716](https://github.com/cheaper-inference/OmniRoute/pull/19716))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(monitoring):** `GET /api/monitoring/health?provider=<id>&unhealthRatioThreshold=<0..1>` (management auth) answers for one provider pool with counts and one `summaryHealth` verdict, with HTTP 503 when the share of unhealthy accounts is above the threshold, so a plain uptime monitor can alert on a degraded pool. ([#19716](https://github.com/cheaper-inference/OmniRoute/pull/19716))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(sse):** the cache-usage log meta no longer records `cacheReadTokens: 0, cacheCreationTokens: 0` for a response whose usage object has cache keys set to `undefined`, and Gemini cache evidence reads `unreported` instead of `invalid` in that case. ([#20197](https://github.com/cheaper-inference/OmniRoute/pull/20197))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(sse):** a Claude OAuth 403 "Request not allowed" no longer triggers a token refresh and a second send; the refusal is about the request, not the token. ([#20197](https://github.com/cheaper-inference/OmniRoute/pull/20197))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(sse):** a Claude tool whose `type` is `null`, an empty string or an explicit `undefined` now gets `type: "custom"`, so strict Anthropic-compatible gateways (for example MiniMax) no longer answer 400 for it. ([#20197](https://github.com/cheaper-inference/OmniRoute/pull/20197))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(sse):** a failed combo-list or upstream-proxy-config read is no longer cached for 10 seconds. A provider set to the upstream proxy is not sent direct after one failed read, and the failure is logged. ([#20197](https://github.com/cheaper-inference/OmniRoute/pull/20197))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(sse):** the final-input token estimate counts a Gemini-style `systemInstruction` (also `system_instruction` and the Cloud Code `request.systemInstruction` / `request.tools`), so the last-resort context guard and the learned estimator calibration no longer ignore a large system prompt. ([#20197](https://github.com/cheaper-inference/OmniRoute/pull/20197))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(plugins):** a plugin `onRequest` hook that blocks a request with a response JSON cannot serialize (a BigInt or a cycle) now still blocks with a 403, instead of letting the request through. ([#20197](https://github.com/cheaper-inference/OmniRoute/pull/20197))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(sse):** the default tool cap (128 tools for non-Claude targets) now keeps the tool a forced `tool_choice` names and the tools the conversation already called, instead of cutting them by position. ([#20197](https://github.com/cheaper-inference/OmniRoute/pull/20197))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(clova):** in tools mode, text an assistant turn wrote before a tool call is kept in the history sent to CLOVA instead of being replaced by an empty string. ([#20224](https://github.com/cheaper-inference/OmniRoute/pull/20224))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(cursor):** with a Cursor agent session, the assistant tool call id now matches the tool result id when the id has a newline. ([#20224](https://github.com/cheaper-inference/OmniRoute/pull/20224))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(gemini):** a repeated finish chunk no longer sends the same tool calls twice in the Antigravity and Gemini SSE streams. ([#20224](https://github.com/cheaper-inference/OmniRoute/pull/20224))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(gemini):** a Gemini stream converted to Claude no longer sends events after `message_stop` when a later chunk repeats `finishReason`. ([#20224](https://github.com/cheaper-inference/OmniRoute/pull/20224))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(gemini):** OpenAI to Gemini usage no longer counts reasoning tokens twice in `candidatesTokenCount`, and it reads `input_tokens` / `output_tokens` when an upstream uses Responses names. ([#20224](https://github.com/cheaper-inference/OmniRoute/pull/20224))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(responses):** long tool call ids that differ only at the end no longer merge when they are cut to 64 characters for the Responses API. ([#20224](https://github.com/cheaper-inference/OmniRoute/pull/20224))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(sse):** when a Claude thinking budget is too small and thinking is dropped, the request keeps the caller's own `max_tokens` (clamped to the model cap) instead of being raised to the full model cap. ([#20224](https://github.com/cheaper-inference/OmniRoute/pull/20224))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(sse):** `clearProviderFailure` accepts a provider alias (the reset now clears the dedupe entries recorded under the canonical id), and `filterAvailableAccounts` drops banned, expired and credits-exhausted accounts. ([#20229](https://github.com/cheaper-inference/OmniRoute/pull/20229))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(embeddings):** `ollama-local` embedding requests now send a configured API key as a bearer token (for an authenticating reverse proxy in front of Ollama). Without a key no `Authorization` header is sent, as before. ([#20229](https://github.com/cheaper-inference/OmniRoute/pull/20229))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(providers):** Muse Spark models on OpenCode Zen and OpenCode Server now report image input, so combos and `/v1/models` no longer treat them as text-only. ([#20229](https://github.com/cheaper-inference/OmniRoute/pull/20229))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(combo):** An auto combo called with an API key that has a connection allowlist no longer drops all of its candidates when the connection lookup fails; it logs a warning and keeps scoring the already-scoped targets. ([#20229](https://github.com/cheaper-inference/OmniRoute/pull/20229))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(combo):** A successful combo target with universal handoff on now writes its session model to `session_model_history` once instead of twice (three times when `context_cache_protection` shares the session), which removes one to two redundant SQLite inserts per request. ([#20229](https://github.com/cheaper-inference/OmniRoute/pull/20229))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(kiro):** a tool result that answers no tool call of the assistant turn before it is now sent to Kiro as message text instead of as a `toolResults` entry that Kiro would reject. ([#20339](https://github.com/cheaper-inference/OmniRoute/pull/20339))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(responses):** a Chat function tool that omits `parameters` now reaches a Responses upstream with an empty object schema, as the Codex path already sends it, instead of with no `parameters` field. ([#20341](https://github.com/cheaper-inference/OmniRoute/pull/20341))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(codex):** Codex connections on a Business Premium seat (`self_serve_business_prolite`) are no longer filtered out as plan-ineligible for the paid-only Sol and Astra models; the paid-plan allow-list now includes that plan, while Free and Go stay blocked ([#20359](https://github.com/cheaper-inference/OmniRoute/pull/20359))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(memory):** a non-streaming reply that a post-call guardrail blocks, or that fails the malformed-reply check, no longer feeds durable Memory, because the client never receives it. ([#20380](https://github.com/cheaper-inference/OmniRoute/pull/20380))
|
||||
@@ -1 +0,0 @@
|
||||
- fix(ocr): `vertex-deepseek-ocr` no longer advertises or sends the `deepseek-ocr-maas` model Google retired on 2026-10-21; it now takes a self-deployed Model Garden model id and endpoint (#20423)
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(logging):** Keep cache-read, cache-creation, fresh-input and reasoning fields inside the green `[USAGE]` console line, restoring green after the estimated marker and resetting once at the end. Preserve explicit zeros and unknown cache provenance without changing persisted usage ([#20548](https://github.com/cheaper-inference/OmniRoute/pull/20548)) — thanks @KiaroSama.
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(ci):** The "Fast Quality Gates" job now has a 150-minute time limit, and each gate of its "Quality gates" step runs under a 10-minute limit with one retry after a timeout, so a gate whose process never exits (as `check:cycles` did after printing its verdict) no longer holds a hosted runner for GitHub's 360-minute default ([#20939](https://github.com/cheaper-inference/OmniRoute/pull/20939))
|
||||
1
changelog.d/fixes/codeql-1407-model-sync-log-format.md
Normal file
1
changelog.d/fixes/codeql-1407-model-sync-log-format.md
Normal file
@@ -0,0 +1 @@
|
||||
- fix(security): model-sync failure logs use a constant format string, so a provider id is never read as a format directive (CodeQL #1407)
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(docker):** The `-web-bun` image installs Playwright's own Chromium and Xvfb, like the `-web` image, instead of Debian's `chromium` package. Browser providers that launch through Playwright found no browser in 3.8.54-web-bun, and the image's HIGH scanner findings drop from 866 to about 150; `/usr/bin/chromium` stays as a link to the same browser
|
||||
@@ -1 +0,0 @@
|
||||
- **perf(analytics):** the usage analytics page runs one grouped database scan, not four, for the daily cost, model, provider cost and service-tier views, so a cache miss on a large history is about 3.6x faster for those queries. ([#19716](https://github.com/cheaper-inference/OmniRoute/pull/19716))
|
||||
@@ -1 +0,0 @@
|
||||
- **perf(cli-tools):** The CLI tools status check runs at most four tool probes at once on a cold batch, instead of starting up to 39 detection processes together. Each tool keeps its 5 second limit, the cache and the result order. ([#19716](https://github.com/cheaper-inference/OmniRoute/pull/19716))
|
||||
@@ -1 +0,0 @@
|
||||
- **perf(gamification):** Each keyed chat no longer scans every retained XP audit row for the hourly anti-cheat check. A new created_at-first covering index serves the hourly range. ([#19741](https://github.com/cheaper-inference/OmniRoute/pull/19741))
|
||||
@@ -1 +0,0 @@
|
||||
- **perf(guardrails):** Requests and responses skip the PII scan, response clone and JSON serialization when their PII masking flags are off (the default). Opt-in masking is unchanged. ([#20122](https://github.com/cheaper-inference/OmniRoute/pull/20122))
|
||||
@@ -1 +0,0 @@
|
||||
- **fix(db):** the pre-commit hook now runs `check:migration-numbering` when the commit stages a file under `src/lib/db/migrations/`, so a hand-numbered or badly named migration fails locally with the same message CI prints (names only; the comparison with the base stays in CI); commits without migrations skip it ([#20938](https://github.com/cheaper-inference/OmniRoute/pull/20938))
|
||||
@@ -165,7 +165,7 @@ Runs on every PR to `main`. Blocks merge on failure.
|
||||
| `check:vitest-exclusions` | Every Vitest exclusion names a tracking issue and appears in `config/quality/vitest-exclusions.json` (#13204) | Yes |
|
||||
| `check:file-size` | Source files (`.ts`/`.tsx` in `src/`, `open-sse/`, `electron/`, `bin/`) stay within `cap` and test files (`*.test.ts(x)`) within `testCap`; files frozen in `file-size-baseline.json` (`frozen` / `testFrozen`) must not grow past their recorded size | Yes |
|
||||
| `check:error-helper` | Error responses in executors/handlers use `buildErrorBody()` / `sanitizeErrorMessage()` (Hard Rule #12) | Yes |
|
||||
| `check:migration-numbering` | Migration file names: the old `001`–`241` series is frozen and new files are `YYYYMMDDHHMMSS_<description>.sql`. Against the PR base it rejects a removed migration, a renamed one without a compatibility entry, and an out-of-order or edited one whose final schema does not commute. Also runs in the husky pre-commit hook when the commit stages a file under `src/lib/db/migrations/` (names, duplicates and the frozen series only; the comparison with the base stays in CI — #20578) |
|
||||
| `check:migration-numbering` | Migration file names: the old `001`–`241` series is frozen and new files are `YYYYMMDDHHMMSS_<description>.sql`. Against the PR base it rejects a removed migration, a renamed one without a compatibility entry, and an out-of-order or edited one whose final schema does not commute |
|
||||
| `check:public-creds` | No literal OAuth `client_id`/`client_secret` or Firebase Web keys outside `publicCreds.ts` (Hard Rule #11) | Yes |
|
||||
| `check:db-rules` | No raw SQL outside `src/lib/db/` modules; no barrel-imports from `localDb.ts` (Hard Rules #2/#5) | Yes |
|
||||
| `check:known-symbols` | Provider executors, routing strategies, and translators registered in their dispatch tables match the files on disk — no orphaned or undeclared symbols | Yes |
|
||||
|
||||
@@ -309,7 +309,7 @@ Use `IF NOT EXISTS`, `IF EXISTS`, and `OR IGNORE` / `OR REPLACE` clauses liberal
|
||||
1. **Create the file with the generator**: `npm run db:new-migration -- <description>` (for example `npm run db:new-migration -- add combo priority`). It writes `src/lib/db/migrations/<YYYYMMDDHHMMSS>_<description>.sql` with the current UTC time and a comment header, moves forward one second if that timestamp is taken, and never overwrites a file. Do not pick a number by hand.
|
||||
2. **Use safe DDL**: `CREATE TABLE IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`, `ALTER TABLE ... ADD COLUMN`
|
||||
3. **Backfill data carefully**: use `UPDATE ... WHERE ...` to handle existing rows
|
||||
4. **Check order and naming**: `npm run test:migrations:fresh` (all migrations on an empty database) and `npm run check:migration-numbering`. The husky pre-commit hook runs `check:migration-numbering` on its own when the commit stages a file under `src/lib/db/migrations/`, so a hand-picked or badly formed name (for example `242_x.sql`) fails the commit locally with the same message CI prints. The hook checks names, duplicates and the frozen `001`–`241` series only; the comparison with the PR base (removed, renamed or out-of-order migrations) still runs in CI
|
||||
4. **Check order and naming**: `npm run test:migrations:fresh` (all migrations on an empty database) and `npm run check:migration-numbering`
|
||||
5. **Test on a copy**: never run untested migrations on production
|
||||
6. **A table created from code needs a migration too**: if a module also creates the table lazily (`CREATE TABLE IF NOT EXISTS`, kept as a self-heal path), a migration must create it with the same DDL. Otherwise a clean install and an upgraded install end up with different schemas, depending on whether that code path ran. `tests/unit/db/lazy-table-migration-guard.test.ts` scans `src/` and `open-sse/` and fails on a lazy `CREATE` without a migration (#20557). Example: `src/lib/db/migrations/20261118120853_compression_run_telemetry.sql`.
|
||||
|
||||
|
||||
@@ -2001,7 +2001,7 @@ The three uses:
|
||||
|
||||
- **Hotfix**: a commit that cannot wait for a batch.
|
||||
- **Sync-back landing**: the `main → release/vX+1` merge commit, pushed as the merge commit it
|
||||
already is (see AGENTS.md → "Sync-back landings are merge commits, never squash").
|
||||
already is (see AGENTS.md → "Sync-back landings are fast-forward, never squash").
|
||||
- **Base repair**: a fix to a red base that the maintainer lands directly instead of through a
|
||||
batch.
|
||||
|
||||
|
||||
@@ -442,11 +442,11 @@ Content-Type: application/json
|
||||
`mistral-ocr-latest`) resolves to its registered provider, and an omitted `model` defaults to
|
||||
Mistral (`mistral-ocr-latest`). Registered providers (`open-sse/config/ocrRegistry.ts`):
|
||||
|
||||
| Provider id | Model id | `model` value | Notes |
|
||||
| ----------------------------- | --------------------------------- | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `mistral` | `mistral-ocr-latest` | `mistral/mistral-ocr-latest` (or bare `mistral-ocr-latest`) | Synchronous — the response is returned directly from the single upstream call. |
|
||||
| `azure-document-intelligence` | `prebuilt-read` | `azure-document-intelligence/prebuilt-read` | Asynchronous upstream (`analyze` + poll) — see below. |
|
||||
| `vertex-deepseek-ocr` | self-deployed (no built-in model) | `vertex-deepseek-ocr/<your-deployed-model-id>` | Synchronous, via your own Vertex AI Model Garden DeepSeek-OCR endpoint (`openapi/chat/completions` shape); Google retired the managed `deepseek-ocr-maas` on 2026-10-21 (#20423), so that id returns 400. |
|
||||
| Provider id | Model id | `model` value | Notes |
|
||||
| ----------------------------- | -------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
|
||||
| `mistral` | `mistral-ocr-latest` | `mistral/mistral-ocr-latest` (or bare `mistral-ocr-latest`) | Synchronous — the response is returned directly from the single upstream call. |
|
||||
| `azure-document-intelligence` | `prebuilt-read` | `azure-document-intelligence/prebuilt-read` | Asynchronous upstream (`analyze` + poll) — see below. |
|
||||
| `vertex-deepseek-ocr` | `deepseek-ocr-maas` | `vertex-deepseek-ocr/deepseek-ocr-maas` | Synchronous, via Vertex AI's `openapi/chat/completions` partner endpoint — see below for auth/URL. |
|
||||
|
||||
All three providers respond in the same Mistral-shaped body:
|
||||
|
||||
|
||||
@@ -647,7 +647,6 @@ detection above).
|
||||
| `MEGABRAIN_API_URL` | `https://api.getmegabrain.com` | `open-sse/services/usage/megabrain.ts` | Base URL for the MegaBrain plan's session and weekly limits in Provider Limits (authenticated with the connection's OAuth token or `mb-v1` API key); override only for a relay or test fixture. |
|
||||
| `OMNIROUTE_DISABLE_BACKGROUND_SERVICES` | `false` | `src/instrumentation-node.ts` | Disable all background services: quota refresh, provider-limits sync, connection recovery, credential health, cloud/model/free-proxy/proxy-health sync, retention cleanup, scheduled VACUUM and the settings hot-reload poll. Useful for CI/test; on a long-running install, connections do not auto-recover and the database keeps growing. |
|
||||
| `OMNIROUTE_HEADLESS` | _(unset)_ | `src/lib/system/headless.ts` | Proxy-engine-only boot: skips optional subsystems, `/dashboard` → 404. Same as `omniroute serve --headless`. See [HEADLESS.md](../guides/HEADLESS.md). |
|
||||
| `OMNIROUTE_WAKE_RECOVERY` | `false` | `src/lib/wakeRecovery.ts` | Opt-in. A 5 s heartbeat compares wall-clock time; a gap above 30 s counts as a host wake and flushes the pooled upstream connections once, so the first requests after resume do not reuse dead sockets. Skipped in headless mode. |
|
||||
| `OMNIROUTE_ENABLE_RUNTIME_BACKGROUND_TASKS` | _(unset)_ | `src/lib/config/runtimeSettings.ts` | Force background tasks on under automated test detection. Set `1` to override the test heuristic. |
|
||||
| `OMNIROUTE_BUDGET_RESET_JOB_INTERVAL_MS` | `600000` | `src/lib/jobs/budgetResetJob.ts` | Budget reset check cadence (ms). Floor `10000`. |
|
||||
| `OMNIROUTE_CONNECTION_RECOVERY_INTERVAL_MS` | `60000` | `src/lib/quota/connectionRecovery.ts` | Proactive connection-cooldown recovery cadence (ms): re-validates connections whose transient `rate_limited_until` has elapsed, off the request hot path. Floor `5000`. |
|
||||
@@ -1429,10 +1428,6 @@ Anthropic-compatible provider instead.
|
||||
| `HEALTHCHECK_JITTER_MIN_MS` | `500` | `src/lib/tokenHealthCheck.ts` | Minimum randomized jitter (ms) added on top of `HEALTHCHECK_STAGGER_MS` between provider token healthchecks, to prevent bursting (Issue #1220). |
|
||||
| `HEALTHCHECK_JITTER_MAX_MS` | `5000` | `src/lib/tokenHealthCheck.ts` | Maximum randomized jitter (ms) added on top of `HEALTHCHECK_STAGGER_MS` between provider token healthchecks, to prevent bursting (Issue #1220). |
|
||||
| `HEALTHCHECK_BATCH_SIZE` | `20` | `src/lib/tokenHealthCheck.ts` | Concurrent-check batch size for the startup token-healthcheck sweep; larger values check more connections in parallel, smaller values reduce burst load (Issue #7875, regression of #7719). |
|
||||
| `TOKEN_REFRESH_RETRY_JITTER` | `off` | `open-sse/services/tokenRefresh/circuitBreaker.ts` | Set to 1 to scale each token-refresh retry delay by 75-125 percent, derived from the account id and attempt, so different accounts spread their retries. Off by default. |
|
||||
| `BG_REFRESH_GOOGLE_DELAY_MS` | `off` | `src/lib/tokenHealthGoogleGap.ts` | Base gap in ms between background token refreshes of Google OAuth accounts (antigravity, agy, gemini); each refresh start also gets up to one third of the base as jitter. Unset or 0 keeps today's behaviour (no spacing); 12000 gives a 12 s gap plus up to 4 s jitter. |
|
||||
| `HEALTHCHECK_PER_PROVIDER_CONCURRENCY` | `0` (no cap) | `src/lib/tokenHealthCheck.ts` | Opt-in cap on proactive token refreshes in flight per provider during the healthcheck sweep. Batches still run together, but a provider with more accounts than the cap refreshes them in turn. `0`, unset or invalid values mean no cap. |
|
||||
| `CLIENT_RETRY_AFTER_MAX_SECONDS` | `unset` | `src/shared/middleware/clientRetryAfterCap.ts` | Caps the Retry-After header sent to clients on error responses (4xx and 5xx), in seconds. Seconds and HTTP-date values both count. The account rest the gateway computes from the upstream header is not changed. Unset or invalid keeps today's behaviour. |
|
||||
| `REQUEST_RETRY` | `2` | `src/sse/services/cooldownAwareRetry.ts` | Number of automatic retries on model-scoped cooldown responses before returning error to client. |
|
||||
| `MAX_RETRY_INTERVAL_SEC` | `30` | `src/sse/services/cooldownAwareRetry.ts` | Max backoff interval (seconds) between cooldown retries. Capped by this value regardless of upstream `Retry-After`. |
|
||||
| `HEADROOM_URL` | `http://localhost:8787` | `src/lib/headroom/detect.ts` | Headroom token-saver proxy URL. The dashboard lifecycle (`api/headroom/*`) spawns a local `headroom-ai` CLI on loopback by default; override only to point at an external Docker sidecar proxy. |
|
||||
|
||||
@@ -528,8 +528,7 @@ export const EMBEDDING_PROVIDERS: Record<string, EmbeddingProvider> = {
|
||||
id: "ollama-local",
|
||||
baseUrl: "http://localhost:11434/v1/embeddings",
|
||||
authType: "none",
|
||||
// Key optional (reverse proxy in front of Ollama): sent as bearer only when configured.
|
||||
authHeader: "bearer",
|
||||
authHeader: "none",
|
||||
models: [
|
||||
{ id: "embeddinggemma", name: "EmbeddingGemma" },
|
||||
{ id: "nomic-embed-text", name: "Nomic Embed Text" },
|
||||
|
||||
@@ -107,10 +107,10 @@ export const AZURE_DI_TRANSFORMATION: OcrTransformation = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Vertex AI DeepSeek OCR (self-deployed Model Garden endpoint), served through Vertex's generic
|
||||
* Vertex AI DeepSeek OCR (deepseek-ai/deepseek-ocr-maas), served through Vertex's generic
|
||||
* OpenAI-compatible partner endpoint ("openapi/chat/completions"). Modeled on litellm's
|
||||
* VertexAIDeepSeekOCRConfig (litellm/llms/vertex_ai/ocr/deepseek_transformation.py):
|
||||
* - request: OpenAI chat-completions shape, model id sent as supplied, the OCR
|
||||
* - request: OpenAI chat-completions shape, model prefixed with "deepseek-ai/", the OCR
|
||||
* document sent as a single image_url content part (document_url documents are mapped to
|
||||
* the same image_url shape — Vertex accepts both gs:// and https:// URLs there).
|
||||
* - response: an OpenAI chat-completions body whose choices[0].message.content is either a
|
||||
@@ -129,14 +129,6 @@ function vertexDeepseekOcrContent(document: Record<string, unknown> | undefined)
|
||||
return { type: "image_url", image_url: url };
|
||||
}
|
||||
|
||||
/**
|
||||
* Google retired the managed (MaaS) `deepseek-ocr-maas` model on Vertex AI on 2026-10-21; the only
|
||||
* remaining path is a self-deployed DeepSeek-OCR on Model Garden (#20423). The provider therefore
|
||||
* has no built-in model: callers pass `vertex-deepseek-ocr/<deployed-model-id>` plus the dedicated
|
||||
* endpoint in `providerSpecificData.baseUrl`, and the id is sent upstream exactly as supplied.
|
||||
*/
|
||||
export const VERTEX_DEEPSEEK_RETIRED_MODEL_ID = "deepseek-ocr-maas";
|
||||
|
||||
export const VERTEX_DEEPSEEK_TRANSFORMATION: OcrTransformation = {
|
||||
buildRequest({ baseUrl, token, body, modelId }) {
|
||||
return {
|
||||
@@ -145,7 +137,7 @@ export const VERTEX_DEEPSEEK_TRANSFORMATION: OcrTransformation = {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({
|
||||
model: modelId,
|
||||
model: `deepseek-ai/${modelId}`,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
@@ -162,7 +154,7 @@ export const VERTEX_DEEPSEEK_TRANSFORMATION: OcrTransformation = {
|
||||
choices?: Array<{ message?: { content?: unknown } }>;
|
||||
usage?: Record<string, unknown>;
|
||||
};
|
||||
const model = r.model ?? "vertex-deepseek-ocr";
|
||||
const model = r.model ?? "deepseek-ocr-maas";
|
||||
const content = r.choices?.[0]?.message?.content;
|
||||
|
||||
if (typeof content === "string") {
|
||||
@@ -212,7 +204,7 @@ export const OCR_PROVIDERS: Record<string, OcrProvider> = {
|
||||
baseUrl: "",
|
||||
authType: "apikey",
|
||||
authHeader: "bearer",
|
||||
models: [],
|
||||
models: [{ id: "deepseek-ocr-maas", name: "DeepSeek OCR (Vertex AI MaaS)" }],
|
||||
transformation: VERTEX_DEEPSEEK_TRANSFORMATION,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -44,7 +44,6 @@ export const opencode_serverProvider: RegistryEntry = {
|
||||
id: "muse-spark-1.3-contributor-free",
|
||||
name: "Muse Spark 1.3 Contributor Free",
|
||||
supportsReasoning: true,
|
||||
supportsVision: true,
|
||||
},
|
||||
{
|
||||
id: "nemotron-3-ultra-free",
|
||||
|
||||
@@ -106,7 +106,6 @@ export const opencode_zenProvider: RegistryEntry = {
|
||||
targetFormat: "openai-responses",
|
||||
contextLength: 1048576,
|
||||
maxOutputTokens: 131072,
|
||||
supportsVision: true,
|
||||
},
|
||||
// Explicit wire-format overlay of the base opencode provider's muse-spark entry
|
||||
// (targetFormat: openai-responses). Keep in sync with base on catalog syncs.
|
||||
@@ -117,7 +116,6 @@ export const opencode_zenProvider: RegistryEntry = {
|
||||
targetFormat: "openai-responses",
|
||||
contextLength: 1048576,
|
||||
maxOutputTokens: 131072,
|
||||
supportsVision: true,
|
||||
},
|
||||
// Muse Spark 1.3 is served only on the Responses API, same as 1.2 above.
|
||||
// Its window matches the published OpenCode catalog instead of the
|
||||
@@ -129,7 +127,6 @@ export const opencode_zenProvider: RegistryEntry = {
|
||||
targetFormat: "openai-responses",
|
||||
contextLength: 1048576,
|
||||
maxOutputTokens: 131072,
|
||||
supportsVision: true,
|
||||
},
|
||||
{
|
||||
id: "muse-spark-1.3-contributor-free",
|
||||
@@ -138,7 +135,6 @@ export const opencode_zenProvider: RegistryEntry = {
|
||||
targetFormat: "openai-responses",
|
||||
contextLength: 1048576,
|
||||
maxOutputTokens: 131072,
|
||||
supportsVision: true,
|
||||
},
|
||||
|
||||
// ── DeepSeek ────────────────────────────────────────────────
|
||||
|
||||
@@ -90,17 +90,15 @@ function hasCacheUsageFields(
|
||||
// `cache_write_tokens` is the cache-creation alias emitted by OpenRouter, Devin
|
||||
// Desktop and the codex-chatgpt-web bridge; without it an OpenAI-shaped usage
|
||||
// payload logged a cache write of 0 for a model that actually reported one.
|
||||
// A key that exists with the value `undefined` is "not reported" (the usage extractors
|
||||
// create such keys when the provider sent nothing), so test the value, not the key.
|
||||
return (
|
||||
usageRecord.cache_read_input_tokens !== undefined ||
|
||||
usageRecord.cached_tokens !== undefined ||
|
||||
usageRecord.cache_creation_input_tokens !== undefined ||
|
||||
usageRecord.cache_write_tokens !== undefined ||
|
||||
"cache_read_input_tokens" in usageRecord ||
|
||||
"cached_tokens" in usageRecord ||
|
||||
"cache_creation_input_tokens" in usageRecord ||
|
||||
"cache_write_tokens" in usageRecord ||
|
||||
(!!promptTokenDetails &&
|
||||
(promptTokenDetails.cached_tokens !== undefined ||
|
||||
promptTokenDetails.cache_creation_tokens !== undefined ||
|
||||
promptTokenDetails.cache_write_tokens !== undefined))
|
||||
("cached_tokens" in promptTokenDetails ||
|
||||
"cache_creation_tokens" in promptTokenDetails ||
|
||||
"cache_write_tokens" in promptTokenDetails))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,8 +20,7 @@ export function defaultClaudeToolType(tools: unknown): unknown {
|
||||
if (!Array.isArray(tools)) return tools;
|
||||
return tools.map((tool) => {
|
||||
if (tool && typeof tool === "object" && !Array.isArray(tool)) {
|
||||
// `type` goes last: with the spread last, an own `type: null | "" | undefined` won over "custom".
|
||||
return (tool as UnknownRecord).type ? tool : { ...(tool as UnknownRecord), type: "custom" };
|
||||
return (tool as UnknownRecord).type ? tool : { type: "custom", ...(tool as UnknownRecord) };
|
||||
}
|
||||
return tool;
|
||||
});
|
||||
|
||||
@@ -43,13 +43,8 @@ export async function getCombosCached(): Promise<unknown[]> {
|
||||
}
|
||||
_combosCacheTs = now;
|
||||
_combosCacheVersionSnapshot = version;
|
||||
// A rejected read must not stay cached for the TTL: drop it so the next caller reads again.
|
||||
const pending = getCombos();
|
||||
_combosPromise = pending;
|
||||
pending.catch(() => {
|
||||
if (_combosPromise === pending) clearCombosCache();
|
||||
});
|
||||
return pending;
|
||||
_combosPromise = getCombos();
|
||||
return _combosPromise;
|
||||
}
|
||||
|
||||
export function clearCombosCache() {
|
||||
@@ -69,18 +64,7 @@ export function clearUpstreamProxyConfigCache(providerId?: string) {
|
||||
export async function getUpstreamProxyConfigCached(providerId: string) {
|
||||
const cached = _proxyConfigCache.get(providerId);
|
||||
if (cached && Date.now() - cached.ts < PROXY_CONFIG_CACHE_TTL) return cached;
|
||||
let failed = false;
|
||||
const cfg = await getUpstreamProxyConfig(providerId).catch((error) => {
|
||||
// Return the native default for this call only; caching it would route a provider that is set
|
||||
// to the upstream proxy straight to the provider for the whole TTL after one failed read.
|
||||
failed = true;
|
||||
console.warn(
|
||||
`[UPSTREAM_PROXY] config read failed for ${providerId}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
return null;
|
||||
});
|
||||
const cfg = await getUpstreamProxyConfig(providerId).catch(() => null);
|
||||
const result: UpstreamProxyConfigCacheEntry = cfg
|
||||
? {
|
||||
mode: cfg.mode,
|
||||
@@ -96,6 +80,6 @@ export async function getUpstreamProxyConfigCached(providerId: string) {
|
||||
fallbackBackend: "cliproxyapi" as const,
|
||||
ts: Date.now(),
|
||||
};
|
||||
if (!failed) _proxyConfigCache.set(providerId, result);
|
||||
_proxyConfigCache.set(providerId, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -33,20 +33,10 @@ export function estimateFinalInputTokenBreakdown(
|
||||
: requestBody?.input && typeof requestBody.input === "object"
|
||||
? requestBody.input
|
||||
: []);
|
||||
const tools = requestBody?.tools ?? nestedRequest?.tools;
|
||||
const breakdown = {
|
||||
messages: estimateTokens(messages),
|
||||
tools: Array.isArray(tools) ? estimateTokens(tools) : 0,
|
||||
// Gemini-shaped bodies keep the system prompt in systemInstruction (either spelling, also
|
||||
// under `request` for Cloud Code), so count it next to `system`.
|
||||
system:
|
||||
estimateTokens(requestBody?.system) +
|
||||
estimateTokens(
|
||||
requestBody?.systemInstruction ??
|
||||
requestBody?.system_instruction ??
|
||||
nestedRequest?.systemInstruction ??
|
||||
nestedRequest?.system_instruction
|
||||
),
|
||||
tools: Array.isArray(requestBody?.tools) ? estimateTokens(requestBody.tools) : 0,
|
||||
system: estimateTokens(requestBody?.system),
|
||||
instructions: estimateTokens(requestBody?.instructions),
|
||||
};
|
||||
return { ...breakdown, total: Object.values(breakdown).reduce((sum, value) => sum + value, 0) };
|
||||
|
||||
@@ -791,6 +791,24 @@ export async function runNonStreamingResponse(deps: NonStreamingDeps) {
|
||||
agentContext,
|
||||
});
|
||||
|
||||
// #12150 P1b surface 3 (fix round 1): a video-bridge-observed request's
|
||||
// request- AND response-derived text both carry the full transcript (the
|
||||
// flattened description on the request side, the model's own reply on
|
||||
// the response side) — neither may populate durable Memory. See
|
||||
// runMemoryExtractionGate for the shared gate + extraction wiring, unit
|
||||
// tested directly in tests/unit/video-bridge-memory-suppression.test.ts.
|
||||
runMemoryExtractionGate({
|
||||
memoryOwnerId,
|
||||
memorySettings,
|
||||
videoBridgeObserved,
|
||||
piiTokensMinted,
|
||||
pipelineSessionId,
|
||||
requestBody: body as Record<string, unknown>,
|
||||
responseBody: memoryExtractionResponse as Record<string, unknown> | null,
|
||||
extractFacts,
|
||||
log,
|
||||
});
|
||||
|
||||
const customSkillExecutionEnabled =
|
||||
Boolean(memoryOwnerId) && memorySettings?.skillsEnabled === true;
|
||||
const builtinToolNames = [
|
||||
@@ -1022,26 +1040,6 @@ export async function runNonStreamingResponse(deps: NonStreamingDeps) {
|
||||
};
|
||||
}
|
||||
|
||||
// Durable Memory only learns from a reply the client receives: a guardrail-blocked (400) or
|
||||
// malformed (502) reply returned above never reaches this point.
|
||||
// #12150 P1b surface 3 (fix round 1): a video-bridge-observed request's
|
||||
// request- AND response-derived text both carry the full transcript (the
|
||||
// flattened description on the request side, the model's own reply on
|
||||
// the response side) — neither may populate durable Memory. See
|
||||
// runMemoryExtractionGate for the shared gate + extraction wiring, unit
|
||||
// tested directly in tests/unit/video-bridge-memory-suppression.test.ts.
|
||||
runMemoryExtractionGate({
|
||||
memoryOwnerId,
|
||||
memorySettings,
|
||||
videoBridgeObserved,
|
||||
piiTokensMinted,
|
||||
pipelineSessionId,
|
||||
requestBody: body as Record<string, unknown>,
|
||||
responseBody: memoryExtractionResponse as Record<string, unknown> | null,
|
||||
extractFacts,
|
||||
log,
|
||||
});
|
||||
|
||||
// ── Phase 9.1: Cache store (non-streaming, temp=0) ──
|
||||
storeSemanticCacheResponse({
|
||||
enabled: semanticCacheEnabled,
|
||||
|
||||
@@ -17,27 +17,6 @@ export type PluginOnRequestGate =
|
||||
|
||||
const JSON_HEADERS = { status: 403, headers: { "Content-Type": "application/json" } } as const;
|
||||
|
||||
const GENERIC_BLOCK_BODY = JSON.stringify({
|
||||
error: { message: "Request blocked by plugin", type: "plugin_block" },
|
||||
});
|
||||
|
||||
/**
|
||||
* The 403 for a blocking hook. A plugin response that JSON cannot serialize (BigInt, a cycle)
|
||||
* must still block: it falls back to the generic body instead of throwing into the fail-open
|
||||
* catch below, which would turn the block into an allow.
|
||||
*/
|
||||
function blockResponse(pluginResponse: unknown): Response {
|
||||
let body = GENERIC_BLOCK_BODY;
|
||||
if (pluginResponse) {
|
||||
try {
|
||||
body = JSON.stringify(pluginResponse) ?? GENERIC_BLOCK_BODY;
|
||||
} catch {
|
||||
// keep the generic body
|
||||
}
|
||||
}
|
||||
return new Response(body, JSON_HEADERS);
|
||||
}
|
||||
|
||||
export async function runPluginOnRequestHook(args: {
|
||||
requestId: string;
|
||||
body: unknown;
|
||||
@@ -61,7 +40,15 @@ export async function runPluginOnRequestHook(args: {
|
||||
const pluginResult = await runOnRequest(pluginCtx);
|
||||
if (pluginResult?.blocked) {
|
||||
args.log?.info?.("PLUGIN", `Request blocked by plugin`);
|
||||
return { blocked: true, response: blockResponse(pluginResult.response) };
|
||||
const response = pluginResult.response
|
||||
? new Response(JSON.stringify(pluginResult.response), JSON_HEADERS)
|
||||
: new Response(
|
||||
JSON.stringify({
|
||||
error: { message: "Request blocked by plugin", type: "plugin_block" },
|
||||
}),
|
||||
JSON_HEADERS
|
||||
);
|
||||
return { blocked: true, response };
|
||||
}
|
||||
if (pluginResult?.metadata) {
|
||||
Object.assign(pluginCtx.metadata, pluginResult.metadata);
|
||||
|
||||
@@ -4,10 +4,6 @@ import { isOpencodeFreeTierRefusalForProvider } from "../../executors/opencodeGe
|
||||
import { isMusePolicyRefusal } from "../../services/musePolicyRefusal.ts";
|
||||
import { getM365FailureScope } from "../../services/m365ErrorPolicy.ts";
|
||||
import { isProviderSafetyRefusalBody } from "../../utils/providerSafety.ts";
|
||||
import {
|
||||
isAnthropicOAuthProvider,
|
||||
isAnthropicRequestNotAllowed,
|
||||
} from "../../services/errorClassifier.ts";
|
||||
|
||||
/**
|
||||
* True when a 401/403 from `provider` cannot be cured by refreshing credentials.
|
||||
@@ -18,8 +14,6 @@ import {
|
||||
* about the token, so a refresh only adds latency before the same answer.
|
||||
* - An explicit provider safety stop refuses the request's content; refreshing would
|
||||
* re-send the refused conversation with a new token.
|
||||
* - A Claude OAuth 403 "Request not allowed" refuses this request, not the token: a refresh
|
||||
* would rotate the refresh token and send the refused request into the enforcement again.
|
||||
*
|
||||
* The body is read from a clone so the caller can still consume the response.
|
||||
*/
|
||||
@@ -33,14 +27,6 @@ export async function shouldSkipCredentialRefresh(
|
||||
if (bodyText !== null && isProviderSafetyRefusalBody(response.status, bodyText)) return true;
|
||||
if (provider.toLowerCase() === "muse-code" && isMusePolicyRefusal(response.status, bodyText))
|
||||
return true;
|
||||
// Claude OAuth 403 "Request not allowed" refuses this request, not the token (REQUEST_REJECTED).
|
||||
if (
|
||||
response.status === 403 &&
|
||||
bodyText !== null &&
|
||||
isAnthropicOAuthProvider(provider) &&
|
||||
isAnthropicRequestNotAllowed(bodyText)
|
||||
)
|
||||
return true;
|
||||
// Neither model nor account licence entitlements change by rotating the token.
|
||||
if (response.status === 403 && getM365FailureScope(provider, response.status, bodyText) !== null)
|
||||
return true;
|
||||
|
||||
@@ -12,11 +12,7 @@ import { getEffectiveToolLimit, getKnownToolLimit } from "../../services/toolLim
|
||||
import { OMNIROUTE_WEB_SEARCH_FALLBACK_TOOL_NAME } from "../../services/webSearchFallback.ts";
|
||||
import { OMNIROUTE_WEB_FETCH_FALLBACK_TOOL_NAME } from "../../services/webFetchInterception.ts";
|
||||
import { CLAUDE_OAUTH_TOOL_PREFIX } from "../../translator/request/openai-to-claude.ts";
|
||||
import {
|
||||
applyToolDisclosure,
|
||||
collectHistoryToolNames,
|
||||
type ToolDisclosureConfig,
|
||||
} from "../../utils/toolDisclosure.ts";
|
||||
import { applyToolDisclosure, type ToolDisclosureConfig } from "../../utils/toolDisclosure.ts";
|
||||
import {
|
||||
isOpenCodeLane,
|
||||
providerSupportsCaching,
|
||||
@@ -173,13 +169,10 @@ function isFallbackTool(tool: unknown): boolean {
|
||||
return FALLBACK_TOOL_NAMES.has(unprefixed);
|
||||
}
|
||||
|
||||
function capToolList(tools: unknown[], limit: number, keepNames: ReadonlySet<string>): unknown[] {
|
||||
// Kept ahead of the cap: the fallback tools, the tool a forced tool_choice names, and the
|
||||
// tools the conversation already called (the same set tool disclosure never drops).
|
||||
const pinned = (tool: unknown) => isFallbackTool(tool) || keepNames.has(toolDisplayName(tool));
|
||||
let pinnedRoom = Math.min(limit, tools.filter(pinned).length);
|
||||
function capToolList(tools: unknown[], limit: number): unknown[] {
|
||||
let pinnedRoom = Math.min(limit, tools.filter(isFallbackTool).length);
|
||||
let room = limit - pinnedRoom;
|
||||
return tools.filter((tool) => (pinned(tool) ? pinnedRoom-- > 0 : room-- > 0));
|
||||
return tools.filter((tool) => (isFallbackTool(tool) ? pinnedRoom-- > 0 : room-- > 0));
|
||||
}
|
||||
|
||||
const MAX_LOGGED_DROPPED_TOOLS = 15;
|
||||
@@ -201,9 +194,7 @@ function applyToolCap(
|
||||
provider: string | null | undefined,
|
||||
log?: LoggerLike
|
||||
): Body {
|
||||
const keepNames = new Set<string>();
|
||||
collectHistoryToolNames(bodyToSend, keepNames);
|
||||
const truncatedTools = capToolList(tools, limit, keepNames);
|
||||
const truncatedTools = capToolList(tools, limit);
|
||||
const kept = new Set(truncatedTools);
|
||||
const dropped = tools.filter((tool) => !kept.has(tool)).map(toolDisplayName);
|
||||
const sample = dropped.slice(0, MAX_LOGGED_DROPPED_TOOLS).join(", ");
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
getOcrTransformation,
|
||||
parseOcrModel,
|
||||
OCR_PROVIDERS,
|
||||
VERTEX_DEEPSEEK_RETIRED_MODEL_ID,
|
||||
type OcrResponseShape,
|
||||
} from "../config/ocrRegistry.ts";
|
||||
import { errorResponse, sanitizeErrorMessage } from "../utils/error.ts";
|
||||
@@ -183,16 +182,6 @@ export async function handleOcr({
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
providerId === VERTEX_DEEPSEEK_OCR_PROVIDER_ID &&
|
||||
modelId === VERTEX_DEEPSEEK_RETIRED_MODEL_ID
|
||||
) {
|
||||
return errorResponse(
|
||||
400,
|
||||
`Model "${VERTEX_DEEPSEEK_RETIRED_MODEL_ID}" was retired by Google on 2026-10-21. Self-deploy DeepSeek-OCR on Vertex Model Garden and pass its model id with the dedicated endpoint URL.`
|
||||
);
|
||||
}
|
||||
|
||||
// accessToken wins when both are present: providers like vertex-deepseek-ocr resolve a
|
||||
// short-lived OAuth token from a Service Account JSON apiKey (see resolveVertexOcrAccessToken
|
||||
// in src/app/api/v1/ocr/route.ts) while keeping the original apiKey around for other
|
||||
|
||||
@@ -31,10 +31,7 @@ import { sanitizeToolId } from "../translator/helpers/schemaCoercion.ts";
|
||||
import { stripGeminiPlaceholderArgs } from "../translator/helpers/geminiPlaceholderArgs.ts";
|
||||
import { stripEmptyOptionalToolArgs } from "../translator/response/openai-responses/pureHelpers.ts";
|
||||
import { toNumber as toFiniteNumber } from "../utils/numeric.ts";
|
||||
import {
|
||||
geminiCandidatesTokenCount,
|
||||
geminiExtraUsageCounts,
|
||||
} from "../translator/response/geminiUsageMetadata.ts";
|
||||
import { geminiExtraUsageCounts } from "../translator/response/geminiUsageMetadata.ts";
|
||||
import {
|
||||
extractThinkingFromContent,
|
||||
shouldParseTextualReasoningTags,
|
||||
@@ -1052,10 +1049,8 @@ function convertOpenAINonStreamingToGeminiFamily(openaiResponse: JsonRecord): Js
|
||||
OPENAI_TO_GEMINI_FINISH_REASON[toString(choice.finish_reason, "stop")] ?? "STOP";
|
||||
|
||||
const usageSrc = toRecord(openaiResponse.usage);
|
||||
// Some OpenAI-compatible upstreams report the Responses names (input/output_tokens).
|
||||
const promptTokens = toFiniteNumber(usageSrc.prompt_tokens ?? usageSrc.input_tokens, 0);
|
||||
const completionTokens = toFiniteNumber(usageSrc.completion_tokens ?? usageSrc.output_tokens, 0);
|
||||
const extraUsage = geminiExtraUsageCounts(usageSrc);
|
||||
const promptTokens = toFiniteNumber(usageSrc.prompt_tokens, 0);
|
||||
const completionTokens = toFiniteNumber(usageSrc.completion_tokens, 0);
|
||||
|
||||
const geminiResponse: JsonRecord = {
|
||||
response: {
|
||||
@@ -1068,12 +1063,9 @@ function convertOpenAINonStreamingToGeminiFamily(openaiResponse: JsonRecord): Js
|
||||
],
|
||||
usageMetadata: {
|
||||
promptTokenCount: promptTokens,
|
||||
candidatesTokenCount: geminiCandidatesTokenCount(
|
||||
completionTokens,
|
||||
extraUsage.thoughtsTokenCount
|
||||
),
|
||||
candidatesTokenCount: completionTokens,
|
||||
totalTokenCount: toFiniteNumber(usageSrc.total_tokens, promptTokens + completionTokens),
|
||||
...extraUsage,
|
||||
...geminiExtraUsageCounts(usageSrc),
|
||||
},
|
||||
modelVersion: toString(openaiResponse.model, "unknown"),
|
||||
responseId: toString(openaiResponse.id, `resp_${Date.now()}`),
|
||||
|
||||
@@ -1474,8 +1474,6 @@ export function recordProviderSuccess(
|
||||
* Reset the shared provider breaker.
|
||||
*/
|
||||
export function clearProviderFailure(provider: string | null | undefined): void {
|
||||
// recordProviderFailure stores its dedupe keys under the canonical id, so resolve an alias first.
|
||||
if (provider) provider = resolveProviderId(provider);
|
||||
if (provider) lastNetworkErrorByProvider.delete(provider); // #13887: fresh blip after reset counts
|
||||
for (const key of lastConnectionFailure.keys())
|
||||
if (provider && key.startsWith(`${provider}:`)) lastConnectionFailure.delete(key);
|
||||
@@ -2718,9 +2716,6 @@ export function filterAvailableAccounts<T extends AccountState>(
|
||||
const now = Date.now();
|
||||
return accounts.filter((acc) => {
|
||||
if (excludeId && acc.id === excludeId) return false;
|
||||
if (acc.status === "banned" || acc.status === "expired" || acc.status === "credits_exhausted") {
|
||||
return false;
|
||||
}
|
||||
if (acc.rateLimitedUntil) {
|
||||
const until = cooldownUntilMs(acc.rateLimitedUntil);
|
||||
if (Number.isFinite(until) && until > now) return false;
|
||||
|
||||
@@ -13,8 +13,6 @@ const CODEX_SOL_PAID_PLANS = new Set([
|
||||
"team",
|
||||
"chatgptteam",
|
||||
"business",
|
||||
// Business Premium: OAuth reports `self_serve_business_prolite` (see quotaPlanCapacity.ts).
|
||||
"selfservebusinessprolite",
|
||||
"enterprise",
|
||||
"edu",
|
||||
"education",
|
||||
|
||||
@@ -5,12 +5,7 @@
|
||||
* context-optimized, context-relay, and fusion strategies
|
||||
*/
|
||||
|
||||
import {
|
||||
errorResponse,
|
||||
errorResponseWithComboDiagnostics,
|
||||
sanitizeErrorMessage,
|
||||
} from "../utils/error.ts";
|
||||
import { logger } from "../utils/logger.ts";
|
||||
import { errorResponse, errorResponseWithComboDiagnostics } from "../utils/error.ts";
|
||||
import { isProviderSafetyStopsEnabled } from "../utils/providerSafety.ts";
|
||||
import { createChaosHeaderBarrier } from "./combo/chaosHeaderBarrier.ts";
|
||||
import { runComboWithSafetyLatch } from "./combo/safetyStopLatch.ts";
|
||||
@@ -384,8 +379,6 @@ export function maybeWarnBootstrapDominant(hasStats: boolean): void {
|
||||
console.warn(formatBootstrapWarning());
|
||||
}
|
||||
|
||||
const scopeReadLog = logger("COMBO_AUTO");
|
||||
|
||||
export async function buildAutoCandidates(
|
||||
targets: ResolvedComboTarget[],
|
||||
comboName: string,
|
||||
@@ -430,14 +423,8 @@ export async function buildAutoCandidates(
|
||||
for (const connection of connections) connectionById.set(connection.id, connection);
|
||||
}
|
||||
targetsForExpansion = expandTargetsWithinConnectionScope(targets, grouped, connectionScope);
|
||||
} catch (error) {
|
||||
// Fail open like the unscoped branch below. The caller already bound `targets` to
|
||||
// permitted connections (expandAutoComboCandidatePool), and credential selection
|
||||
// enforces the key's allowlist again at dispatch, so this only keeps scoring alive.
|
||||
scopeReadLog.warn("Scoped auto candidates: active connection read failed; keeping targets", {
|
||||
scopeSize: connectionScope.size,
|
||||
error: sanitizeErrorMessage(error instanceof Error ? error.message : String(error)),
|
||||
});
|
||||
} catch {
|
||||
targetsForExpansion = [];
|
||||
}
|
||||
} else {
|
||||
const uniqueProviders = Array.from(
|
||||
|
||||
@@ -686,13 +686,11 @@ export async function executeTargetAttempt(
|
||||
// (independent of universal handoff — always fires when context_cache_protection is on)
|
||||
// #3825: write under the SAME effectiveSessionId used by the read site so a
|
||||
// sessionless conversation re-pins to this model on its next turn.
|
||||
let recordedHistoryKey: string | null = null;
|
||||
if (
|
||||
deps.combo.context_cache_protection &&
|
||||
deps.effectiveSessionId &&
|
||||
!(deps.body as Record<string, unknown>)?.[SKIP_UNIVERSAL_HANDOFF_FLAG]
|
||||
) {
|
||||
recordedHistoryKey = deps.effectiveSessionId;
|
||||
recordSessionModelUsage(
|
||||
deps.effectiveSessionId,
|
||||
deps.combo.name,
|
||||
@@ -709,20 +707,16 @@ export async function executeTargetAttempt(
|
||||
!(deps.body as Record<string, unknown>)?.[SKIP_UNIVERSAL_HANDOFF_FLAG]
|
||||
) {
|
||||
const prevModel = getLastSessionModel(handoffSessionId, deps.combo.name);
|
||||
// One row per successful target. The context-cache block above already wrote this exact
|
||||
// row when both features share the session key.
|
||||
if (handoffSessionId !== recordedHistoryKey) {
|
||||
recordSessionModelUsage(
|
||||
handoffSessionId,
|
||||
deps.combo.name,
|
||||
modelStr,
|
||||
provider,
|
||||
target.connectionId ?? undefined
|
||||
);
|
||||
}
|
||||
recordSessionModelUsage(
|
||||
handoffSessionId,
|
||||
deps.combo.name,
|
||||
modelStr,
|
||||
provider,
|
||||
target.connectionId ?? undefined
|
||||
);
|
||||
// i === 0 only: a same-request fallback target (i > 0) never
|
||||
// needs a summary generated for it -- see the injection-site
|
||||
// comment above. The row recorded above stays
|
||||
// comment above. recordSessionModelUsage above stays
|
||||
// unconditional regardless of i: it must reflect whichever
|
||||
// model actually served THIS response, since the next
|
||||
// request's i === 0 comparison depends on that being
|
||||
@@ -745,6 +739,14 @@ export async function executeTargetAttempt(
|
||||
handleSingleModel: deps.handleSingleModelWithTimeout,
|
||||
});
|
||||
}
|
||||
|
||||
recordSessionModelUsage(
|
||||
handoffSessionId,
|
||||
deps.combo.name,
|
||||
modelStr,
|
||||
provider,
|
||||
target.connectionId ?? undefined
|
||||
);
|
||||
}
|
||||
// Context-relay intentionally splits responsibilities:
|
||||
// combo.ts decides whether a successful turn should generate a handoff,
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
// failures → 30min pause). Unrecoverable refresh errors (invalid_grant,
|
||||
// refresh_token_reused, …) short-circuit retries so the HealthCheck can
|
||||
// deactivate the account instead of looping every 60s.
|
||||
import { createHash } from "node:crypto";
|
||||
import { isPassiveCodex } from "./passiveCodex.ts";
|
||||
import type { RefreshLogger } from "./shared.ts";
|
||||
import { isUnrecoverableRefreshError, NO_REFRESH_NEEDED } from "./shared.ts";
|
||||
@@ -101,17 +100,6 @@ interface RefreshLoggerLike {
|
||||
warn?: (scope: string, message: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opt-in (TOKEN_REFRESH_RETRY_JITTER=1): scale a retry delay by 75-125 %, derived
|
||||
* from the account id and attempt. Replicas that share an id pick the same delay
|
||||
* (no random flakiness); different accounts spread out instead of retrying in lockstep.
|
||||
*/
|
||||
function jitteredRetryDelayMs(baseMs: number, accountId: string, attempt: number): number {
|
||||
if (process.env.TOKEN_REFRESH_RETRY_JITTER !== "1") return baseMs;
|
||||
const h = createHash("sha256").update(`${accountId}:${attempt}`).digest().readUInt32BE(0);
|
||||
return Math.round(baseMs * (0.75 + 0.5 * (h / 0x1_0000_0000)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a provider is circuit-breaker blocked.
|
||||
*/
|
||||
@@ -267,11 +255,7 @@ export async function refreshWithRetry(
|
||||
|
||||
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
||||
if (attempt > 0) {
|
||||
const delay = jitteredRetryDelayMs(
|
||||
attempt * 1000,
|
||||
options?.connectionId || provider,
|
||||
attempt
|
||||
);
|
||||
const delay = attempt * 1000;
|
||||
log?.debug?.("TOKEN_REFRESH", `Retry ${attempt}/${maxRetries} after ${delay}ms`);
|
||||
await new Promise((r) => setTimeout(r, delay));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
// Pure shared primitives for the OpenAI Responses <-> Chat Completions request
|
||||
// translators. Extracted verbatim from openai-responses.ts (no host imports).
|
||||
import { createHash } from "node:crypto";
|
||||
import { getProviderModels, supportsClaudeMaxEffort } from "../../../config/providerModels.ts";
|
||||
|
||||
export type JsonRecord = Record<string, unknown>;
|
||||
@@ -39,12 +38,8 @@ export function toRecord(value: unknown): JsonRecord {
|
||||
// Clamp deterministically so a function_call and its matching function_call_output keep
|
||||
// the same id and stay paired through the orphaned-output filter below.
|
||||
export const MAX_CALL_ID_LEN = 64;
|
||||
// A cut alone would merge ids that differ only at the end (`name:0`, `name:1`), so an over-long
|
||||
// id keeps 55 characters plus `_` plus 8 hex of its hash. Same id in, same id out.
|
||||
export function clampCallId(id: string): string {
|
||||
if (id.length <= MAX_CALL_ID_LEN) return id;
|
||||
const hash = createHash("sha256").update(id).digest("hex").slice(0, 8);
|
||||
return `${id.slice(0, MAX_CALL_ID_LEN - 9)}_${hash}`;
|
||||
return id.length > MAX_CALL_ID_LEN ? id.slice(0, MAX_CALL_ID_LEN) : id;
|
||||
}
|
||||
|
||||
export function toArray(value: unknown): unknown[] {
|
||||
|
||||
@@ -516,8 +516,7 @@ export function openaiToOpenAIResponsesRequest(
|
||||
type: "function",
|
||||
name,
|
||||
description: toString(fn.description),
|
||||
// Responses requires `parameters`; Chat lets a zero-argument tool omit it.
|
||||
parameters: fn.parameters ?? { type: "object", properties: {} },
|
||||
parameters: fn.parameters,
|
||||
// Omitted strict is non-strict on Chat but strict-normalized on Responses.
|
||||
strict: chatStrictForResponses(fn),
|
||||
...(credentialRecord._provider === "codex" && typeof fn.defer_loading === "boolean"
|
||||
|
||||
@@ -80,15 +80,7 @@ export function fitThinkingToMaxTokens(
|
||||
|
||||
// Cap too tight for any thinking — disable rather than send an invalid request.
|
||||
if (fittedBudget < MIN_CLAUDE_THINKING_BUDGET) {
|
||||
// Keep the caller's explicit cap (same clamp as the no-thinking branch above); only the model
|
||||
// cap may lower it. Returning the bare model cap raised a 256-token request to 64000.
|
||||
return {
|
||||
maxTokens:
|
||||
modelCap === null
|
||||
? Math.max(callerMaxTokens, 1)
|
||||
: Math.min(Math.max(callerMaxTokens, 1), modelCap),
|
||||
thinking: undefined,
|
||||
};
|
||||
return { maxTokens: modelCap ?? Math.max(callerMaxTokens, 1), thinking: undefined };
|
||||
}
|
||||
|
||||
const adjustedThinking: Record<string, unknown> = { ...thinking };
|
||||
|
||||
@@ -244,8 +244,7 @@ function toClovaToolModeMessage(message: unknown): JsonRecord {
|
||||
if (record.role === "assistant" && toolCalls.length > 0) {
|
||||
return {
|
||||
role: "assistant",
|
||||
// Keep the text the assistant wrote before the call; "" only when there is none.
|
||||
content: contentToString(record.content),
|
||||
content: "",
|
||||
toolCalls: toolCalls.map(toClovaToolCall),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -65,14 +65,6 @@ function buildToolResultBlock(toolName: string, toolCallId: string, resultText:
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
// A structured tool message carries the first line of its id, so the assistant call it answers
|
||||
// must carry the same id, or the pair no longer matches.
|
||||
function withPairedId<T extends { id?: unknown }>(toolCall: T): T {
|
||||
return typeof toolCall.id === "string"
|
||||
? { ...toolCall, id: normalizeToolCallId(toolCall.id) }
|
||||
: toolCall;
|
||||
}
|
||||
|
||||
function convertMessages(messages, preserveToolResults = false) {
|
||||
const result = [];
|
||||
// Build a map of tool_call_id -> tool name from assistant tool calls.
|
||||
@@ -160,9 +152,7 @@ function convertMessages(messages, preserveToolResults = false) {
|
||||
toolCallMetaMap.get(normalizeToolCallId(toolCallId));
|
||||
const toolName = toolMeta?.name || "tool";
|
||||
const toolContent = extractContent(tr.content);
|
||||
// Same id as the assistant call it answers (see withPairedId).
|
||||
const pairedId = preserveToolResults ? normalizeToolCallId(toolCallId) : toolCallId;
|
||||
parts.push(buildToolResultBlock(toolName, pairedId, toolContent));
|
||||
parts.push(buildToolResultBlock(toolName, toolCallId, toolContent));
|
||||
}
|
||||
}
|
||||
const joined = parts.filter(Boolean).join("\n");
|
||||
@@ -192,14 +182,14 @@ function convertMessages(messages, preserveToolResults = false) {
|
||||
} = { role: "assistant", content: content || "" };
|
||||
assistantMsg.tool_calls = msg.tool_calls.map((tc) => {
|
||||
const { index, ...rest } = tc || {};
|
||||
return preserveToolResults ? withPairedId(rest) : rest;
|
||||
return rest;
|
||||
});
|
||||
result.push(assistantMsg);
|
||||
} else if (msg.role === "assistant" && Array.isArray(msg.content)) {
|
||||
const extractedToolCalls = (msg.content as ToolUsePart[])
|
||||
.filter((b) => b?.type === "tool_use")
|
||||
.map((b) => ({
|
||||
id: preserveToolResults ? normalizeToolCallId(b.id) : b.id || "",
|
||||
id: b.id || "",
|
||||
type: "function",
|
||||
function: {
|
||||
name: b.name || "tool",
|
||||
|
||||
@@ -164,33 +164,6 @@ function hasFollowingToolResult(messages, index: number): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Kiro validates that every toolResults entry answers a toolUse of the assistant turn right
|
||||
// before it. An entry that does not (a truncated history, a duplicate or stray result) is moved
|
||||
// into the message text so its content is kept and only the pairing is dropped.
|
||||
function demoteUnpairedToolResults(userInputMessage, previousTurn) {
|
||||
const context = userInputMessage.userInputMessageContext;
|
||||
const useIds = new Set(
|
||||
(previousTurn?.assistantResponseMessage?.toolUses ?? []).map((u) => u.toolUseId)
|
||||
);
|
||||
const paired = [];
|
||||
const unpaired = [];
|
||||
for (const result of context.toolResults) {
|
||||
(useIds.has(result?.toolUseId) ? paired : unpaired).push(result);
|
||||
}
|
||||
if (unpaired.length === 0) return;
|
||||
|
||||
const texts = (unpaired as OrphanToolResult[]).map(orphanToolResultText).join("\n\n");
|
||||
const originalContent = userInputMessage.content || "";
|
||||
userInputMessage.content = originalContent ? `${originalContent}\n\n${texts}` : texts;
|
||||
|
||||
if (paired.length > 0) {
|
||||
context.toolResults = paired;
|
||||
return;
|
||||
}
|
||||
delete context.toolResults;
|
||||
if (Object.keys(context).length === 0) delete userInputMessage.userInputMessageContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert OpenAI messages to Kiro format
|
||||
* Rules: system/tool/user -> user role, merge consecutive same roles
|
||||
@@ -734,15 +707,49 @@ function convertMessages(messages, tools, model) {
|
||||
const item = mergedHistory[i];
|
||||
if (!item.userInputMessage?.userInputMessageContext?.toolResults) continue;
|
||||
|
||||
demoteUnpairedToolResults(item.userInputMessage, mergedHistory[i - 1]);
|
||||
const prev = mergedHistory[i - 1];
|
||||
const hasPrecedingAssistant =
|
||||
prev?.assistantResponseMessage?.toolUses && prev.assistantResponseMessage.toolUses.length > 0;
|
||||
|
||||
if (!hasPrecedingAssistant) {
|
||||
const toolResults = item.userInputMessage.userInputMessageContext
|
||||
.toolResults as OrphanToolResult[];
|
||||
const toolResultTexts = toolResults.map(orphanToolResultText).join("\n\n");
|
||||
|
||||
const originalContent = item.userInputMessage.content || "";
|
||||
item.userInputMessage.content = originalContent
|
||||
? `${originalContent}\n\n${toolResultTexts}`
|
||||
: toolResultTexts;
|
||||
delete item.userInputMessage.userInputMessageContext.toolResults;
|
||||
|
||||
if (Object.keys(item.userInputMessage.userInputMessageContext).length === 0) {
|
||||
delete item.userInputMessage.userInputMessageContext;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Also check currentMessage for orphaned toolResults (not in history)
|
||||
if (currentMessage?.userInputMessage?.userInputMessageContext?.toolResults) {
|
||||
demoteUnpairedToolResults(
|
||||
currentMessage.userInputMessage,
|
||||
mergedHistory[mergedHistory.length - 1]
|
||||
);
|
||||
const lastHistory = mergedHistory[mergedHistory.length - 1];
|
||||
const hasPrecedingAssistant =
|
||||
lastHistory?.assistantResponseMessage?.toolUses &&
|
||||
lastHistory.assistantResponseMessage.toolUses.length > 0;
|
||||
|
||||
if (!hasPrecedingAssistant) {
|
||||
const toolResults = currentMessage.userInputMessage.userInputMessageContext
|
||||
.toolResults as OrphanToolResult[];
|
||||
const toolResultTexts = toolResults.map(orphanToolResultText).join("\n\n");
|
||||
|
||||
const originalContent = currentMessage.userInputMessage.content || "";
|
||||
currentMessage.userInputMessage.content = originalContent
|
||||
? `${originalContent}\n\n${toolResultTexts}`
|
||||
: toolResultTexts;
|
||||
delete currentMessage.userInputMessage.userInputMessageContext.toolResults;
|
||||
|
||||
if (Object.keys(currentMessage.userInputMessage.userInputMessageContext).length === 0) {
|
||||
delete currentMessage.userInputMessage.userInputMessageContext;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Strip orphaned toolUses: an assistantResponseMessage that advertises a
|
||||
|
||||
@@ -143,9 +143,6 @@ export function geminiToClaudeResponse(chunk, state) {
|
||||
// Handle Antigravity wrapper
|
||||
const response = chunk.response || chunk;
|
||||
if (!response || !response.candidates?.[0]) return null;
|
||||
// message_stop closed the stream; a later chunk (for example a trailing usage chunk that
|
||||
// repeats finishReason) must not add events after it.
|
||||
if (state.claudeFinishEmitted) return null;
|
||||
|
||||
const results = [];
|
||||
const candidate = response.candidates[0];
|
||||
@@ -502,7 +499,6 @@ export function geminiToClaudeResponse(chunk, state) {
|
||||
usage: state.usage || { input_tokens: 0, output_tokens: 0 },
|
||||
});
|
||||
results.push({ type: "message_stop" });
|
||||
state.claudeFinishEmitted = true;
|
||||
}
|
||||
|
||||
return results.length > 0 ? results : null;
|
||||
|
||||
@@ -19,11 +19,6 @@ export interface OpenAIUsage {
|
||||
total_tokens?: number;
|
||||
prompt_tokens_details?: { cached_tokens?: number };
|
||||
completion_tokens_details?: { reasoning_tokens?: number };
|
||||
// Responses naming: some OpenAI-compatible upstreams report these instead.
|
||||
input_tokens?: number;
|
||||
output_tokens?: number;
|
||||
input_tokens_details?: { cached_tokens?: number };
|
||||
output_tokens_details?: { reasoning_tokens?: number };
|
||||
}
|
||||
|
||||
/** Per-stream flag: `usageMetadata` already reached the client. */
|
||||
@@ -49,29 +44,19 @@ export function geminiExtraUsageCounts(
|
||||
): Pick<GeminiUsageMetadata, "thoughtsTokenCount" | "cachedContentTokenCount"> {
|
||||
const u = (usage ?? {}) as OpenAIUsage;
|
||||
const out: Pick<GeminiUsageMetadata, "thoughtsTokenCount" | "cachedContentTokenCount"> = {};
|
||||
const reasoning =
|
||||
u.completion_tokens_details?.reasoning_tokens ?? u.output_tokens_details?.reasoning_tokens;
|
||||
const reasoning = u.completion_tokens_details?.reasoning_tokens;
|
||||
if (reasoning) out.thoughtsTokenCount = reasoning;
|
||||
const cached = u.prompt_tokens_details?.cached_tokens ?? u.input_tokens_details?.cached_tokens;
|
||||
const cached = u.prompt_tokens_details?.cached_tokens;
|
||||
if (cached) out.cachedContentTokenCount = cached;
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Gemini `candidatesTokenCount` excludes thoughts; OpenAI `completion_tokens` includes them. */
|
||||
export function geminiCandidatesTokenCount(completionTokens: number, thoughtsTokenCount = 0) {
|
||||
return Math.max(0, completionTokens - thoughtsTokenCount);
|
||||
}
|
||||
|
||||
export function buildGeminiUsageMetadata(usage: OpenAIUsage): GeminiUsageMetadata {
|
||||
const extra = geminiExtraUsageCounts(usage);
|
||||
return {
|
||||
promptTokenCount: usage.prompt_tokens || usage.input_tokens || 0,
|
||||
candidatesTokenCount: geminiCandidatesTokenCount(
|
||||
usage.completion_tokens || usage.output_tokens || 0,
|
||||
extra.thoughtsTokenCount
|
||||
),
|
||||
promptTokenCount: usage.prompt_tokens || 0,
|
||||
candidatesTokenCount: usage.completion_tokens || 0,
|
||||
totalTokenCount: usage.total_tokens || 0,
|
||||
...extra,
|
||||
...geminiExtraUsageCounts(usage),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -83,8 +83,6 @@ export function openaiToAntigravityResponse(chunk, state) {
|
||||
},
|
||||
});
|
||||
}
|
||||
// A repeated finish chunk must not emit the same calls again.
|
||||
state._toolCallAccum = {};
|
||||
}
|
||||
|
||||
// Skip empty non-finish chunks
|
||||
|
||||
@@ -185,8 +185,6 @@ export function openAIChunkToGeminiChunk(
|
||||
}
|
||||
parts.push({ functionCall: { name: entry.name, args } });
|
||||
}
|
||||
// A repeated finish chunk must not emit the same calls again.
|
||||
state.toolCallAccum = {};
|
||||
}
|
||||
|
||||
// Skip pure role-only deltas with no content and no finish signal.
|
||||
|
||||
@@ -290,7 +290,7 @@ function mentionsName(query: string, name: string): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
export function collectHistoryToolNames(body: unknown, into: Set<string>): void {
|
||||
function collectHistoryToolNames(body: unknown, into: Set<string>): void {
|
||||
for (const raw of conversationItems(body)) {
|
||||
if (!raw || typeof raw !== "object") continue;
|
||||
const item = raw as ToolRecord;
|
||||
|
||||
@@ -1153,11 +1153,11 @@ export function logUsage(
|
||||
? normalizedConnectionId.slice(0, 8) + "..."
|
||||
: "unknown";
|
||||
|
||||
let msg = `[${getTimeString()}] 📊 ${COLORS.green}[USAGE] ${p} | in=${evidence.input.source === "estimated" ? "~" : ""}${inTokens} | out=${evidence.output.source === "estimated" ? "~" : ""}${outTokens} | account=${accountPrefix}`;
|
||||
let msg = `[${getTimeString()}] 📊 ${COLORS.green}[USAGE] ${p} | in=${evidence.input.source === "estimated" ? "~" : ""}${inTokens} | out=${evidence.output.source === "estimated" ? "~" : ""}${outTokens} | account=${accountPrefix}${COLORS.reset}`;
|
||||
|
||||
// Add estimated flag if present
|
||||
if (usage.estimated) {
|
||||
msg += ` ${COLORS.yellow}(estimated)${COLORS.green}`;
|
||||
msg += ` ${COLORS.yellow}(estimated)${COLORS.reset}`;
|
||||
}
|
||||
|
||||
// Add cache info if present (unified from different formats)
|
||||
@@ -1175,7 +1175,7 @@ export function logUsage(
|
||||
const reasoning = usage.reasoning_tokens;
|
||||
if (reasoning) msg += ` | reasoning=${reasoning}`;
|
||||
|
||||
console.log(msg + COLORS.reset);
|
||||
console.log(msg);
|
||||
|
||||
// Streaming requests persist usage once in chatCore's completion callback.
|
||||
// This diagnostic request-log append is separate from durable token accounting.
|
||||
|
||||
@@ -1,20 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
# scripts/release/preflight-bun-apt-smoke.sh — proves Dockerfile.bun's `runner-web` stage installs
|
||||
# on the Bun base image and that its Chromium launches, WITHOUT the 12 GB Next build the real stage
|
||||
# sits on.
|
||||
# scripts/release/preflight-bun-apt-smoke.sh — proves the apt list of Dockerfile.bun's `runner-web`
|
||||
# stage installs on the Bun base image, WITHOUT the 12 GB Next build the real stage sits on.
|
||||
#
|
||||
# The stage is `continue-on-error` in docker-publish.yml, so a broken install (dead apt packages
|
||||
# such as gconf-service, stdc++6, fonts-kacst on v3.8.52 — #17236) never fails the build job; it
|
||||
# only surfaced when the manifest guard tripped over the missing bun-web digest (#17223). And a
|
||||
# stage that installs fine can still ship a browser Playwright cannot find: 3.8.54-web-bun had
|
||||
# Debian's chromium but nothing under PLAYWRIGHT_BROWSERS_PATH, so chromium.launch() failed.
|
||||
#
|
||||
# This smoke replays the stage itself (FROM runner-base AS runner-web, every instruction up to the
|
||||
# next FROM) in a throwaway image on a Docker host (default: the .113 build VPS, which the devbox
|
||||
# reaches over ssh; set PREFLIGHT_DOCKER_HOST="" to build locally). The checkout's playwright and
|
||||
# playwright-core packages stand in for the standalone build's node_modules. As the bun user it then
|
||||
# launches Chromium through Playwright headless, headed under a private Xvfb, and through the
|
||||
# /usr/bin/chromium path the system-browser lookups use.
|
||||
# The stage is `continue-on-error` in docker-publish.yml, so a dead package (gconf-service,
|
||||
# stdc++6, fonts-kacst on v3.8.52 — #17236) never fails the build job; it only surfaced when the
|
||||
# manifest guard tripped over the missing bun-web digest (#17223). This smoke runs the same
|
||||
# `apt-get install` block in a throwaway image on a Docker host (default: the .113 build VPS, which
|
||||
# the devbox reaches over ssh; set PREFLIGHT_DOCKER_HOST="" to build locally) and asks the installed
|
||||
# Chromium for its version.
|
||||
#
|
||||
# Usage: scripts/release/preflight-bun-apt-smoke.sh [Dockerfile.bun]
|
||||
# Env: PREFLIGHT_DOCKER_HOST ssh target with Docker (default root@192.168.0.113); "" = local docker
|
||||
@@ -23,84 +16,33 @@ ROOT=$(git rev-parse --show-toplevel)
|
||||
DOCKERFILE=${1:-"$ROOT/Dockerfile.bun"}
|
||||
HOST=${PREFLIGHT_DOCKER_HOST-root@192.168.0.113}
|
||||
OUT="$ROOT/_artifacts/preflight"
|
||||
CTX="$OUT/bun-web-smoke"
|
||||
REMOTE_CTX=/tmp/omniroute-bun-web-smoke
|
||||
mkdir -p "$OUT"
|
||||
SMOKE="$OUT/bun-apt-smoke.Dockerfile"
|
||||
|
||||
BASE=$(awk '/^FROM .* AS runner-base$/ { print $2; exit }' "$DOCKERFILE")
|
||||
[ -n "$BASE" ] || { echo "runner-base FROM line not found in $DOCKERFILE" >&2; exit 2; }
|
||||
# Every instruction of the runner-web stage, verbatim, minus its ENTRYPOINT.
|
||||
STAGE=$(awk '
|
||||
# The RUN apt-get … block of the runner-web stage, verbatim (first RUN after its FROM).
|
||||
APT_BLOCK=$(awk '
|
||||
/^FROM runner-base AS runner-web$/ { stage = 1; next }
|
||||
stage && /^FROM / { exit }
|
||||
stage && !/^ENTRYPOINT / { print }
|
||||
stage && /^RUN apt-get/ { grab = 1 }
|
||||
grab { print }
|
||||
grab && !/\\$/ { exit }
|
||||
' "$DOCKERFILE")
|
||||
[ -n "$STAGE" ] || { echo "runner-web stage not found in $DOCKERFILE" >&2; exit 2; }
|
||||
|
||||
for pkg in playwright playwright-core; do
|
||||
[ -f "$ROOT/node_modules/$pkg/package.json" ] || {
|
||||
echo "node_modules/$pkg missing — run npm ci first" >&2
|
||||
exit 2
|
||||
}
|
||||
done
|
||||
|
||||
rm -rf "$CTX"
|
||||
mkdir -p "$CTX/node_modules"
|
||||
cp -rL "$ROOT/node_modules/playwright" "$ROOT/node_modules/playwright-core" "$CTX/node_modules/"
|
||||
|
||||
cat > "$CTX/probe.cjs" <<'PROBE'
|
||||
// Launches Chromium the three ways the app does; any failure exits 1.
|
||||
const { spawn } = require("node:child_process");
|
||||
const { chromium } = require("/app/node_modules/playwright-core");
|
||||
|
||||
async function launch(label, options) {
|
||||
const browser = await chromium.launch({ args: ["--no-sandbox"], ...options });
|
||||
const page = await (await browser.newContext()).newPage();
|
||||
await page.setContent("<title>ok</title>");
|
||||
if ((await page.title()) !== "ok") throw new Error(`${label}: page did not render`);
|
||||
console.log(`[probe] ${label} OK (Chromium ${browser.version()})`);
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const xvfb = spawn("Xvfb", [":99", "-screen", "0", "1280x800x24"], { stdio: "ignore" });
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
try {
|
||||
await launch("headless", { headless: true });
|
||||
await launch("headed under Xvfb", { headless: false, env: { ...process.env, DISPLAY: ":99" } });
|
||||
await launch("/usr/bin/chromium", { headless: true, executablePath: "/usr/bin/chromium" });
|
||||
} finally {
|
||||
xvfb.kill();
|
||||
}
|
||||
})().catch((error) => {
|
||||
console.log(`[probe] FAIL: ${String(error && error.message).split("\n")[0]}`);
|
||||
process.exit(1);
|
||||
});
|
||||
PROBE
|
||||
[ -n "$APT_BLOCK" ] || { echo "runner-web apt block not found in $DOCKERFILE" >&2; exit 2; }
|
||||
|
||||
{
|
||||
echo "FROM $BASE"
|
||||
echo "WORKDIR /app"
|
||||
echo "COPY node_modules/ /app/node_modules/"
|
||||
printf '%s\n' "$STAGE"
|
||||
echo "COPY probe.cjs /tmp/probe.cjs"
|
||||
echo "RUN bun /tmp/probe.cjs"
|
||||
} > "$CTX/Dockerfile"
|
||||
echo "USER root"
|
||||
printf '%s\n' "$APT_BLOCK"
|
||||
echo 'RUN /usr/bin/chromium --version'
|
||||
} > "$SMOKE"
|
||||
|
||||
FILTER='\[probe\]|^#[0-9]+ (DONE|ERROR)|E: |Package .* (is not|has no)'
|
||||
echo "[bun-web-smoke] base=$BASE host=${HOST:-local}"
|
||||
# The build's exit status decides; grep only trims the log (and finds nothing on some failures).
|
||||
set +e
|
||||
echo "[bun-apt-smoke] base=$BASE host=${HOST:-local}"
|
||||
if [ -z "$HOST" ]; then
|
||||
docker build --no-cache --progress=plain -t omniroute-bun-web-smoke "$CTX" 2>&1 \
|
||||
| grep -E "$FILTER"
|
||||
status=${PIPESTATUS[0]}
|
||||
docker image rm -f omniroute-bun-web-smoke >/dev/null 2>&1
|
||||
docker build --no-cache -f "$SMOKE" -t omniroute-bun-apt-smoke "$OUT"
|
||||
else
|
||||
scp -q -o BatchMode=yes "$SMOKE" "$HOST:/tmp/omniroute-bun-apt-smoke.Dockerfile"
|
||||
# shellcheck disable=SC2029
|
||||
tar -C "$CTX" -czf - . | ssh -o BatchMode=yes "$HOST" \
|
||||
"rm -rf $REMOTE_CTX && mkdir -p $REMOTE_CTX && tar -xzf - -C $REMOTE_CTX && cd $REMOTE_CTX && docker build --no-cache --progress=plain -t omniroute-bun-web-smoke . 2>&1 | grep -E '$FILTER'; s=\${PIPESTATUS[0]}; docker image rm -f omniroute-bun-web-smoke >/dev/null 2>&1; rm -rf $REMOTE_CTX; exit \$s"
|
||||
status=$?
|
||||
ssh -o BatchMode=yes "$HOST" 'cd /tmp && docker build --no-cache -f omniroute-bun-apt-smoke.Dockerfile -t omniroute-bun-apt-smoke . 2>&1 | grep -E "^#[0-9]+ (DONE|ERROR)|E: |Chromium [0-9]|Package .* (is not|has no)" ; exit ${PIPESTATUS[0]}'
|
||||
fi
|
||||
set -e
|
||||
[ "$status" -eq 0 ] || { echo "[bun-web-smoke] ❌ runner-web failed on $BASE" >&2; exit "$status"; }
|
||||
echo "[bun-web-smoke] ✅ runner-web installs on $BASE and its Chromium launches"
|
||||
echo "[bun-apt-smoke] ✅ the runner-web apt list installs on $BASE"
|
||||
|
||||
@@ -25,26 +25,7 @@ import type { ToolBatchStatus, ToolBatchStatusMap } from "@/shared/types/cliBatc
|
||||
|
||||
const logger = pino({ name: "cli-tools-all-statuses-api" });
|
||||
|
||||
const TOOL_CHECK_TIMEOUT_MS = 5000; // 5s per tool max, counted from when its check starts
|
||||
// A cold batch used to start one detection probe per catalog tool (39) at once.
|
||||
const TOOL_CHECK_CONCURRENCY = 4;
|
||||
|
||||
/** At most `limit` holders at once; `acquire` waits for a free slot, `release` frees one. */
|
||||
function createSlots(limit: number) {
|
||||
let free = limit;
|
||||
const waiting: Array<() => void> = [];
|
||||
return {
|
||||
async acquire(): Promise<void> {
|
||||
if (free > 0) free--;
|
||||
else await new Promise<void>((resolve) => waiting.push(resolve));
|
||||
},
|
||||
release(): void {
|
||||
const next = waiting.shift();
|
||||
if (next) next();
|
||||
else free++;
|
||||
},
|
||||
};
|
||||
}
|
||||
const TOOL_CHECK_TIMEOUT_MS = 5000; // 5s per tool max
|
||||
|
||||
const getConfigPath = (toolId: string): string | null =>
|
||||
toolId === "grok-build"
|
||||
@@ -168,9 +149,7 @@ export async function GET(request: Request): Promise<Response> {
|
||||
})
|
||||
);
|
||||
|
||||
// For each tool: use cache hit, or run detection + config check. At most
|
||||
// TOOL_CHECK_CONCURRENCY uncached checks run at once; the rest wait for a free slot.
|
||||
const slots = createSlots(TOOL_CHECK_CONCURRENCY);
|
||||
// For each tool: use cache hit, or run detection + config check in parallel
|
||||
await Promise.allSettled(
|
||||
toolIds.map(async (toolId) => {
|
||||
const mtimeMs = mtimesMap[toolId] ?? 0;
|
||||
@@ -181,8 +160,6 @@ export async function GET(request: Request): Promise<Response> {
|
||||
return;
|
||||
}
|
||||
|
||||
await slots.acquire();
|
||||
|
||||
try {
|
||||
const runtimePromise = Promise.race<Awaited<ReturnType<typeof getCliRuntimeStatus>>>([
|
||||
getCliRuntimeStatus(toolId),
|
||||
@@ -242,8 +219,6 @@ export async function GET(request: Request): Promise<Response> {
|
||||
error: errMsg,
|
||||
};
|
||||
statuses[toolId] = result;
|
||||
} finally {
|
||||
slots.release();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
@@ -58,18 +58,6 @@ const migrateFeatureFlags = (doc: TomlDoc) =>
|
||||
_sections: doc as Record<string, Record<string, unknown>>,
|
||||
});
|
||||
|
||||
// A root openai_base_url is OmniRoute's only when it equals the base_url OmniRoute wrote into
|
||||
// [model_providers.omniroute] (or is about to write). Any other value is the user's own route.
|
||||
const trimUrl = (url: unknown) => (typeof url === "string" ? url.trim().replace(/\/+$/, "") : null);
|
||||
const deleteOwnedRootUrl = (doc: TomlDoc, ...ownedUrls: string[]) => {
|
||||
const current = trimUrl(doc.openai_base_url);
|
||||
const providers = asRecord(doc.model_providers);
|
||||
const owned = [asRecord(providers.omniroute).base_url, ...ownedUrls];
|
||||
if (current !== null && owned.some((url) => trimUrl(url) === current)) {
|
||||
delete doc.openai_base_url;
|
||||
}
|
||||
};
|
||||
|
||||
// Read current config.toml
|
||||
const readConfig = async () => {
|
||||
try {
|
||||
@@ -210,9 +198,6 @@ export async function POST(request: Request) {
|
||||
const effectiveWireApi = wireApi ?? "responses";
|
||||
const normalizedBaseUrl = normalizeCodexBaseUrl(baseUrl, effectiveWireApi);
|
||||
|
||||
// Read the previous OmniRoute URL before the provider section is replaced below.
|
||||
deleteOwnedRootUrl(doc, normalizedBaseUrl);
|
||||
|
||||
// Always create a custom provider to reliably pass wire_api and use OMNIROUTE_API_KEY
|
||||
doc.model_provider = "omniroute";
|
||||
doc.model_providers = {
|
||||
@@ -224,6 +209,7 @@ export async function POST(request: Request) {
|
||||
env_key: "OPENAI_API_KEY",
|
||||
},
|
||||
};
|
||||
delete doc.openai_base_url;
|
||||
|
||||
// Process model aliases into notice.model_migrations
|
||||
const notice = asRecord(doc.notice);
|
||||
@@ -310,7 +296,7 @@ export async function DELETE(request: Request) {
|
||||
migrateFeatureFlags(doc);
|
||||
|
||||
// Remove OmniRoute related root fields
|
||||
deleteOwnedRootUrl(doc);
|
||||
delete doc.openai_base_url;
|
||||
|
||||
if (doc.model_provider === "omniroute") {
|
||||
delete doc.model;
|
||||
|
||||
@@ -1,20 +1,14 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { getProviderConnections } from "@/lib/db/providers";
|
||||
import { getCachedSettings } from "@/lib/db/readCache";
|
||||
import { getWalMaintenanceState } from "@/lib/db/walMaintenance";
|
||||
import {
|
||||
buildHealthPayload,
|
||||
countStaleDbNonOkConnections,
|
||||
summarizeConnectionCooldown,
|
||||
} from "@/lib/monitoring/observability";
|
||||
import { buildHealthPayload } from "@/lib/monitoring/observability";
|
||||
import { getEventLoopStallStats as readEventLoopStallStats } from "@/lib/healthzLag";
|
||||
import { readRunningBuildSha } from "@/lib/monitoring/buildSha";
|
||||
import { APP_CONFIG } from "@/shared/constants/config";
|
||||
import { AI_PROVIDERS } from "@/shared/constants/providers";
|
||||
import { isAuthenticated } from "@/shared/utils/apiAuth";
|
||||
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
|
||||
import { buildErrorBody } from "@omniroute/open-sse/utils/error";
|
||||
|
||||
/**
|
||||
* GET /api/monitoring/health — System health overview
|
||||
@@ -134,61 +128,8 @@ function refreshDeepHealthVerdict(): void {
|
||||
});
|
||||
}
|
||||
|
||||
// ?provider=<id>[&unhealthRatioThreshold=0..1]: one provider pool as counts plus one verdict, so a
|
||||
// plain uptime monitor can alert on pool degradation from the HTTP status alone. An active account
|
||||
// is unhealthy when its stored test status is a known non-ok or it is cooling down. A pool with no
|
||||
// active account counts as fully unhealthy. Counts only: no account name, id or key leaves here.
|
||||
const poolQuerySchema = z.object({
|
||||
provider: z.string().trim().min(1).max(64),
|
||||
unhealthRatioThreshold: z.coerce.number().min(0).max(1).default(0.5),
|
||||
});
|
||||
|
||||
async function poolHealthResponse(request: Request, authError: Response | null) {
|
||||
if (authError) return authError;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const parsed = poolQuerySchema.safeParse({
|
||||
provider: searchParams.get("provider") || undefined,
|
||||
unhealthRatioThreshold: searchParams.get("unhealthRatioThreshold") || undefined,
|
||||
});
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
buildErrorBody(400, parsed.error.issues[0]?.message ?? "Invalid query parameters"),
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const { provider, unhealthRatioThreshold } = parsed.data;
|
||||
const connections = await getProviderConnections({ provider, isActive: true });
|
||||
const nowMs = Date.now();
|
||||
const unhealthy = connections.filter(
|
||||
(connection) =>
|
||||
countStaleDbNonOkConnections([connection]) > 0 ||
|
||||
Object.keys(summarizeConnectionCooldown([connection], nowMs)).length > 0
|
||||
).length;
|
||||
const total = connections.length;
|
||||
// Judge on the exact ratio; round only the value shown in the body (1/3 must fail a 0.33 bar).
|
||||
const exactRatio = total === 0 ? 1 : unhealthy / total;
|
||||
const unhealthyRatio = Math.round(exactRatio * 100) / 100;
|
||||
const summaryHealth = exactRatio <= unhealthRatioThreshold;
|
||||
return NextResponse.json(
|
||||
{
|
||||
provider,
|
||||
total,
|
||||
healthy: total - unhealthy,
|
||||
unhealthy,
|
||||
unhealthyRatio,
|
||||
unhealthRatioThreshold,
|
||||
summaryHealth,
|
||||
},
|
||||
{ status: summaryHealth ? 200 : 503 }
|
||||
);
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const authError = await requireManagementAuth(request, { alwaysRequireAuth: true });
|
||||
if (new URL(request.url).searchParams.has("provider")) {
|
||||
return poolHealthResponse(request, authError);
|
||||
}
|
||||
const fullView = authError === null;
|
||||
const fullView = (await requireManagementAuth(request, { alwaysRequireAuth: true })) === null;
|
||||
const wantDeep = fullView && isDeepHealthOptedIn(request);
|
||||
if (wantDeep) refreshDeepHealthVerdict();
|
||||
const cachedNow = Date.now();
|
||||
|
||||
@@ -11,11 +11,14 @@ import {
|
||||
getDailyUsage,
|
||||
getDailyCostRows,
|
||||
getHeatmapRows,
|
||||
getModelUsageRows,
|
||||
getProviderCostRows,
|
||||
getProviderUsageRows,
|
||||
getAccountCostRows,
|
||||
getAccountUsageRows,
|
||||
getApiKeyUsageRows,
|
||||
getApiKeyTotalsRows,
|
||||
getServiceTierUsageRows,
|
||||
getApiKeyMetadataRows,
|
||||
getWeeklyPatternRows,
|
||||
getPresetCostModelRows,
|
||||
@@ -254,8 +257,6 @@ async function computeAnalyticsResponse(
|
||||
>;
|
||||
|
||||
const dailyRows = getDailyUsage(unifiedSource, unifiedParams);
|
||||
// One grouped scan at day x provider x model x service tier feeds the daily cost, model,
|
||||
// provider cost and service-tier views below. Each used to run the same scan on its own.
|
||||
const dailyCostRows = getDailyCostRows(unifiedSource, unifiedParams);
|
||||
|
||||
const heatmapStart = new Date();
|
||||
@@ -280,9 +281,9 @@ async function computeAnalyticsResponse(
|
||||
|
||||
const heatmapRows = getHeatmapRows(heatmapConditions, heatmapParams);
|
||||
|
||||
const modelRows = [...dailyCostRows].sort((left, right) => right.requests - left.requests);
|
||||
const modelRows = getModelUsageRows(unifiedSource, unifiedParams);
|
||||
|
||||
const providerCostRows = dailyCostRows;
|
||||
const providerCostRows = getProviderCostRows(unifiedSource, unifiedParams);
|
||||
|
||||
const providerRows = getProviderUsageRows(unifiedSource, unifiedParams);
|
||||
|
||||
@@ -295,7 +296,7 @@ async function computeAnalyticsResponse(
|
||||
|
||||
const apiKeyRows = getApiKeyUsageRows(apiKeyWhereClause, params);
|
||||
|
||||
const serviceTierRows = dailyCostRows;
|
||||
const serviceTierRows = getServiceTierUsageRows(unifiedSource, unifiedParams);
|
||||
|
||||
const apiKeyMetadataRows = getApiKeyMetadataRows(apiKeyWhereClause, params);
|
||||
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
/**
|
||||
* Claude extra-usage monthly spend cap, as a pre-dispatch signal (#18059).
|
||||
*
|
||||
* A Claude connection that opted into extra usage (`blockExtraUsage === false`) bypasses the
|
||||
* plan-window quota filter, so an account whose plan windows AND monthly cap are both spent used
|
||||
* to stay eligible until the upstream "monthly spend limit" 429. The cap is tracked here, apart
|
||||
* from the plan windows, because it alone never makes an account ineligible: the plan windows
|
||||
* still serve requests while the cap is spent. Only the combination does.
|
||||
*/
|
||||
import {
|
||||
buildClaudeExtraUsageConnectionUpdate,
|
||||
isClaudeExtraUsageAllowed,
|
||||
} from "@/lib/providers/claudeExtraUsage";
|
||||
|
||||
type JsonRecord = Record<string, unknown>;
|
||||
|
||||
/** connectionId -> epoch ms at which the spent cap stops being trusted (next billing month). */
|
||||
const spentCapUntil = new Map<string, number>();
|
||||
|
||||
function asRecord(value: unknown): JsonRecord {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
|
||||
}
|
||||
|
||||
/** First instant of the next UTC month: where Anthropic's monthly spend cap rolls over. */
|
||||
function nextBillingMonthStartMs(now: number): number {
|
||||
const d = new Date(now);
|
||||
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1);
|
||||
}
|
||||
|
||||
/** True when the payload says extra usage is enabled and its monthly cap is fully spent. */
|
||||
export function isClaudeExtraUsageCapSpent(extraUsage: unknown): boolean {
|
||||
const eu = asRecord(extraUsage);
|
||||
if (eu.is_enabled !== true) return false;
|
||||
const { monthly_limit: limit, used_credits: used, utilization } = eu;
|
||||
if (typeof limit === "number" && limit > 0 && typeof used === "number") return used >= limit;
|
||||
return typeof utilization === "number" && utilization >= 100;
|
||||
}
|
||||
|
||||
/** Record the cap state from a fresh usage reading (a non-spent reading clears it). */
|
||||
export function recordClaudeExtraUsageCap(
|
||||
connectionId: string,
|
||||
provider: string | null | undefined,
|
||||
usage: unknown,
|
||||
now: number = Date.now()
|
||||
): void {
|
||||
if (provider !== "claude" || !connectionId) return;
|
||||
const record = asRecord(usage);
|
||||
if (!Object.prototype.hasOwnProperty.call(record, "extraUsage")) return;
|
||||
if (isClaudeExtraUsageCapSpent(record.extraUsage)) {
|
||||
spentCapUntil.set(connectionId, nextBillingMonthStartMs(now));
|
||||
} else {
|
||||
spentCapUntil.delete(connectionId);
|
||||
}
|
||||
}
|
||||
|
||||
/** True while the last reading showed a spent cap and the billing month has not rolled over. */
|
||||
export function isClaudeExtraUsageCapKnownSpent(
|
||||
connectionId: string,
|
||||
now: number = Date.now()
|
||||
): boolean {
|
||||
const until = spentCapUntil.get(connectionId);
|
||||
if (until === undefined) return false;
|
||||
if (now >= until) {
|
||||
spentCapUntil.delete(connectionId);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the operator's extra-usage opt-in makes cached plan windows irrelevant for this request.
|
||||
* It stops doing so once the monthly cap is known spent: the account then has no pay-as-you-go
|
||||
* headroom left, so the plan-window check applies again (exhausted plan windows + spent cap).
|
||||
*/
|
||||
export function isClaudeExtraUsageBypassingQuota(
|
||||
connectionId: string,
|
||||
provider: string,
|
||||
providerSpecificData: unknown
|
||||
): boolean {
|
||||
return (
|
||||
isClaudeExtraUsageAllowed(provider, providerSpecificData) &&
|
||||
!isClaudeExtraUsageCapKnownSpent(connectionId)
|
||||
);
|
||||
}
|
||||
|
||||
/** Records the cap, then builds the connection's extra-usage state update (one call site). */
|
||||
export function trackCapAndBuildClaudeExtraUsageUpdate(
|
||||
connection: Parameters<typeof buildClaudeExtraUsageConnectionUpdate>[0] & { id: string },
|
||||
usage: JsonRecord
|
||||
) {
|
||||
recordClaudeExtraUsageCap(connection.id, connection.provider, usage);
|
||||
return buildClaudeExtraUsageConnectionUpdate(connection, usage);
|
||||
}
|
||||
|
||||
export function __resetClaudeExtraUsageCapForTests(): void {
|
||||
spentCapUntil.clear();
|
||||
}
|
||||
@@ -45,7 +45,7 @@ import {
|
||||
type CodexPersistedQuotaState,
|
||||
} from "@omniroute/open-sse/services/codexAccount/index.ts";
|
||||
import { selectAntigravityQuotaWindowNames } from "@omniroute/open-sse/services/antigravityQuotaFamily.ts";
|
||||
import { isClaudeExtraUsageBypassingQuota } from "./claudeExtraUsageCap";
|
||||
import { isClaudeExtraUsageAllowed } from "@/lib/providers/claudeExtraUsage";
|
||||
import { filterCodexQuotaWindows } from "@omniroute/open-sse/services/codexQuotaWindowPolicy.ts";
|
||||
import { isCodexQuotaFilteringDisabled } from "@/lib/providers/codexQuotaFiltering";
|
||||
import { resolveProviderId } from "@/shared/constants/providers";
|
||||
@@ -759,7 +759,7 @@ function isQuotaFilterBypassed(
|
||||
if (provider === "codex") getQuotaCache(connectionId); // expire a replaced owner's override
|
||||
if (isQuotaHealthy(connectionId)) return true;
|
||||
if (isCodexQuotaFilteringDisabled(provider, providerSpecificData)) return true;
|
||||
if (isClaudeExtraUsageBypassingQuota(connectionId, provider, providerSpecificData)) return true;
|
||||
if (isClaudeExtraUsageAllowed(provider, providerSpecificData)) return true;
|
||||
// Subscription snapshots cannot decide paid-credit eligibility. The mandatory
|
||||
// Codex preflight checks the credit balance before dispatch; cooldowns remain separate.
|
||||
return isCodexPaidCreditsEnabled(provider, providerSpecificData, requestedModel);
|
||||
|
||||
@@ -516,20 +516,6 @@ export const OPTIONAL_BOOT_SUBSYSTEMS: ReadonlyArray<OptionalBootSubsystem> = [
|
||||
);
|
||||
}),
|
||||
},
|
||||
// Host wake recovery: opt-in (OMNIROUTE_WAKE_RECOVERY=1). Flushes pooled upstream sockets once
|
||||
// after the host resumes from sleep. Self-gated: the flag-off boot stays timer-free.
|
||||
{
|
||||
name: "wake-recovery",
|
||||
start: () =>
|
||||
import("@/lib/wakeRecovery")
|
||||
.then((m) => {
|
||||
if (m.startWakeRecovery()) console.log("[STARTUP] Wake recovery heartbeat started");
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
console.warn("[STARTUP] Wake recovery failed to start (non-fatal):", msg);
|
||||
}),
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,33 +1,29 @@
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
|
||||
import { mergeJsonConfig, readJsonValue } from "./jsonMerge.ts";
|
||||
|
||||
const CONFIG_PATH = path.join(os.homedir(), ".claude", "settings.json");
|
||||
|
||||
export function generateClaudeConfig(options: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
model?: string;
|
||||
configPath?: string;
|
||||
}): string {
|
||||
let base = options.baseUrl;
|
||||
let end = base.length;
|
||||
while (end > 0 && base[end - 1] === "/") end--;
|
||||
base = end < base.length ? base.slice(0, end) : base;
|
||||
if (base.endsWith("/v1")) base = base.slice(0, -3);
|
||||
const existingModel = readJsonValue(options.configPath, ["model"]);
|
||||
const model =
|
||||
options.model ||
|
||||
(typeof existingModel === "string" && existingModel) ||
|
||||
"claude-3-5-sonnet-20241022";
|
||||
const model = options.model || "claude-3-5-sonnet-20241022";
|
||||
|
||||
// Only these keys are OmniRoute's; permissions, hooks, statusLine and other env stay.
|
||||
return mergeJsonConfig(options.configPath, [
|
||||
[["model"], model],
|
||||
[["env", "ANTHROPIC_BASE_URL"], base],
|
||||
[["env", "ANTHROPIC_AUTH_TOKEN"], options.apiKey],
|
||||
[["env", "ANTHROPIC_MODEL"], model],
|
||||
[["env", "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"], "1"],
|
||||
]);
|
||||
const config = {
|
||||
model,
|
||||
env: {
|
||||
ANTHROPIC_BASE_URL: base,
|
||||
ANTHROPIC_AUTH_TOKEN: options.apiKey,
|
||||
ANTHROPIC_MODEL: model,
|
||||
CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: "1",
|
||||
},
|
||||
};
|
||||
|
||||
return JSON.stringify(config, null, 2);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
|
||||
import { mergeJsonConfig } from "./jsonMerge.ts";
|
||||
|
||||
const CONFIG_PATH = path.join(os.homedir(), ".cline", "data", "globalState.json");
|
||||
|
||||
export function generateClineConfig(options: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
model?: string;
|
||||
configPath?: string;
|
||||
}): string {
|
||||
let base = options.baseUrl;
|
||||
let end = base.length;
|
||||
@@ -17,8 +14,10 @@ export function generateClineConfig(options: {
|
||||
base = end < base.length ? base.slice(0, end) : base;
|
||||
if (base.endsWith("/v1")) base = base.slice(0, -3);
|
||||
|
||||
return mergeJsonConfig(options.configPath, [
|
||||
[["openAiBaseUrl"], `${base}/v1`],
|
||||
[["openAiApiKey"], options.apiKey],
|
||||
]);
|
||||
const config = {
|
||||
openAiBaseUrl: `${base}/v1`,
|
||||
openAiApiKey: options.apiKey,
|
||||
};
|
||||
|
||||
return JSON.stringify(config, null, 2);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
|
||||
import { readPrivateConfigFile } from "../privateConfigFile";
|
||||
|
||||
let yaml: typeof import("js-yaml") | null = null;
|
||||
async function loadYaml() {
|
||||
@@ -18,7 +15,6 @@ export async function generateContinueConfig(options: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
model?: string;
|
||||
configPath?: string;
|
||||
}): Promise<string> {
|
||||
const y = await loadYaml();
|
||||
let base = options.baseUrl;
|
||||
@@ -27,33 +23,15 @@ export async function generateContinueConfig(options: {
|
||||
base = end < base.length ? base.slice(0, end) : base;
|
||||
if (base.endsWith("/v1")) base = base.slice(0, -3);
|
||||
|
||||
// Keep the user's other keys and models; replace only the OmniRoute entry.
|
||||
let config: Record<string, unknown> = {};
|
||||
if (options.configPath && fs.existsSync(options.configPath)) {
|
||||
// Read errors (e.g. the symlink guard) propagate as they are; a file that does not parse
|
||||
// aborts Apply like the JSON generators do, instead of being replaced by a fresh document.
|
||||
const text = readPrivateConfigFile(options.configPath);
|
||||
let loaded: unknown;
|
||||
try {
|
||||
loaded = y.load(text);
|
||||
} catch {
|
||||
throw new Error(
|
||||
`Existing ${options.configPath} is not valid YAML; refusing to overwrite it.`
|
||||
);
|
||||
}
|
||||
if (loaded === null || loaded === undefined) loaded = {};
|
||||
if (typeof loaded !== "object" || Array.isArray(loaded)) {
|
||||
throw new Error(
|
||||
`Existing ${options.configPath} is not a valid YAML mapping; refusing to overwrite it.`
|
||||
);
|
||||
}
|
||||
config = loaded as Record<string, unknown>;
|
||||
}
|
||||
const entry = { title: "OmniRoute", apiKey: options.apiKey, apiBase: `${base}/v1` };
|
||||
const models = Array.isArray(config.models) ? (config.models as Array<{ title?: unknown }>) : [];
|
||||
const at = models.findIndex((m) => m?.title === "OmniRoute");
|
||||
config.models =
|
||||
at >= 0 ? models.map((m, i) => (i === at ? { ...m, ...entry } : m)) : [...models, entry];
|
||||
const config = {
|
||||
models: [
|
||||
{
|
||||
title: "OmniRoute",
|
||||
apiKey: options.apiKey,
|
||||
apiBase: `${base}/v1`,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return y.dump(config, { lineWidth: -1 });
|
||||
}
|
||||
|
||||
@@ -95,10 +95,6 @@ const PATH_AWARE_GENERATORS: Record<
|
||||
opencode: generateOpencodeConfig,
|
||||
codex: generateCodexConfig,
|
||||
whycodes: generateWhyCodesConfig,
|
||||
claude: generateClaudeConfig,
|
||||
cline: generateClineConfig,
|
||||
kilo: generateKilocodeConfig,
|
||||
continue: generateContinueConfig,
|
||||
};
|
||||
|
||||
export async function generateConfig(
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user