mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-11-24 04:43:07 +00:00
Compare commits
133 Commits
fix/21056-
...
fix/throug
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72556c31cd | ||
|
|
cd3e1a0b87 | ||
|
|
929be985f9 | ||
|
|
bdafbf9567 | ||
|
|
0c2877103c | ||
|
|
a539017d31 | ||
|
|
760e0ec783 | ||
|
|
3f8f2495bb | ||
|
|
58638f2697 | ||
|
|
198c82e9e3 | ||
|
|
a4a5e239bd | ||
|
|
2d4c466e1a | ||
|
|
713bf17cc7 | ||
|
|
8a47c93a4b | ||
|
|
3d8e392092 | ||
|
|
fa906f7ec2 | ||
|
|
c7d3b9cc2f | ||
|
|
791ec7fa9d | ||
|
|
a4d1449081 | ||
|
|
ab44955bbd | ||
|
|
486d8d2798 | ||
|
|
aaa0bf2eeb | ||
|
|
fe1508f987 | ||
|
|
6816b09b4b | ||
|
|
baf64267a0 | ||
|
|
ba68a6fdcf | ||
|
|
12a09c8831 | ||
|
|
d531353743 | ||
|
|
1f945369df | ||
|
|
b9d9732f16 | ||
|
|
4b61fc9381 | ||
|
|
09b4053eea | ||
|
|
321ffbe2c2 | ||
|
|
38d38c2825 | ||
|
|
63db262cc6 | ||
|
|
d6c64656eb | ||
|
|
2a48a0a823 | ||
|
|
6441b5b6f3 | ||
|
|
c13cee2357 | ||
|
|
eca9826d29 | ||
|
|
b03f265540 | ||
|
|
909af20270 | ||
|
|
59471c8d58 | ||
|
|
a91c7b8c06 | ||
|
|
83e890018d | ||
|
|
10c3883ef4 | ||
|
|
658402ca7f | ||
|
|
638e676ceb | ||
|
|
ca5e0e680c | ||
|
|
d17d44fffd | ||
|
|
73f02b9d74 | ||
|
|
8176f09487 | ||
|
|
b02e282ac7 | ||
|
|
8fb3258b83 | ||
|
|
5bfc0c0aa6 | ||
|
|
eaef73624b | ||
|
|
0813d37fd5 | ||
|
|
687f7effea | ||
|
|
ea623362f8 | ||
|
|
cdafb29e24 | ||
|
|
91906d5532 | ||
|
|
9e0ea19e9d | ||
|
|
5a021bf4ca | ||
|
|
cb2f162029 | ||
|
|
82ff9b48d1 | ||
|
|
4f24fe900f | ||
|
|
3933f8c3b0 | ||
|
|
a91df305a9 | ||
|
|
39fd3565e6 | ||
|
|
52f4e527dd | ||
|
|
a6a6694ac9 | ||
|
|
ebc6182076 | ||
|
|
3762f28f20 | ||
|
|
eed69f0041 | ||
|
|
272d1a73c9 | ||
|
|
e9548cb67d | ||
|
|
08e9c3ea72 | ||
|
|
3580391bd0 | ||
|
|
5fa63c10a8 | ||
|
|
511306251c | ||
|
|
53555c8fd3 | ||
|
|
c79305e945 | ||
|
|
561ff51c2d | ||
|
|
1f1c8c0d93 | ||
|
|
78c76407e5 | ||
|
|
871017e0d5 | ||
|
|
7a1b9d198e | ||
|
|
c40aaac629 | ||
|
|
3588f5ca79 | ||
|
|
7e69860ab1 | ||
|
|
63599ad10f | ||
|
|
b2e4554446 | ||
|
|
3aaeec83d8 | ||
|
|
5f21cec083 | ||
|
|
abd4533a39 | ||
|
|
2d0d3112ad | ||
|
|
6bb7f88d98 | ||
|
|
799279a67a | ||
|
|
d23a4fd5b2 | ||
|
|
5cbee02707 | ||
|
|
3249965f8a | ||
|
|
38dc13c18b | ||
|
|
d56a18406b | ||
|
|
62c7b123e5 | ||
|
|
648192b7dd | ||
|
|
bd1e271be3 | ||
|
|
95248b1b11 | ||
|
|
568c680261 | ||
|
|
2185c7a8db | ||
|
|
89186157dc | ||
|
|
a2897f3505 | ||
|
|
da0e3c2f4c | ||
|
|
74b42d209d | ||
|
|
024882f804 | ||
|
|
f253d9c2cc | ||
|
|
d6c39585fd | ||
|
|
8478ee6cb6 | ||
|
|
b8ac709829 | ||
|
|
d04c1541ff | ||
|
|
5333e6a223 | ||
|
|
aa0501aa49 | ||
|
|
7d8f2ed96e | ||
|
|
aaa6c2dc47 | ||
|
|
37dc6e6a9b | ||
|
|
55cb20e500 | ||
|
|
4e4bc8f799 | ||
|
|
b06e40e5a0 | ||
|
|
97379a6c7e | ||
|
|
55b62e9356 | ||
|
|
4c1c02f408 | ||
|
|
04596e0281 | ||
|
|
70993506ee | ||
|
|
65b5bdf7b5 |
19
.env.example
19
.env.example
@@ -1540,6 +1540,10 @@ 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.
|
||||
@@ -3307,6 +3311,21 @@ 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,6 +165,14 @@ 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:
|
||||
@@ -301,6 +309,24 @@ 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"
|
||||
@@ -313,9 +339,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
|
||||
npm run "check:$g" -- --base-ref "$PR_BASE_SHA" || failed+=("$g")
|
||||
run_gate npm run "check:$g" -- --base-ref "$PR_BASE_SHA" || failed+=("$g")
|
||||
else
|
||||
npm run "check:$g" || failed+=("$g")
|
||||
run_gate npm run "check:$g" || failed+=("$g")
|
||||
fi
|
||||
echo "::endgroup::"
|
||||
done
|
||||
@@ -327,20 +353,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
|
||||
npm run "check:$g" -- --ratchet --base-ref "$PR_BASE_SHA" || failed+=("$g")
|
||||
run_gate npm run "check:$g" -- --ratchet --base-ref "$PR_BASE_SHA" || failed+=("$g")
|
||||
else
|
||||
npm run "check:$g" -- --ratchet || failed+=("$g")
|
||||
run_gate npm run "check:$g" -- --ratchet || failed+=("$g")
|
||||
fi
|
||||
echo "::endgroup::"
|
||||
done
|
||||
echo "::group::typecheck:core"
|
||||
npm run typecheck:core || failed+=("typecheck:core")
|
||||
run_gate npm run typecheck:core || failed+=("typecheck:core")
|
||||
echo "::endgroup::"
|
||||
echo "::group::check:dashboard-typecheck"
|
||||
npm run check:dashboard-typecheck || failed+=("check:dashboard-typecheck")
|
||||
run_gate npm run check:dashboard-typecheck || failed+=("check:dashboard-typecheck")
|
||||
echo "::endgroup::"
|
||||
echo "::group::check:build-typecheck"
|
||||
npm run check:build-typecheck || failed+=("check:build-typecheck")
|
||||
run_gate 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
|
||||
@@ -348,7 +374,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"
|
||||
npm run check:ts7-diagnostics-ratchet -- --base-ref "$PR_BASE_SHA" || failed+=("ts7-diagnostics-ratchet")
|
||||
run_gate 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)
|
||||
|
||||
31
AGENTS.md
31
AGENTS.md
@@ -326,12 +326,33 @@ 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`.
|
||||
|
||||
### Sync-back landings are fast-forward, never squash
|
||||
### Landing on a release branch: omni-queue
|
||||
|
||||
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.
|
||||
`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.
|
||||
Steps + baseline-freeze check: `docs/ops/WORKTREE_ISOLATION.md` → "Sync-back landings".
|
||||
|
||||
---
|
||||
|
||||
@@ -117,50 +117,30 @@ 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 \
|
||||
&& 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 \
|
||||
&& 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 \
|
||||
&& 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,22 +2,29 @@ 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 } from "../sqlite.mjs";
|
||||
import { backupSqliteFile, withReadonlySqlite } from "../sqlite.mjs";
|
||||
import { CLI_TOKEN_HEADER, getCliToken } from "../utils/cliToken.mjs";
|
||||
|
||||
function getBackupDir() {
|
||||
@@ -96,6 +103,7 @@ 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);
|
||||
@@ -154,15 +162,56 @@ 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) =>
|
||||
return new Promise((resolve) => {
|
||||
// End of input (no TTY, closed pipe) answers with an empty passphrase instead of hanging.
|
||||
rl.once("close", () => resolve(""));
|
||||
rl.question(t("backup.passphrasePrompt"), (ans) => {
|
||||
rl.close();
|
||||
resolve(ans.trim());
|
||||
})
|
||||
);
|
||||
rl.close();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function pruneBackups(backupDir, retention) {
|
||||
@@ -464,20 +513,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`)));
|
||||
|
||||
// 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`)))
|
||||
) {
|
||||
// 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;
|
||||
console.error(
|
||||
`Backup ${backupId} is encrypted. restore cannot decrypt it; nothing was changed.`
|
||||
`A server answers at ${getBaseUrl()}. Stop it (omniroute stop) before restore; nothing was changed.`
|
||||
);
|
||||
return 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (await restoreBlockedByServer()) return 1;
|
||||
|
||||
if (!opts.yes) {
|
||||
const readline = await import("node:readline");
|
||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
@@ -489,17 +538,60 @@ 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;
|
||||
}
|
||||
|
||||
console.log(t("backup.restoring", { path: backupPath }));
|
||||
|
||||
const dataDir = resolveDataDir();
|
||||
// Decrypt every payload before touching live files. GCM rejects wrong keys and damaged data.
|
||||
let sourceDir = backupPath;
|
||||
let tempDir = null;
|
||||
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(backupPath, file.name);
|
||||
const sourcePath = join(sourceDir, file.name);
|
||||
if (existsSync(sourcePath)) {
|
||||
copyFileSync(sourcePath, join(dataDir, file.name));
|
||||
if (file.name === "storage.sqlite")
|
||||
installRestoredSqlite(sourcePath, join(dataDir, file.name));
|
||||
else copyFileSync(sourcePath, join(dataDir, file.name));
|
||||
restored++;
|
||||
console.log(`\x1b[2m Restored: ${file.name}\x1b[0m`);
|
||||
}
|
||||
@@ -513,5 +605,7 @@ 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 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,29 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { t } from "../i18n.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { discoverPlugins } from "../plugins.mjs";
|
||||
import { getPluginPrefix, resolvePluginSpec, runPluginNpm } from "../pluginNpm.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const HOST_MAJOR = Number(
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "package.json"),
|
||||
"utf8"
|
||||
)
|
||||
).version.split(".")[0]
|
||||
);
|
||||
const HOST_RANGE = `>=${HOST_MAJOR}.0.0`;
|
||||
// Run npm with an explicit argument array and no shell. Passing args this way
|
||||
// (instead of string-interpolating into `execSync`) prevents a malicious plugin
|
||||
// name like `foo; rm -rf ~` or `` foo`id` `` from being interpreted by the shell.
|
||||
function runNpm(args) {
|
||||
const isBun = Boolean(process.versions.bun);
|
||||
const pm = isBun ? "bun" : "npm";
|
||||
const cmdArgs = isBun && args[0] === "install" ? ["add", ...args.slice(1)] : args;
|
||||
const res = spawnSync(pm, cmdArgs, { stdio: "inherit", shell: false });
|
||||
if (res.error) throw res.error;
|
||||
if (typeof res.status === "number" && res.status !== 0) {
|
||||
throw new Error(`${pm} exited with code ${res.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
const TEMPLATE_INDEX = `export const meta = {
|
||||
name: "PLUGIN_NAME",
|
||||
version: "0.1.0",
|
||||
description: "OmniRoute plugin",
|
||||
omnirouteApi: "HOST_RANGE",
|
||||
omnirouteApi: ">=4.0.0",
|
||||
};
|
||||
|
||||
export function register(program, ctx) {
|
||||
@@ -64,7 +65,8 @@ export function registerPlugin(program) {
|
||||
.description(t("plugin.install") || "Install a plugin")
|
||||
.option("-y, --yes", "Skip confirmation prompt")
|
||||
.action(async (name, opts) => {
|
||||
const pkgName = resolvePluginSpec(name);
|
||||
const isLocal = name.startsWith("./") || name.startsWith("/") || name.startsWith("../");
|
||||
const pkgName = isLocal ? name : `omniroute-cmd-${name}`;
|
||||
|
||||
if (!opts.yes) {
|
||||
process.stderr.write(
|
||||
@@ -81,10 +83,10 @@ export function registerPlugin(program) {
|
||||
}
|
||||
|
||||
try {
|
||||
runPluginNpm(["install", "--prefix", getPluginPrefix(), pkgName]);
|
||||
runNpm(["install", "-g", pkgName]);
|
||||
process.stdout.write(`\n✓ Installed: ${pkgName}\n`);
|
||||
} catch (err) {
|
||||
process.stderr.write(`✗ Failed to install ${pkgName}: ${err.message}\n`);
|
||||
} catch {
|
||||
process.stderr.write(`✗ Failed to install ${pkgName}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
@@ -103,10 +105,10 @@ export function registerPlugin(program) {
|
||||
}
|
||||
}
|
||||
try {
|
||||
runPluginNpm(["uninstall", "--prefix", getPluginPrefix(), pkgName]);
|
||||
runNpm(["uninstall", "-g", pkgName]);
|
||||
process.stdout.write(`✓ Removed: ${pkgName}\n`);
|
||||
} catch (err) {
|
||||
process.stderr.write(`✗ Failed to remove ${pkgName}: ${err.message}\n`);
|
||||
} catch {
|
||||
process.stderr.write(`✗ Failed to remove ${pkgName}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
@@ -159,7 +161,7 @@ export function registerPlugin(program) {
|
||||
try {
|
||||
if (name) {
|
||||
const pkg = `omniroute-cmd-${name}`;
|
||||
runPluginNpm(["update", "--prefix", getPluginPrefix(), pkg]);
|
||||
runNpm(["update", "-g", pkg]);
|
||||
process.stdout.write(`✓ Updated: ${pkg}\n`);
|
||||
return;
|
||||
}
|
||||
@@ -174,10 +176,10 @@ export function registerPlugin(program) {
|
||||
process.stdout.write("No plugins installed to update.\n");
|
||||
return;
|
||||
}
|
||||
runPluginNpm(["update", "--prefix", getPluginPrefix(), ...names]);
|
||||
runNpm(["update", "-g", ...names]);
|
||||
process.stdout.write(`✓ Updated: ${names.join(", ")}\n`);
|
||||
} catch (err) {
|
||||
process.stderr.write(`✗ Update failed: ${err.message}\n`);
|
||||
} catch {
|
||||
process.stderr.write(`✗ Update failed\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
@@ -202,17 +204,14 @@ export function registerPlugin(program) {
|
||||
type: "module",
|
||||
main: "index.mjs",
|
||||
description: `OmniRoute CLI plugin: ${safeName}`,
|
||||
engines: { omniroute: HOST_RANGE },
|
||||
engines: { omniroute: ">=4.0.0" },
|
||||
keywords: ["omniroute-plugin", "omniroute-cmd"],
|
||||
},
|
||||
null,
|
||||
2
|
||||
) + "\n"
|
||||
);
|
||||
writeFileSync(
|
||||
join(dir, "index.mjs"),
|
||||
TEMPLATE_INDEX.replace(/PLUGIN_NAME/g, safeName).replace(/HOST_RANGE/g, HOST_RANGE)
|
||||
);
|
||||
writeFileSync(join(dir, "index.mjs"), TEMPLATE_INDEX.replace(/PLUGIN_NAME/g, safeName));
|
||||
writeFileSync(
|
||||
join(dir, "README.md"),
|
||||
`# omniroute-cmd-${safeName}\n\nAn OmniRoute CLI plugin.\n\n## Install\n\n\`\`\`bash\nomniroute plugin install ${safeName}\n\`\`\`\n`
|
||||
|
||||
@@ -287,6 +287,7 @@
|
||||
"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,82 +0,0 @@
|
||||
// npm plumbing for `omniroute plugin install|remove|update` (#21056).
|
||||
//
|
||||
// Plugins are installed into a private npm prefix (`~/.omniroute/plugins`), which is
|
||||
// the same directory `discoverPlugins()` scans — a global `npm install -g` landed in
|
||||
// `$(npm root -g)`, a place discovery never looked at.
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { homedir } from "node:os";
|
||||
import { isAbsolute, join, resolve } from "node:path";
|
||||
import { npmBin, npmExecInvocation, npmExecOptions } from "./npm-exec.mjs";
|
||||
import { escapeWindowsShellArg } from "./utils/winShellArgs.mjs";
|
||||
|
||||
const LITERAL_TOKEN = /^[A-Za-z0-9@._/:=+-]+$/;
|
||||
const UNSAFE_CHARS = /[\0\r\n]/;
|
||||
const WINDOWS_DRIVE_RE = /^[A-Za-z]:[\\/]/;
|
||||
|
||||
/** Where plugins are installed (an npm `--prefix`); `node_modules/` lives below it. */
|
||||
export function getPluginPrefix(home = homedir()) {
|
||||
return join(home, ".omniroute", "plugins");
|
||||
}
|
||||
|
||||
/** True when the user passed a path / file: spec rather than a registry name. */
|
||||
export function isLocalPluginSpec(name) {
|
||||
return (
|
||||
name === "." ||
|
||||
name === ".." ||
|
||||
name.startsWith("./") ||
|
||||
name.startsWith("../") ||
|
||||
name.startsWith(".\\") ||
|
||||
name.startsWith("..\\") ||
|
||||
name.startsWith("/") ||
|
||||
name.startsWith("~/") ||
|
||||
name.startsWith("file:") ||
|
||||
WINDOWS_DRIVE_RE.test(name) ||
|
||||
name.startsWith("\\\\")
|
||||
);
|
||||
}
|
||||
|
||||
/** Spec handed to npm: absolute path for local installs, `omniroute-cmd-<name>` otherwise. */
|
||||
export function resolvePluginSpec(name, cwd = process.cwd(), home = homedir()) {
|
||||
if (!isLocalPluginSpec(name)) {
|
||||
return name.startsWith("omniroute-cmd-") || name.startsWith("@")
|
||||
? name
|
||||
: `omniroute-cmd-${name}`;
|
||||
}
|
||||
if (name.startsWith("file:")) return name;
|
||||
if (name.startsWith("~/")) return join(home, name.slice(2));
|
||||
if (isAbsolute(name) || WINDOWS_DRIVE_RE.test(name) || name.startsWith("\\\\")) return name;
|
||||
return resolve(cwd, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build `[file, args, options]` for spawnSync. Tokens that are not plain literals are
|
||||
* validated (no NUL/newline, no leading "-") and, on win32, escaped before joining
|
||||
* (Hard Rule #13).
|
||||
*/
|
||||
export function buildPluginNpmInvocation(args, platform = process.platform) {
|
||||
const isBun = Boolean(process.versions.bun);
|
||||
const cmdArgs = isBun && args[0] === "install" ? ["add", ...args.slice(1)] : args;
|
||||
const bin = npmBin(platform);
|
||||
const opts = npmExecOptions(platform, { stdio: "inherit" });
|
||||
cmdArgs.forEach((token, i) => {
|
||||
if (
|
||||
typeof token !== "string" ||
|
||||
UNSAFE_CHARS.test(token) ||
|
||||
(i > 0 && token.startsWith("-") && !LITERAL_TOKEN.test(token))
|
||||
) {
|
||||
throw new Error(`Refusing unsafe npm argument ${JSON.stringify(token)}`);
|
||||
}
|
||||
});
|
||||
if (platform !== "win32") return npmExecInvocation(platform, bin, cmdArgs, opts);
|
||||
const line = [bin, ...cmdArgs.map((t) => (LITERAL_TOKEN.test(t) ? t : escapeWindowsShellArg(t)))];
|
||||
return [line.join(" "), [], opts];
|
||||
}
|
||||
|
||||
export function runPluginNpm(args, platform = process.platform) {
|
||||
const [file, fileArgs, opts] = buildPluginNpmInvocation(args, platform);
|
||||
const res = spawnSync(file, fileArgs, opts);
|
||||
if (res.error) throw res.error;
|
||||
if (typeof res.status === "number" && res.status !== 0) {
|
||||
throw new Error(`${file.split(" ")[0]} exited with code ${res.status}`);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { readdirSync, existsSync, readFileSync, statSync } from "node:fs";
|
||||
import { readdirSync, existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
import { pathToFileURL } from "node:url";
|
||||
@@ -6,51 +6,24 @@ import { pathToFileURL } from "node:url";
|
||||
const PLUGIN_PREFIX_RE = /^(@[^/]+\/)?omniroute-cmd-/;
|
||||
|
||||
function getPluginDirs() {
|
||||
const prefix = join(homedir(), ".omniroute", "plugins");
|
||||
// `omniroute plugin install` uses `prefix` as an npm --prefix, so packages land in
|
||||
// `<prefix>/node_modules` (#21056).
|
||||
return [prefix, join(prefix, "node_modules"), process.env.OMNIROUTE_PLUGIN_PATH].filter(Boolean);
|
||||
}
|
||||
|
||||
function isDir(path) {
|
||||
try {
|
||||
return statSync(path).isDirectory(); // follows symlinks (npm links local installs)
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function listCandidates(dir) {
|
||||
const out = [];
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
if (entry.name.startsWith(".")) continue;
|
||||
const full = join(dir, entry.name);
|
||||
if (!isDir(full)) continue;
|
||||
if (entry.name.startsWith("@")) {
|
||||
try {
|
||||
for (const sub of readdirSync(full)) out.push(join(full, sub));
|
||||
} catch {
|
||||
// ignore unreadable scope dir
|
||||
}
|
||||
} else {
|
||||
out.push(full);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
return [join(homedir(), ".omniroute", "plugins"), process.env.OMNIROUTE_PLUGIN_PATH].filter(
|
||||
Boolean
|
||||
);
|
||||
}
|
||||
|
||||
export async function discoverPlugins() {
|
||||
const found = [];
|
||||
for (const dir of getPluginDirs()) {
|
||||
if (!existsSync(dir)) continue;
|
||||
let candidates;
|
||||
let entries;
|
||||
try {
|
||||
candidates = listCandidates(dir);
|
||||
entries = readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const candidate of candidates) {
|
||||
const pkgPath = join(candidate, "package.json");
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
const pkgPath = join(dir, entry.name, "package.json");
|
||||
if (!existsSync(pkgPath)) continue;
|
||||
let pkg;
|
||||
try {
|
||||
@@ -59,12 +32,11 @@ export async function discoverPlugins() {
|
||||
continue;
|
||||
}
|
||||
if (!pkg.name || !PLUGIN_PREFIX_RE.test(pkg.name)) continue;
|
||||
if (found.some((f) => f.name === pkg.name)) continue;
|
||||
found.push({
|
||||
name: pkg.name,
|
||||
version: pkg.version || "0.0.0",
|
||||
description: pkg.description || "",
|
||||
dir: candidate,
|
||||
dir: join(dir, entry.name),
|
||||
pkg,
|
||||
});
|
||||
}
|
||||
@@ -95,12 +67,6 @@ export function buildPluginContext(opts = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
// Startup entry (#21056): `--version`/`-v` stays fast and never imports plugin code.
|
||||
export async function loadCliPlugins(program, argv = process.argv, env = process.env) {
|
||||
if (argv.slice(2).some((a) => a === "--version" || a === "-v")) return 0;
|
||||
return loadPlugins(program, { baseUrl: env.OMNIROUTE_BASE_URL, apiKey: env.OMNIROUTE_API_KEY });
|
||||
}
|
||||
|
||||
export async function loadPlugins(program, ctx = {}) {
|
||||
const plugins = await discoverPlugins();
|
||||
for (const p of plugins) {
|
||||
|
||||
@@ -449,10 +449,6 @@ try {
|
||||
pathToFileURL(join(ROOT, "bin", "cli", "program.mjs")).href
|
||||
);
|
||||
const program = createProgram();
|
||||
const { loadCliPlugins } = await import(
|
||||
pathToFileURL(join(ROOT, "bin", "cli", "plugins.mjs")).href
|
||||
);
|
||||
await loadCliPlugins(program);
|
||||
await program.parseAsync(process.argv);
|
||||
} catch (err) {
|
||||
if (err?.exitCode !== undefined) process.exit(err.exitCode);
|
||||
|
||||
1
changelog.d/features/client-retry-after-cap.md
Normal file
1
changelog.d/features/client-retry-after-cap.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/features/cpa-health-v8-path.md
Normal file
1
changelog.d/features/cpa-health-v8-path.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/features/google-refresh-gap.md
Normal file
1
changelog.d/features/google-refresh-gap.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/features/refresh-provider-concurrency.md
Normal file
1
changelog.d/features/refresh-provider-concurrency.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/features/refresh-retry-jitter.md
Normal file
1
changelog.d/features/refresh-retry-jitter.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/features/wake-recovery-flush.md
Normal file
1
changelog.d/features/wake-recovery-flush.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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.
|
||||
@@ -0,0 +1 @@
|
||||
- fix(claude): stop routing to an extra-usage-enabled Claude account whose plan windows and monthly spend cap are both exhausted (#18059)
|
||||
1
changelog.d/fixes/19633-cli-restore-stale-wal.md
Normal file
1
changelog.d/fixes/19633-cli-restore-stale-wal.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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))
|
||||
@@ -0,0 +1,2 @@
|
||||
- **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))
|
||||
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/19716-codex-settings-owned-urls.md
Normal file
1
changelog.d/fixes/19716-codex-settings-owned-urls.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/19716-pool-health-summary.md
Normal file
1
changelog.d/fixes/19716-pool-health-summary.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20197-cache-usage-meta-undefined.md
Normal file
1
changelog.d/fixes/20197-cache-usage-meta-undefined.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20197-claude-refusal-no-refresh.md
Normal file
1
changelog.d/fixes/20197-claude-refusal-no-refresh.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20197-claude-tool-type-falsy.md
Normal file
1
changelog.d/fixes/20197-claude-tool-type-falsy.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20197-combo-cache-failure.md
Normal file
1
changelog.d/fixes/20197-combo-cache-failure.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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))
|
||||
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20197-plugin-block-unserializable.md
Normal file
1
changelog.d/fixes/20197-plugin-block-unserializable.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20197-tool-cap-pins-used-tools.md
Normal file
1
changelog.d/fixes/20197-tool-cap-pins-used-tools.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20224-clova-assistant-tool-text.md
Normal file
1
changelog.d/fixes/20224-clova-assistant-tool-text.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20224-cursor-tool-call-id.md
Normal file
1
changelog.d/fixes/20224-cursor-tool-call-id.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20224-gemini-finish-flush-once.md
Normal file
1
changelog.d/fixes/20224-gemini-finish-flush-once.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20224-gemini-to-claude-finish-once.md
Normal file
1
changelog.d/fixes/20224-gemini-to-claude-finish-once.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20224-gemini-usage-metadata.md
Normal file
1
changelog.d/fixes/20224-gemini-usage-metadata.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20224-responses-call-id-clamp.md
Normal file
1
changelog.d/fixes/20224-responses-call-id-clamp.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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))
|
||||
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20229-account-fallback-alias-banned.md
Normal file
1
changelog.d/fixes/20229-account-fallback-alias-banned.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20229-ollama-local-embedding-key.md
Normal file
1
changelog.d/fixes/20229-ollama-local-embedding-key.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20229-opencode-zen-muse-vision.md
Normal file
1
changelog.d/fixes/20229-opencode-zen-muse-vision.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20229-scoped-auto-read-error.md
Normal file
1
changelog.d/fixes/20229-scoped-auto-read-error.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20229-session-model-history-once.md
Normal file
1
changelog.d/fixes/20229-session-model-history-once.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20339-kiro-orphan-tool-results.md
Normal file
1
changelog.d/fixes/20339-kiro-orphan-tool-results.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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))
|
||||
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20359-codex-business-premium-plan.md
Normal file
1
changelog.d/fixes/20359-codex-business-premium-plan.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20380-blocked-reply-no-memory.md
Normal file
1
changelog.d/fixes/20380-blocked-reply-no-memory.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20423-vertex-deepseek-ocr-retired.md
Normal file
1
changelog.d/fixes/20423-vertex-deepseek-ocr-retired.md
Normal file
@@ -0,0 +1 @@
|
||||
- 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
changelog.d/fixes/20548-usage-log-cache-colours.md
Normal file
1
changelog.d/fixes/20548-usage-log-cache-colours.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/fixes/20823-codeql-redos-model-ids.md
Normal file
1
changelog.d/fixes/20823-codeql-redos-model-ids.md
Normal file
@@ -0,0 +1 @@
|
||||
- **fix(security):** GitHub Copilot Responses-only inference, model display names and the Context7 library id check use linear regexes, so a long crafted model or library id no longer blocks the event loop for seconds (CodeQL js/polynomial-redos #1325, #1324, #1296)
|
||||
1
changelog.d/fixes/20825-compression-regex-bounds.md
Normal file
1
changelog.d/fixes/20825-compression-regex-bounds.md
Normal file
@@ -0,0 +1 @@
|
||||
- **fix(security):** Compression engines bound their regex work on hostile input: the headroom GCF inline-array check and the RTK raw-output command slug run in linear time, and CCR `grep` rejects patterns with more than one unbounded quantifier and stops a scan that exceeds a 1 s time budget (CodeQL #1301, #1302, #1349)
|
||||
@@ -0,0 +1 @@
|
||||
- **fix(security):** The remaining async media handlers (Kie image, video and music; Runway; DashScope; Novita; MiniMax video; the video job presets; RenderHour video and speech; UC image and video) cap a caller's `poll_interval_ms` at 30 s and `timeout_ms` at 10 minutes, or at the built-in default when that is longer; defaults are unchanged (CodeQL #1389) ([#20867](https://github.com/cheaper-inference/OmniRoute/pull/20867))
|
||||
@@ -0,0 +1 @@
|
||||
- **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 +0,0 @@
|
||||
- fix(cli): CLI plugins are now loaded at startup, `plugin install` uses the directory discovery scans (and `.`/local paths, npm.cmd on Windows), scaffold range matches the host version (#21056)
|
||||
1
changelog.d/fixes/21092-throughput-plausible-samples.md
Normal file
1
changelog.d/fixes/21092-throughput-plausible-samples.md
Normal file
@@ -0,0 +1 @@
|
||||
- **fix(usage):** tokens-per-second measurements ignore generation windows shorter than 250 ms and rates above 5,000 tok/s, so a response that arrives in one burst no longer reports hundreds of thousands of tok/s in `usage.tokens_per_second`, the `X-OmniRoute-Tokens-Per-Second` header or the model latency stats. The latency stats that feed speed-based routing now compute `avgTokensPerSecond` as total tokens over total generation time instead of a mean of per-request rates.
|
||||
1
changelog.d/fixes/docker-bun-web-playwright-chromium.md
Normal file
1
changelog.d/fixes/docker-bun-web-playwright-chromium.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
|
||||
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/maintenance/19716-cli-status-probe-cap.md
Normal file
1
changelog.d/maintenance/19716-cli-status-probe-cap.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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
changelog.d/maintenance/19741-xp-audit-created-index.md
Normal file
1
changelog.d/maintenance/19741-xp-audit-created-index.md
Normal file
@@ -0,0 +1 @@
|
||||
- **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))
|
||||
@@ -0,0 +1 @@
|
||||
- **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))
|
||||
@@ -157,13 +157,14 @@
|
||||
"dedicatedGate": true
|
||||
},
|
||||
"codeqlAlerts": {
|
||||
"value": 103,
|
||||
"value": 6,
|
||||
"direction": "down",
|
||||
"dedicatedGate": true,
|
||||
"_rebaseline_2026_08_06_base_grew": "Base branch file-size drift: translator-openai-to-gemini.test.ts grew 1619->1622 (test assertions for Gemini translator compatibility). CodeQL alert (js/insufficient-password-hash in raycast.ts) is pre-existing base-red; incremented baseline to match.",
|
||||
"_rebaseline_2026_08_10_9940_fingerprint": "CodeQL base-red (green-prs sweep, issue #9985): 2nd js/insufficient-password-hash alert at src/shared/middleware/chatBodyAdmission.ts:265,269 introduced by #9940 (per-connection virtual admission lanes). Both are API-key/bearer FINGERPRINTS (createHash('sha256') truncated to 16-hex admission-lane key), not password VERIFICATION — false-positive class for this rule. Reproduces on release/v3.8.50 tip. Owner-authorized rebaseline 1->2; revisit at v3.9.0.",
|
||||
"_rebaseline_2026_08_11_merge_storm_drift": "2 -> 9. Drift from the 2026-08-11 authorized merge storm (99 PRs into release/v3.8.50): js/insufficient-password-hash in open-sse/executors/chatgpt-web-codex/storageState.ts x3 + conol-web.ts (PRs #8949/#8974 — Chromium browser-profile credential storage SKUs that CodeQL flags under the password-hash rule; same fingerprint/credential-cache false-positive class already rebaselined in #9940/2026-08-06), js/stack-trace-exposure (chatgpt-web-codex.ts, #8949 debug logging), js/double-escaping (environment.ts, #8949), js/insecure-randomness (tinycms.ts, #9435). None introduced by this base-fix PR. Owner-authorized rebaseline (2026-08-11); revisit hardening at v3.9.0.",
|
||||
"_rebaseline_2026_11_20_codeql_2_27_5": "6 -> 103. Tool upgrade, not code: the default setup moved CodeQL 2.27.4 -> 2.27.5 on 2026-11-20 and the release/v3.8.55 JS analysis went 236 -> 339 results with the same 87 rules (760357c4 only touched a test file). 101 alerts were created together at 14:07:12Z (path-injection 34, polynomial-redos 30, request-forgery 22, unvalidated-dynamic-method-call 6, regex-injection 6, resource-exhaustion 3). Owner-authorized temporary ceiling (2026-11-20) to unblock merges while the security wave triages them (dismiss false positives with justification, fix real defects); a follow-up PR lowers the value to the measured count."
|
||||
"_rebaseline_2026_11_20_codeql_2_27_5": "6 -> 103. Tool upgrade, not code: the default setup moved CodeQL 2.27.4 -> 2.27.5 on 2026-11-20 and the release/v3.8.55 JS analysis went 236 -> 339 results with the same 87 rules (760357c4 only touched a test file). 101 alerts were created together at 14:07:12Z (path-injection 34, polynomial-redos 30, request-forgery 22, unvalidated-dynamic-method-call 6, regex-injection 6, resource-exhaustion 3). Owner-authorized temporary ceiling (2026-11-20) to unblock merges while the security wave triages them (dismiss false positives with justification, fix real defects); a follow-up PR lowers the value to the measured count.",
|
||||
"_rebaseline_2026_11_21_restore_after_2_27_5": "103 -> 6. Ends the temporary ceiling of 2026-11-20: the security wave dismissed the false positives with justification and fixed the real defects (#20770, #20775, #20776, #20781, #20819, #20820, #20824, #20839; #20825 and #20867 close the last two). 6 is the ceiling in force before the CodeQL 2.27.5 upgrade (velocity phase headroom included); tightening to the measured count is left to the release --update."
|
||||
},
|
||||
"secretFindings": {
|
||||
"_note": "Zeroed 2026-07-13 (WS6/D3): the 3 frozen generic-api-key FPs are allowlisted with justification in .gitleaks.toml — any NEW finding regresses the ratchet.",
|
||||
|
||||
@@ -45,7 +45,7 @@ omniroute-cmd-myplugin/
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
"engines": { "omniroute": ">=3.8.0" },
|
||||
"engines": { "omniroute": ">=4.0.0" },
|
||||
"keywords": ["omniroute-plugin", "omniroute-cmd"]
|
||||
}
|
||||
```
|
||||
@@ -57,7 +57,7 @@ export const meta = {
|
||||
name: "myplugin",
|
||||
version: "0.1.0",
|
||||
description: "My plugin for OmniRoute",
|
||||
omnirouteApi: ">=3.8.0",
|
||||
omnirouteApi: ">=4.0.0",
|
||||
};
|
||||
|
||||
export function register(program, ctx) {
|
||||
@@ -94,11 +94,8 @@ The `ctx` object passed to `register(program, ctx)`:
|
||||
|
||||
Plugins are discovered from:
|
||||
|
||||
1. `~/.omniroute/plugins/node_modules/<name>/` — where `omniroute plugin install` puts packages (an npm `--prefix`, not `npm -g`)
|
||||
2. `~/.omniroute/plugins/<name>/` — hand-copied plugin directories
|
||||
3. `OMNIROUTE_PLUGIN_PATH` env var — custom directory
|
||||
|
||||
Symlinked directories (what npm creates for `plugin install ./dir`) are followed.
|
||||
1. `~/.omniroute/plugins/<name>/` — user-local installs
|
||||
2. `OMNIROUTE_PLUGIN_PATH` env var — custom directory
|
||||
|
||||
Both are **CLI-only**. The server-side plugin runtime (the marketplace/`plugin.json`
|
||||
plugins that run inside the proxy) has its own scanner with its own override,
|
||||
|
||||
@@ -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 fast-forward, never squash").
|
||||
already is (see AGENTS.md → "Sync-back landings are merge commits, 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` | `deepseek-ocr-maas` | `vertex-deepseek-ocr/deepseek-ocr-maas` | Synchronous, via Vertex AI's `openapi/chat/completions` partner endpoint — see below for auth/URL. |
|
||||
| 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. |
|
||||
|
||||
All three providers respond in the same Mistral-shaped body:
|
||||
|
||||
|
||||
@@ -647,6 +647,7 @@ 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`. |
|
||||
@@ -1428,6 +1429,10 @@ 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,7 +528,8 @@ export const EMBEDDING_PROVIDERS: Record<string, EmbeddingProvider> = {
|
||||
id: "ollama-local",
|
||||
baseUrl: "http://localhost:11434/v1/embeddings",
|
||||
authType: "none",
|
||||
authHeader: "none",
|
||||
// Key optional (reverse proxy in front of Ollama): sent as bearer only when configured.
|
||||
authHeader: "bearer",
|
||||
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 (deepseek-ai/deepseek-ocr-maas), served through Vertex's generic
|
||||
* Vertex AI DeepSeek OCR (self-deployed Model Garden endpoint), 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 prefixed with "deepseek-ai/", the OCR
|
||||
* - request: OpenAI chat-completions shape, model id sent as supplied, 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,6 +129,14 @@ 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 {
|
||||
@@ -137,7 +145,7 @@ export const VERTEX_DEEPSEEK_TRANSFORMATION: OcrTransformation = {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({
|
||||
model: `deepseek-ai/${modelId}`,
|
||||
model: modelId,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
@@ -154,7 +162,7 @@ export const VERTEX_DEEPSEEK_TRANSFORMATION: OcrTransformation = {
|
||||
choices?: Array<{ message?: { content?: unknown } }>;
|
||||
usage?: Record<string, unknown>;
|
||||
};
|
||||
const model = r.model ?? "deepseek-ocr-maas";
|
||||
const model = r.model ?? "vertex-deepseek-ocr";
|
||||
const content = r.choices?.[0]?.message?.content;
|
||||
|
||||
if (typeof content === "string") {
|
||||
@@ -204,7 +212,7 @@ export const OCR_PROVIDERS: Record<string, OcrProvider> = {
|
||||
baseUrl: "",
|
||||
authType: "apikey",
|
||||
authHeader: "bearer",
|
||||
models: [{ id: "deepseek-ocr-maas", name: "DeepSeek OCR (Vertex AI MaaS)" }],
|
||||
models: [],
|
||||
transformation: VERTEX_DEEPSEEK_TRANSFORMATION,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -44,6 +44,7 @@ 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,6 +106,7 @@ 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.
|
||||
@@ -116,6 +117,7 @@ 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
|
||||
@@ -127,6 +129,7 @@ export const opencode_zenProvider: RegistryEntry = {
|
||||
targetFormat: "openai-responses",
|
||||
contextLength: 1048576,
|
||||
maxOutputTokens: 131072,
|
||||
supportsVision: true,
|
||||
},
|
||||
{
|
||||
id: "muse-spark-1.3-contributor-free",
|
||||
@@ -135,6 +138,7 @@ export const opencode_zenProvider: RegistryEntry = {
|
||||
targetFormat: "openai-responses",
|
||||
contextLength: 1048576,
|
||||
maxOutputTokens: 131072,
|
||||
supportsVision: true,
|
||||
},
|
||||
|
||||
// ── DeepSeek ────────────────────────────────────────────────
|
||||
|
||||
@@ -90,15 +90,17 @@ 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 (
|
||||
"cache_read_input_tokens" in usageRecord ||
|
||||
"cached_tokens" in usageRecord ||
|
||||
"cache_creation_input_tokens" in usageRecord ||
|
||||
"cache_write_tokens" in usageRecord ||
|
||||
usageRecord.cache_read_input_tokens !== undefined ||
|
||||
usageRecord.cached_tokens !== undefined ||
|
||||
usageRecord.cache_creation_input_tokens !== undefined ||
|
||||
usageRecord.cache_write_tokens !== undefined ||
|
||||
(!!promptTokenDetails &&
|
||||
("cached_tokens" in promptTokenDetails ||
|
||||
"cache_creation_tokens" in promptTokenDetails ||
|
||||
"cache_write_tokens" in promptTokenDetails))
|
||||
(promptTokenDetails.cached_tokens !== undefined ||
|
||||
promptTokenDetails.cache_creation_tokens !== undefined ||
|
||||
promptTokenDetails.cache_write_tokens !== undefined))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,8 @@ export function defaultClaudeToolType(tools: unknown): unknown {
|
||||
if (!Array.isArray(tools)) return tools;
|
||||
return tools.map((tool) => {
|
||||
if (tool && typeof tool === "object" && !Array.isArray(tool)) {
|
||||
return (tool as UnknownRecord).type ? tool : { type: "custom", ...(tool as UnknownRecord) };
|
||||
// `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;
|
||||
});
|
||||
|
||||
@@ -43,8 +43,13 @@ export async function getCombosCached(): Promise<unknown[]> {
|
||||
}
|
||||
_combosCacheTs = now;
|
||||
_combosCacheVersionSnapshot = version;
|
||||
_combosPromise = getCombos();
|
||||
return _combosPromise;
|
||||
// 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;
|
||||
}
|
||||
|
||||
export function clearCombosCache() {
|
||||
@@ -64,7 +69,18 @@ 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;
|
||||
const cfg = await getUpstreamProxyConfig(providerId).catch(() => null);
|
||||
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 result: UpstreamProxyConfigCacheEntry = cfg
|
||||
? {
|
||||
mode: cfg.mode,
|
||||
@@ -80,6 +96,6 @@ export async function getUpstreamProxyConfigCached(providerId: string) {
|
||||
fallbackBackend: "cliproxyapi" as const,
|
||||
ts: Date.now(),
|
||||
};
|
||||
_proxyConfigCache.set(providerId, result);
|
||||
if (!failed) _proxyConfigCache.set(providerId, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -33,10 +33,20 @@ 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(requestBody?.tools) ? estimateTokens(requestBody.tools) : 0,
|
||||
system: estimateTokens(requestBody?.system),
|
||||
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
|
||||
),
|
||||
instructions: estimateTokens(requestBody?.instructions),
|
||||
};
|
||||
return { ...breakdown, total: Object.values(breakdown).reduce((sum, value) => sum + value, 0) };
|
||||
|
||||
@@ -791,24 +791,6 @@ 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 = [
|
||||
@@ -1040,6 +1022,26 @@ 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,6 +17,27 @@ 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;
|
||||
@@ -40,15 +61,7 @@ export async function runPluginOnRequestHook(args: {
|
||||
const pluginResult = await runOnRequest(pluginCtx);
|
||||
if (pluginResult?.blocked) {
|
||||
args.log?.info?.("PLUGIN", `Request blocked by plugin`);
|
||||
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 };
|
||||
return { blocked: true, response: blockResponse(pluginResult.response) };
|
||||
}
|
||||
if (pluginResult?.metadata) {
|
||||
Object.assign(pluginCtx.metadata, pluginResult.metadata);
|
||||
|
||||
@@ -4,6 +4,10 @@ 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.
|
||||
@@ -14,6 +18,8 @@ import { isProviderSafetyRefusalBody } from "../../utils/providerSafety.ts";
|
||||
* 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.
|
||||
*/
|
||||
@@ -27,6 +33,14 @@ 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,7 +12,11 @@ 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, type ToolDisclosureConfig } from "../../utils/toolDisclosure.ts";
|
||||
import {
|
||||
applyToolDisclosure,
|
||||
collectHistoryToolNames,
|
||||
type ToolDisclosureConfig,
|
||||
} from "../../utils/toolDisclosure.ts";
|
||||
import {
|
||||
isOpenCodeLane,
|
||||
providerSupportsCaching,
|
||||
@@ -169,10 +173,13 @@ function isFallbackTool(tool: unknown): boolean {
|
||||
return FALLBACK_TOOL_NAMES.has(unprefixed);
|
||||
}
|
||||
|
||||
function capToolList(tools: unknown[], limit: number): unknown[] {
|
||||
let pinnedRoom = Math.min(limit, tools.filter(isFallbackTool).length);
|
||||
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);
|
||||
let room = limit - pinnedRoom;
|
||||
return tools.filter((tool) => (isFallbackTool(tool) ? pinnedRoom-- > 0 : room-- > 0));
|
||||
return tools.filter((tool) => (pinned(tool) ? pinnedRoom-- > 0 : room-- > 0));
|
||||
}
|
||||
|
||||
const MAX_LOGGED_DROPPED_TOOLS = 15;
|
||||
@@ -194,7 +201,9 @@ function applyToolCap(
|
||||
provider: string | null | undefined,
|
||||
log?: LoggerLike
|
||||
): Body {
|
||||
const truncatedTools = capToolList(tools, limit);
|
||||
const keepNames = new Set<string>();
|
||||
collectHistoryToolNames(bodyToSend, keepNames);
|
||||
const truncatedTools = capToolList(tools, limit, keepNames);
|
||||
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(", ");
|
||||
|
||||
@@ -1006,8 +1006,8 @@ async function handleKieImageGeneration({
|
||||
}: KieImageOptions) {
|
||||
const startTime = Date.now();
|
||||
const token = credentials?.apiKey || credentials?.accessToken;
|
||||
const timeoutMs = normalizePositiveNumber(body.timeout_ms, 300000);
|
||||
const pollIntervalMs = normalizePositiveNumber(body.poll_interval_ms, 2500);
|
||||
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
|
||||
const pollIntervalMs = clampPollIntervalMs(body.poll_interval_ms, 2500);
|
||||
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
|
||||
const size = typeof body.size === "string" ? body.size : undefined;
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ import { resolveUcCredential } from "../../../executors/uc/credentials.ts";
|
||||
import { mintUcSessionToken } from "../../../executors/uc/clerkAuth.ts";
|
||||
import { UC_ORIGIN } from "../../../executors/uc/constants.ts";
|
||||
import { sanitizeErrorMessage } from "../../../utils/error.ts";
|
||||
import { clampPollIntervalMs, clampPollTimeoutMs } from "../../../utils/pollBounds.ts";
|
||||
import { saveImageErrorResult, saveImageSuccessResult } from "../../imageGeneration.ts";
|
||||
|
||||
/** Persona web image-gen endpoint (immediate response + result-URL polling). */
|
||||
@@ -308,11 +309,11 @@ async function handleUcPersonaImage(
|
||||
});
|
||||
}
|
||||
|
||||
const timeoutMs = normalizePositiveNumber(
|
||||
const timeoutMs = clampPollTimeoutMs(
|
||||
body.timeout_ms,
|
||||
normalizePositiveNumber(process.env.UC_IMAGE_POLL_TIMEOUT_MS, UC_POLL_TIMEOUT_MS_DEFAULT)
|
||||
);
|
||||
const pollIntervalMs = normalizePositiveNumber(
|
||||
const pollIntervalMs = clampPollIntervalMs(
|
||||
body.poll_interval_ms,
|
||||
normalizePositiveNumber(process.env.UC_IMAGE_POLL_INTERVAL_MS, UC_POLL_INTERVAL_MS_DEFAULT)
|
||||
);
|
||||
|
||||
@@ -365,11 +365,6 @@ export async function runRenderhourJob({
|
||||
return pollRenderhourJob({ baseUrl, token, job, timeoutMs, pollIntervalMs, log, signal });
|
||||
}
|
||||
|
||||
/** A positive number from the request (e.g. `timeout_ms`), else the fallback. */
|
||||
export function renderhourNumber(value: unknown, fallback: number): number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
|
||||
/** Turns a thrown upload / network error into the handlers' failure shape. */
|
||||
export function renderhourFailure(err: unknown): { status: number; error: string } {
|
||||
if (err instanceof RenderhourRequestError) {
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
import { getMusicProvider, parseMusicModel } from "../config/musicRegistry.ts";
|
||||
import { kieExecutor } from "../executors/kie.ts";
|
||||
import { clampPollIntervalMs, clampPollTimeoutMs } from "../utils/pollBounds.ts";
|
||||
import { vertexGenerateMusic } from "../executors/vertexMedia.ts";
|
||||
import {
|
||||
submitComfyWorkflow,
|
||||
@@ -361,8 +362,8 @@ async function handleKieMusicGeneration({
|
||||
} | null;
|
||||
}) {
|
||||
const startTime = Date.now();
|
||||
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
|
||||
const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
|
||||
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
|
||||
const pollIntervalMs = clampPollIntervalMs(body.poll_interval_ms, 2500);
|
||||
const token = credentials?.apiKey || credentials?.accessToken;
|
||||
const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
|
||||
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
getOcrTransformation,
|
||||
parseOcrModel,
|
||||
OCR_PROVIDERS,
|
||||
VERTEX_DEEPSEEK_RETIRED_MODEL_ID,
|
||||
type OcrResponseShape,
|
||||
} from "../config/ocrRegistry.ts";
|
||||
import { errorResponse, sanitizeErrorMessage } from "../utils/error.ts";
|
||||
@@ -182,6 +183,16 @@ 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
|
||||
|
||||
@@ -9,10 +9,10 @@ import { errorResponse } from "../utils/error.ts";
|
||||
import {
|
||||
renderhourBaseUrl,
|
||||
renderhourFailure,
|
||||
renderhourNumber,
|
||||
renderhourToken,
|
||||
runRenderhourJob,
|
||||
} from "./mediaGeneration/renderhour.ts";
|
||||
import { clampPollIntervalMs, clampPollTimeoutMs } from "../utils/pollBounds.ts";
|
||||
|
||||
export async function handleRenderhourSpeech({
|
||||
providerConfig,
|
||||
@@ -37,8 +37,8 @@ export async function handleRenderhourSpeech({
|
||||
baseUrl: renderhourBaseUrl(credentials, providerConfig.baseUrl),
|
||||
token,
|
||||
request: { model: modelId, text },
|
||||
timeoutMs: renderhourNumber(body.timeout_ms, 180_000),
|
||||
pollIntervalMs: renderhourNumber(body.poll_interval_ms, 2000),
|
||||
timeoutMs: clampPollTimeoutMs(body.timeout_ms, 180_000),
|
||||
pollIntervalMs: clampPollIntervalMs(body.poll_interval_ms, 2000),
|
||||
});
|
||||
if (result.ok === false) return errorResponse(result.status, result.error);
|
||||
return audioStreamResponse(await fetch(result.job.outputs[0].url));
|
||||
|
||||
@@ -31,7 +31,10 @@ 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 { geminiExtraUsageCounts } from "../translator/response/geminiUsageMetadata.ts";
|
||||
import {
|
||||
geminiCandidatesTokenCount,
|
||||
geminiExtraUsageCounts,
|
||||
} from "../translator/response/geminiUsageMetadata.ts";
|
||||
import {
|
||||
extractThinkingFromContent,
|
||||
shouldParseTextualReasoningTags,
|
||||
@@ -1049,8 +1052,10 @@ function convertOpenAINonStreamingToGeminiFamily(openaiResponse: JsonRecord): Js
|
||||
OPENAI_TO_GEMINI_FINISH_REASON[toString(choice.finish_reason, "stop")] ?? "STOP";
|
||||
|
||||
const usageSrc = toRecord(openaiResponse.usage);
|
||||
const promptTokens = toFiniteNumber(usageSrc.prompt_tokens, 0);
|
||||
const completionTokens = toFiniteNumber(usageSrc.completion_tokens, 0);
|
||||
// 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 geminiResponse: JsonRecord = {
|
||||
response: {
|
||||
@@ -1063,9 +1068,12 @@ function convertOpenAINonStreamingToGeminiFamily(openaiResponse: JsonRecord): Js
|
||||
],
|
||||
usageMetadata: {
|
||||
promptTokenCount: promptTokens,
|
||||
candidatesTokenCount: completionTokens,
|
||||
candidatesTokenCount: geminiCandidatesTokenCount(
|
||||
completionTokens,
|
||||
extraUsage.thoughtsTokenCount
|
||||
),
|
||||
totalTokenCount: toFiniteNumber(usageSrc.total_tokens, promptTokens + completionTokens),
|
||||
...geminiExtraUsageCounts(usageSrc),
|
||||
...extraUsage,
|
||||
},
|
||||
modelVersion: toString(openaiResponse.model, "unknown"),
|
||||
responseId: toString(openaiResponse.id, `resp_${Date.now()}`),
|
||||
|
||||
@@ -30,11 +30,11 @@ import {
|
||||
} from "./videoGeneration/job.ts";
|
||||
import { abortedVideoResult, POLL_ABORTED, pollJsonAfter } from "./videoGeneration/abort.ts";
|
||||
import { sleep } from "../utils/sleep.ts";
|
||||
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../utils/pollBounds.ts";
|
||||
import {
|
||||
downloadResultVideo,
|
||||
extractRunwayFailureMessage,
|
||||
normalizeRunwayVideoResult,
|
||||
resolvePositiveInteger,
|
||||
resultVideoErrorText,
|
||||
resolveRunwayDuration,
|
||||
resolveRunwayPromptImage,
|
||||
@@ -135,12 +135,11 @@ function resolveVideoJobPollingOverrides(body: Record<string, unknown>): {
|
||||
pollIntervalMs?: number;
|
||||
} {
|
||||
const maxPolls = Number(body.max_polls);
|
||||
const pollIntervalMs = Number(body.poll_interval_ms);
|
||||
// 0 marks "not sent": the preset's own interval (2-5 s) then applies.
|
||||
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, 0);
|
||||
return {
|
||||
...(Number.isFinite(maxPolls) && maxPolls > 0 ? { maxPolls: Math.floor(maxPolls) } : {}),
|
||||
...(Number.isFinite(pollIntervalMs) && pollIntervalMs > 0
|
||||
? { pollIntervalMs: Math.floor(pollIntervalMs) }
|
||||
: {}),
|
||||
...(pollIntervalMs > 0 ? { pollIntervalMs } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -867,8 +866,8 @@ async function handleKieVideoGeneration({
|
||||
} | null;
|
||||
}) {
|
||||
const startTime = Date.now();
|
||||
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
|
||||
const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
|
||||
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
|
||||
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, 2500);
|
||||
const token = credentials?.apiKey || credentials?.accessToken;
|
||||
const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
|
||||
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
|
||||
@@ -977,8 +976,8 @@ async function handleRunwayVideoGeneration({
|
||||
|
||||
const ratio = resolveRunwayRatio(body);
|
||||
const duration = resolveRunwayDuration(body);
|
||||
const timeoutMs = resolvePositiveInteger(body.timeout_ms, 300000);
|
||||
const pollIntervalMs = resolvePositiveInteger(body.poll_interval_ms, 5000);
|
||||
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
|
||||
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, 5000);
|
||||
const submitUrl = buildRunwayApiUrl(
|
||||
useImageToVideo ? "/image_to_video" : "/text_to_video",
|
||||
providerConfig.baseUrl
|
||||
|
||||
@@ -3,6 +3,7 @@ import { saveCallLog } from "@/lib/usageDb";
|
||||
import { resolveAlibabaProviderMediaBaseUrl } from "@/shared/constants/alibabaProviderRegions";
|
||||
import { sanitizeErrorMessage } from "../../utils/error.ts";
|
||||
import { sleep } from "../../utils/sleep.ts";
|
||||
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../utils/pollBounds.ts";
|
||||
import { abortedVideoResult } from "./abort.ts";
|
||||
|
||||
// Shared with the DashScope TTS executor so the engine keeps a single import of this app
|
||||
@@ -63,8 +64,8 @@ export async function handleDashscopeVideoGeneration({
|
||||
signal?: AbortSignal | null;
|
||||
}) {
|
||||
const startTime = Date.now();
|
||||
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
|
||||
const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
|
||||
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
|
||||
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, 2500);
|
||||
const token = credentials?.apiKey || credentials?.accessToken;
|
||||
const isAlibabaManagedMediaProvider =
|
||||
provider === "alibaba" ||
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from "@/shared/utils/fetchTimeout";
|
||||
import { sanitizeErrorMessage } from "../../utils/error.ts";
|
||||
import { sleep } from "../../utils/sleep.ts";
|
||||
import { MAX_CALLER_POLL_TIMEOUT_MS } from "../../utils/pollBounds.ts";
|
||||
import {
|
||||
MAX_CONSECUTIVE_POLL_RETRIES,
|
||||
computePollRetryDelayMs,
|
||||
@@ -511,8 +512,18 @@ async function runVideoJobGeneration({
|
||||
}
|
||||
|
||||
// Poll loop.
|
||||
const maxPolls = maxPollsOverride ?? preset.maxPolls;
|
||||
const pollInterval = pollIntervalOverride ?? preset.pollIntervalMs;
|
||||
// A preset has no deadline: its window is maxPolls x interval. Caller overrides of either
|
||||
// may not stretch it past the larger of the preset's own window and the caller ceiling
|
||||
// (CodeQL #1389); with no override this leaves the preset's maxPolls unchanged.
|
||||
const windowCeilingMs = Math.max(
|
||||
preset.maxPolls * preset.pollIntervalMs,
|
||||
MAX_CALLER_POLL_TIMEOUT_MS
|
||||
);
|
||||
const maxPolls = Math.min(
|
||||
maxPollsOverride ?? preset.maxPolls,
|
||||
Math.max(1, Math.floor(windowCeilingMs / pollInterval))
|
||||
);
|
||||
|
||||
let consecutiveRetries = 0;
|
||||
let nextDelay = pollInterval;
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
import { saveCallLog } from "@/lib/usageDb";
|
||||
import { sanitizeErrorMessage } from "../../utils/error.ts";
|
||||
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../utils/pollBounds.ts";
|
||||
import { isJsonObject } from "../../utils/kieTask.ts";
|
||||
import {
|
||||
MAX_CONSECUTIVE_POLL_RETRIES,
|
||||
@@ -196,9 +197,8 @@ export async function handleMinimaxVideoGeneration({
|
||||
log?: MinimaxLog;
|
||||
}): Promise<VideoResult> {
|
||||
const startTime = Date.now();
|
||||
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : DEFAULT_TIMEOUT_MS;
|
||||
const pollIntervalMs =
|
||||
Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : DEFAULT_POLL_INTERVAL_MS;
|
||||
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, DEFAULT_TIMEOUT_MS);
|
||||
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, DEFAULT_POLL_INTERVAL_MS);
|
||||
const token = credentials?.apiKey || credentials?.accessToken;
|
||||
|
||||
const request = buildMinimaxVideoRequestBody(
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
import { sanitizeErrorMessage } from "../../utils/error.ts";
|
||||
import { sleep } from "../../utils/sleep.ts";
|
||||
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../utils/pollBounds.ts";
|
||||
import { abortedVideoResult } from "./abort.ts";
|
||||
import {
|
||||
buildNovitaPollUrl,
|
||||
@@ -72,9 +73,8 @@ function resolveNovitaTiming(body: NovitaHandlerArgs["body"]): {
|
||||
timeoutMs: number;
|
||||
pollIntervalMs: number;
|
||||
} {
|
||||
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : DEFAULT_TIMEOUT_MS;
|
||||
const pollIntervalMs =
|
||||
Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : DEFAULT_POLL_INTERVAL_MS;
|
||||
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, DEFAULT_TIMEOUT_MS);
|
||||
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, DEFAULT_POLL_INTERVAL_MS);
|
||||
return { timeoutMs, pollIntervalMs };
|
||||
}
|
||||
|
||||
|
||||
@@ -57,6 +57,7 @@ import { resolveUcCredential } from "../../../executors/uc/credentials.ts";
|
||||
import { mintUcSessionToken } from "../../../executors/uc/clerkAuth.ts";
|
||||
import { UC_ORIGIN } from "../../../executors/uc/constants.ts";
|
||||
import { sanitizeErrorMessage } from "../../../utils/error.ts";
|
||||
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../../utils/pollBounds.ts";
|
||||
|
||||
/** Persona signed-upload-URL endpoint (for the image-to-video input image). */
|
||||
export const UC_PERSONA_SIGNED_URL = "https://internal-6.pubyar.com/generate-signed-url";
|
||||
@@ -559,8 +560,8 @@ async function handleUcPersonaVideo(ctx: PersonaContext): Promise<UcVideoResult>
|
||||
Number.isFinite(timeoutSeconds) && timeoutSeconds > 0
|
||||
? timeoutSeconds * 1000
|
||||
: normalizePositiveNumber(process.env.UC_VIDEO_POLL_TIMEOUT_MS, UC_POLL_TIMEOUT_MS_DEFAULT);
|
||||
const timeoutMs = normalizePositiveNumber(body.timeout_ms, defaultTimeoutMs);
|
||||
const pollIntervalMs = normalizePositiveNumber(
|
||||
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, defaultTimeoutMs);
|
||||
const pollIntervalMs = clampVideoPollIntervalMs(
|
||||
body.poll_interval_ms,
|
||||
normalizePositiveNumber(process.env.UC_VIDEO_POLL_INTERVAL_MS, UC_POLL_INTERVAL_MS_DEFAULT)
|
||||
);
|
||||
@@ -702,8 +703,8 @@ async function handleUcDirectVideo(ctx: DirectContext): Promise<UcVideoResult> {
|
||||
|
||||
// Poll status_url until complete or timeout.
|
||||
const statusUrl = extracted.statusUrl;
|
||||
const timeoutMs = normalizePositiveNumber(body.timeout_ms, UC_POLL_TIMEOUT_MS_DEFAULT);
|
||||
const pollIntervalMs = normalizePositiveNumber(
|
||||
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, UC_POLL_TIMEOUT_MS_DEFAULT);
|
||||
const pollIntervalMs = clampVideoPollIntervalMs(
|
||||
body.poll_interval_ms,
|
||||
UC_POLL_INTERVAL_MS_DEFAULT
|
||||
);
|
||||
|
||||
@@ -15,13 +15,13 @@ import {
|
||||
renderhourBaseUrl,
|
||||
renderhourConfig,
|
||||
renderhourFailure,
|
||||
renderhourNumber,
|
||||
renderhourSeconds,
|
||||
renderhourToken,
|
||||
runRenderhourJob,
|
||||
uploadRenderhourInputs,
|
||||
type RenderhourUploadTarget,
|
||||
} from "../mediaGeneration/renderhour.ts";
|
||||
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../utils/pollBounds.ts";
|
||||
|
||||
type Body = Record<string, unknown>;
|
||||
|
||||
@@ -112,8 +112,8 @@ async function runVideoJob({
|
||||
baseUrl,
|
||||
token,
|
||||
request,
|
||||
timeoutMs: renderhourNumber(body.timeout_ms, 900_000),
|
||||
pollIntervalMs: renderhourNumber(body.poll_interval_ms, 5000),
|
||||
timeoutMs: clampPollTimeoutMs(body.timeout_ms, 900_000),
|
||||
pollIntervalMs: clampVideoPollIntervalMs(body.poll_interval_ms, 5000),
|
||||
log,
|
||||
signal,
|
||||
});
|
||||
|
||||
@@ -86,12 +86,6 @@ function clampRunwayDuration(value) {
|
||||
return Math.min(10, Math.max(2, duration));
|
||||
}
|
||||
|
||||
export function resolvePositiveInteger(value, fallback) {
|
||||
const numeric = Number(value);
|
||||
if (!Number.isFinite(numeric) || numeric <= 0) return fallback;
|
||||
return Math.floor(numeric);
|
||||
}
|
||||
|
||||
function extractRunwayOutputUrls(task) {
|
||||
const rawOutput = Array.isArray(task?.output)
|
||||
? task.output
|
||||
|
||||
@@ -1474,6 +1474,8 @@ 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);
|
||||
@@ -2716,6 +2718,9 @@ 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,6 +13,8 @@ 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,7 +5,12 @@
|
||||
* context-optimized, context-relay, and fusion strategies
|
||||
*/
|
||||
|
||||
import { errorResponse, errorResponseWithComboDiagnostics } from "../utils/error.ts";
|
||||
import {
|
||||
errorResponse,
|
||||
errorResponseWithComboDiagnostics,
|
||||
sanitizeErrorMessage,
|
||||
} from "../utils/error.ts";
|
||||
import { logger } from "../utils/logger.ts";
|
||||
import { isProviderSafetyStopsEnabled } from "../utils/providerSafety.ts";
|
||||
import { createChaosHeaderBarrier } from "./combo/chaosHeaderBarrier.ts";
|
||||
import { runComboWithSafetyLatch } from "./combo/safetyStopLatch.ts";
|
||||
@@ -379,6 +384,8 @@ export function maybeWarnBootstrapDominant(hasStats: boolean): void {
|
||||
console.warn(formatBootstrapWarning());
|
||||
}
|
||||
|
||||
const scopeReadLog = logger("COMBO_AUTO");
|
||||
|
||||
export async function buildAutoCandidates(
|
||||
targets: ResolvedComboTarget[],
|
||||
comboName: string,
|
||||
@@ -423,8 +430,14 @@ export async function buildAutoCandidates(
|
||||
for (const connection of connections) connectionById.set(connection.id, connection);
|
||||
}
|
||||
targetsForExpansion = expandTargetsWithinConnectionScope(targets, grouped, connectionScope);
|
||||
} catch {
|
||||
targetsForExpansion = [];
|
||||
} 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)),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const uniqueProviders = Array.from(
|
||||
|
||||
@@ -686,11 +686,13 @@ 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,
|
||||
@@ -707,16 +709,20 @@ export async function executeTargetAttempt(
|
||||
!(deps.body as Record<string, unknown>)?.[SKIP_UNIVERSAL_HANDOFF_FLAG]
|
||||
) {
|
||||
const prevModel = getLastSessionModel(handoffSessionId, deps.combo.name);
|
||||
recordSessionModelUsage(
|
||||
handoffSessionId,
|
||||
deps.combo.name,
|
||||
modelStr,
|
||||
provider,
|
||||
target.connectionId ?? undefined
|
||||
);
|
||||
// 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
|
||||
);
|
||||
}
|
||||
// i === 0 only: a same-request fallback target (i > 0) never
|
||||
// needs a summary generated for it -- see the injection-site
|
||||
// comment above. recordSessionModelUsage above stays
|
||||
// comment above. The row recorded 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
|
||||
@@ -739,14 +745,6 @@ 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,
|
||||
|
||||
@@ -3,9 +3,12 @@
|
||||
*
|
||||
* `full`/absent → whole text (backward-compat). All modes are fail-safe:
|
||||
* incoherent params or an unsafe regex yield { error }, never throw. The grep
|
||||
* mode validates the pattern with `safe-regex` (no catastrophic backtracking)
|
||||
* before compiling, and bounds matches/pattern length.
|
||||
* mode validates the pattern with `safe-regex` (no nested quantifiers), allows at
|
||||
* most one unbounded quantifier, bounds matches/pattern length, and runs the scan
|
||||
* under a wall-clock budget (CodeQL #1349): a caller-supplied pattern can still be
|
||||
* super-linear (`.*x` is quadratic per line), so the budget is the hard bound.
|
||||
*/
|
||||
import vm from "node:vm";
|
||||
import safeRegex from "safe-regex";
|
||||
|
||||
export type CcrMode = "full" | "head" | "tail" | "lines" | "grep" | "stats";
|
||||
@@ -24,6 +27,8 @@ export type CcrQueryResult = { content: string } | { error: string };
|
||||
export const MAX_RANGE_LINES = 10_000;
|
||||
export const MAX_GREP_MATCHES = 1_000;
|
||||
export const MAX_PATTERN_LEN = 512;
|
||||
/** Wall-clock budget for one grep scan over a block (ms). */
|
||||
export const GREP_TIME_BUDGET_MS = 1_000;
|
||||
|
||||
const err = (m: string): CcrQueryResult => ({ error: m });
|
||||
const ok = (c: string): CcrQueryResult => ({ content: c });
|
||||
@@ -53,30 +58,104 @@ function sliceLines(lines: string[], start?: number, end?: number): CcrQueryResu
|
||||
return ok(lines.slice(start - 1, Math.min(end, lines.length)).join("\n"));
|
||||
}
|
||||
|
||||
function grepLines(lines: string[], pattern?: string, unique?: boolean): CcrQueryResult {
|
||||
/**
|
||||
* Number of unbounded quantifiers (`*`, `+`, `{n,}`) outside character classes and
|
||||
* escapes. Two or more in sequence make the backtracking polynomial in the line length
|
||||
* (`.*.*.*.*x` is O(n^4)), which `safe-regex`'s star-height check does not catch.
|
||||
*/
|
||||
export function countUnboundedQuantifiers(pattern: string): number {
|
||||
let count = 0;
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === "\\") {
|
||||
i += 2;
|
||||
} else if (c === "[") {
|
||||
i = classEnd(pattern, i);
|
||||
} else {
|
||||
if (c === "*" || c === "+" || (c === "{" && isOpenRange(pattern, i))) count++;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/** Index just past the character class that opens at `start` (escapes honoured). */
|
||||
function classEnd(pattern: string, start: number): number {
|
||||
let i = start + 1;
|
||||
while (i < pattern.length && pattern[i] !== "]") i += pattern[i] === "\\" ? 2 : 1;
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
/** True when an open range quantifier `{n,}` starts at `start`. */
|
||||
function isOpenRange(pattern: string, start: number): boolean {
|
||||
let j = start + 1;
|
||||
while (j < pattern.length && pattern[j] >= "0" && pattern[j] <= "9") j++;
|
||||
return j > start + 1 && pattern[j] === "," && pattern[j + 1] === "}";
|
||||
}
|
||||
|
||||
// The scan runs in a dedicated context only so `timeout` can stop a runaway regex.
|
||||
// No host object enters it: inputs are primitives, the result leaves as a JSON string.
|
||||
const GREP_SCRIPT = new vm.Script(`(() => {
|
||||
"use strict";
|
||||
let re;
|
||||
try { re = new RegExp(grepPattern); } catch { return JSON.stringify({ invalid: true }); }
|
||||
const matched = [];
|
||||
let truncated = false;
|
||||
for (const line of grepText.split("\\n")) {
|
||||
if (re.test(line)) {
|
||||
matched.push(line);
|
||||
if (matched.length >= grepMaxMatches) { truncated = true; break; }
|
||||
}
|
||||
}
|
||||
return JSON.stringify({ matched, truncated });
|
||||
})()`);
|
||||
let grepContext: vm.Context | null = null;
|
||||
|
||||
function runGrepScan(
|
||||
text: string,
|
||||
pattern: string
|
||||
): { matched: string[]; truncated: boolean } | "invalid" | "timeout" {
|
||||
grepContext ??= vm.createContext(Object.create(null), {
|
||||
codeGeneration: { strings: false, wasm: false },
|
||||
});
|
||||
grepContext.grepPattern = pattern;
|
||||
grepContext.grepText = text;
|
||||
grepContext.grepMaxMatches = MAX_GREP_MATCHES;
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = GREP_SCRIPT.runInContext(grepContext, { timeout: GREP_TIME_BUDGET_MS });
|
||||
} catch (e) {
|
||||
if ((e as { code?: string })?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") return "timeout";
|
||||
throw e;
|
||||
} finally {
|
||||
grepContext.grepText = "";
|
||||
grepContext.grepPattern = "";
|
||||
}
|
||||
const parsed = JSON.parse(String(raw)) as {
|
||||
invalid?: boolean;
|
||||
matched?: string[];
|
||||
truncated?: boolean;
|
||||
};
|
||||
if (parsed.invalid === true) return "invalid";
|
||||
return { matched: parsed.matched ?? [], truncated: parsed.truncated === true };
|
||||
}
|
||||
|
||||
function grepLines(text: string, pattern?: string, unique?: boolean): CcrQueryResult {
|
||||
if (!pattern) return err("grep requires a 'pattern'");
|
||||
if (pattern.length > MAX_PATTERN_LEN) return err(`pattern exceeds ${MAX_PATTERN_LEN} chars`);
|
||||
if (!safeRegex(pattern)) return err("pattern rejected: potentially catastrophic backtracking");
|
||||
let re: RegExp;
|
||||
try {
|
||||
re = new RegExp(pattern);
|
||||
} catch {
|
||||
return err("invalid regex pattern");
|
||||
if (countUnboundedQuantifiers(pattern) > 1) {
|
||||
return err("pattern rejected: at most one unbounded quantifier (*, +, {n,}) is allowed");
|
||||
}
|
||||
const matched: string[] = [];
|
||||
let truncated = false;
|
||||
for (const line of lines) {
|
||||
if (re.test(line)) {
|
||||
matched.push(line);
|
||||
if (matched.length >= MAX_GREP_MATCHES) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const scan = runGrepScan(text, pattern);
|
||||
if (scan === "invalid") return err("invalid regex pattern");
|
||||
if (scan === "timeout") {
|
||||
return err(`grep exceeded its ${GREP_TIME_BUDGET_MS} ms time budget; use a narrower pattern`);
|
||||
}
|
||||
const out = unique ? [...new Set(matched)] : matched;
|
||||
const out = unique ? [...new Set(scan.matched)] : scan.matched;
|
||||
const body = out.join("\n");
|
||||
return ok(truncated ? `${body}\n…[truncated at ${MAX_GREP_MATCHES} matches]` : body);
|
||||
return ok(scan.truncated ? `${body}\n…[truncated at ${MAX_GREP_MATCHES} matches]` : body);
|
||||
}
|
||||
|
||||
function blockStats(text: string, lines: string[]): CcrQueryResult {
|
||||
@@ -101,7 +180,7 @@ export function queryBlock(text: string, q: CcrQuery): CcrQueryResult {
|
||||
case "lines":
|
||||
return sliceLines(lines, q.start, q.end);
|
||||
case "grep":
|
||||
return grepLines(lines, q.pattern, q.unique);
|
||||
return grepLines(text, q.pattern, q.unique);
|
||||
case "stats":
|
||||
return blockStats(text, lines);
|
||||
default:
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
// 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";
|
||||
@@ -100,6 +101,17 @@ 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.
|
||||
*/
|
||||
@@ -255,7 +267,11 @@ export async function refreshWithRetry(
|
||||
|
||||
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
||||
if (attempt > 0) {
|
||||
const delay = attempt * 1000;
|
||||
const delay = jitteredRetryDelayMs(
|
||||
attempt * 1000,
|
||||
options?.connectionId || provider,
|
||||
attempt
|
||||
);
|
||||
log?.debug?.("TOKEN_REFRESH", `Retry ${attempt}/${maxRetries} after ${delay}ms`);
|
||||
await new Promise((r) => setTimeout(r, delay));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// 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>;
|
||||
@@ -38,8 +39,12 @@ 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 {
|
||||
return id.length > MAX_CALL_ID_LEN ? id.slice(0, MAX_CALL_ID_LEN) : id;
|
||||
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}`;
|
||||
}
|
||||
|
||||
export function toArray(value: unknown): unknown[] {
|
||||
|
||||
@@ -516,7 +516,8 @@ export function openaiToOpenAIResponsesRequest(
|
||||
type: "function",
|
||||
name,
|
||||
description: toString(fn.description),
|
||||
parameters: fn.parameters,
|
||||
// Responses requires `parameters`; Chat lets a zero-argument tool omit it.
|
||||
parameters: fn.parameters ?? { type: "object", properties: {} },
|
||||
// Omitted strict is non-strict on Chat but strict-normalized on Responses.
|
||||
strict: chatStrictForResponses(fn),
|
||||
...(credentialRecord._provider === "codex" && typeof fn.defer_loading === "boolean"
|
||||
|
||||
@@ -80,7 +80,15 @@ export function fitThinkingToMaxTokens(
|
||||
|
||||
// Cap too tight for any thinking — disable rather than send an invalid request.
|
||||
if (fittedBudget < MIN_CLAUDE_THINKING_BUDGET) {
|
||||
return { maxTokens: modelCap ?? Math.max(callerMaxTokens, 1), thinking: undefined };
|
||||
// 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,
|
||||
};
|
||||
}
|
||||
|
||||
const adjustedThinking: Record<string, unknown> = { ...thinking };
|
||||
|
||||
@@ -244,7 +244,8 @@ function toClovaToolModeMessage(message: unknown): JsonRecord {
|
||||
if (record.role === "assistant" && toolCalls.length > 0) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
// Keep the text the assistant wrote before the call; "" only when there is none.
|
||||
content: contentToString(record.content),
|
||||
toolCalls: toolCalls.map(toClovaToolCall),
|
||||
};
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user