Compare commits

..

133 Commits

Author SHA1 Message Date
diegosouzapw
72556c31cd chore(changelog): prefix the fragment with its PR number 2026-11-23 19:36:40 -03:00
diegosouzapw
cd3e1a0b87 fix(usage): aggregate tok/s as total tokens over total time and skip implausible samples 2026-11-23 19:09:12 -03:00
diegosouzapw
929be985f9 fix(sse): omit tok/s for sub-250ms windows and implausible rates 2026-11-23 18:53:58 -03:00
Diego Rodrigues de Sa e Souza
bdafbf9567 fix(ci): time limits for the Fast Quality Gates job and for each of its gates (#20939)
* fix(ci): time limits for the Fast Quality Gates job and for each of its gates

On 2026-11-20 (run 44821771451, an omni-queue candidate) check:cycles printed
its ratchet verdict and its node process never exited; the gates step sat for
118 minutes until the run was cancelled by hand. The job had no time limit, so a
stuck step holds a hosted runner until GitHub's 360-minute default.

- fast-gates: timeout-minutes 150, above the merge queue's base check (the
  unsharded unit suite in this job, 94 min measured) and below the queue's
  checksTimeoutMinutes (240).
- Quality gates step: each of its 8 npm run calls goes through run_gate, which
  runs the gate under `timeout --kill-after=30s 10m` (the process group is
  signalled, so the kill reaches node under npm and sh). A gate cut by the
  limit runs once more; a second timeout is a failed gate. Exit codes and the
  failed/EXTERNAL_STATE_GATES accounting are unchanged.
- tests: a new workflow test executes the step with a fake npm and shortened
  limits; check-boundary-ratchet's text pin follows the run_gate prefix.

* docs(changelog): fragment for the Fast Quality Gates time limits (#20939)
2026-11-23 18:33:51 -03:00
Diego Rodrigues de Sa e Souza
0c2877103c docs(ci): AGENTS.md says how a PR lands on a release branch and how a sync-back lands (#20866)
The sync-back section prescribed a direct push that the default branch has refused since
the ruleset Require PR on default branch: a sync-back lands through a pull request merged
with a merge commit, which scripts/release/sync-next-cycle.mjs opens since #20645.

New section Landing on a release branch: omni-queue. In shadow mode a manual merge waits
for the queue's verdict on the PR's final head (green checks prove a PR against the base
they ran on: #19132); in live mode the label is the landing.
2026-11-23 18:33:19 -03:00
Diego Rodrigues de Sa e Souza
a539017d31 fix(docker): use Playwright's Chromium in the Bun web image (#20956)
The -web-bun image installed Debian's chromium, chromium-common and
chromium-driver packages. Playwright's own chromium.launch() looks for
its managed build under PLAYWRIGHT_BROWSERS_PATH, which stayed 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 image had no Xvfb
either, so headed launches (#15300) could not start.

The Debian chromium packages also carried 723 of the image's 866 HIGH
scanner findings, none with a Debian fix; chromium-driver was never used.

runner-web now installs Chromium with `playwright install chromium
--with-deps` plus xvfb, as the Node runner-web does, and keeps
/usr/bin/chromium as a symlink to the same build for the ChatGPT Web,
Codex Web and Adobe Firefly lookups.

The release preflight smoke now replays the whole stage and launches
Chromium headless, headed under Xvfb and through /usr/bin/chromium.
Measured on the .113 build host: OS-package findings go from C1/H866
to C1/H153 (Trivy), level with the Node -web image (C1/H143).
2026-11-23 18:24:14 -03:00
Diego Rodrigues de Sa e Souza
760e0ec783 Merge pull request #20965 from cheaper-inference/fix/merge-train-j-20261121
chore(release): contributor train j of 5 PRs for v3.8.55 (2026-11-21)
2026-11-23 18:12:52 -03:00
diegosouzapw
3f8f2495bb Merge branch 'release/v3.8.55' into fix/merge-train-j-20261121 2026-11-23 16:38:46 -03:00
diegosouzapw
58638f2697 fix(test): match the user's root URL literally in the codex-settings test
CodeQL (js/incomplete-hostname-regexp) flagged the #19716 test: the user URL
went into new RegExp() unescaped, so its dots matched any character. Escape
the URL before building the pattern; the three assertions keep their meaning.
2026-11-23 16:37:46 -03:00
Diego Rodrigues de Sa e Souza
198c82e9e3 Merge pull request #20339 from serenity-X/pr/fix/or9r-w3-kiro-orphan-tool-results
fix(kiro): send a tool result that has no matching tool call as text
2026-11-23 16:33:31 -03:00
Diego Rodrigues de Sa e Souza
a4a5e239bd Merge pull request #19633 from serenity-X/pr/fix/or9r-bundle-hd-cli
fix(cli): restore removes stale WAL files, config generators keep existing settings
2026-11-23 16:33:21 -03:00
Diego Rodrigues de Sa e Souza
2d4c466e1a Merge pull request #19741 from serenity-X/pr/perf/or9r-b-xp-audit-created-index
perf(gamification): add a created_at-first covering index for the hourly XP audit range
2026-11-23 16:33:05 -03:00
Diego Rodrigues de Sa e Souza
713bf17cc7 Merge pull request #20963 from cheaper-inference/fix/merge-train-i-20261121
chore(release): contributor train i of 7 PRs for v3.8.55 (2026-11-21)
2026-11-23 16:32:44 -03:00
Diego Rodrigues de Sa e Souza
8a47c93a4b Merge pull request #20823 from cheaper-inference/fix/codeql-redos-model-ids
test(security): pin linear model id parsing (CodeQL #1325, #1324, #1296)
2026-11-23 16:30:25 -03:00
Diego Rodrigues de Sa e Souza
3d8e392092 Merge pull request #20825 from cheaper-inference/fix/codeql-redos-compression
fix(security): bound caller grep regex in CCR and pin compression regex bounds (CodeQL #1349, #1301, #1302)
2026-11-23 16:30:08 -03:00
Diego Rodrigues de Sa e Souza
fa906f7ec2 Merge pull request #20940 from cheaper-inference/chore/codeql-ceiling-restore-20261121
chore(quality): end the temporary codeqlAlerts ceiling (103 -> 6)
2026-11-23 16:29:50 -03:00
Diego Rodrigues de Sa e Souza
c7d3b9cc2f Merge pull request #20867 from cheaper-inference/fix/codeql-1389-remaining-poll-sites
fix(security): clamp caller polling values at the remaining media handlers (CodeQL #1389)
2026-11-23 16:29:43 -03:00
diegosouzapw
791ec7fa9d Merge branch 'release/v3.8.55' into pr/fix/or9r-w3-kiro-orphan-tool-results
# Conflicts:
#	open-sse/translator/request/openai-to-kiro.ts
2026-11-21 15:23:23 -03:00
diegosouzapw
a4d1449081 Merge branch 'release/v3.8.55' into pr/fix/or9r-bundle-hd-cli
# Conflicts:
#	bin/cli/commands/backup.mjs
2026-11-21 15:14:29 -03:00
diegosouzapw
ab44955bbd Merge branch 'release/v3.8.55' into pr/perf/or9r-b-xp-audit-created-index
# Conflicts:
#	src/lib/db/migrationRunner/constants.ts
#	tests/unit/db-migrationrunner-constants-split.test.ts
2026-11-21 15:06:54 -03:00
diegosouzapw
486d8d2798 Merge #20594 (head 658402ca) into contributor train j 2026-11-21 14:58:07 -03:00
diegosouzapw
aaa0bf2eeb Merge #20341 (head 5a021bf4) into contributor train j 2026-11-21 14:58:06 -03:00
diegosouzapw
fe1508f987 Merge #20197 (head a6a6694a) into contributor train j 2026-11-21 14:58:04 -03:00
diegosouzapw
6816b09b4b Merge #20101 (head ca5e0e68) into contributor train j 2026-11-21 14:58:01 -03:00
diegosouzapw
baf64267a0 Merge #19716 (head a91c7b8c) into contributor train j 2026-11-21 14:57:55 -03:00
diegosouzapw
ba68a6fdcf Merge #20587 (head 638e676c) into contributor train i 2026-11-21 14:29:36 -03:00
diegosouzapw
12a09c8831 Merge #20380 (head ea623362) into contributor train i 2026-11-21 14:29:30 -03:00
diegosouzapw
d531353743 Merge #20359 (head 91906d55) into contributor train i 2026-11-21 14:29:25 -03:00
diegosouzapw
1f945369df Merge #20229 (head 52f4e527) into contributor train i 2026-11-21 14:29:18 -03:00
diegosouzapw
b9d9732f16 Merge #20224 (head 73f02b9d) into contributor train i 2026-11-21 14:29:15 -03:00
diegosouzapw
4b61fc9381 Merge #20122 (head e9548cb6) into contributor train i 2026-11-21 14:29:11 -03:00
diegosouzapw
09b4053eea Merge #20548 (head eaef7362) into contributor train i 2026-11-21 14:29:07 -03:00
diegosouzapw
321ffbe2c2 chore(quality): end the temporary codeqlAlerts ceiling (103 -> 6)
The CodeQL 2.27.5 upgrade ceiling of 2026-11-20 is no longer needed: the security wave dismissed the false positives with justification and fixed the real defects. 6 is the ceiling in force before the upgrade; tightening to the measured count is left to the release --update.
2026-11-21 10:52:16 -03:00
diegosouzapw
38d38c2825 fix(security): longer video poll ceiling and a bounded job-preset polling window
Video jobs render for minutes and providers such as Agnes poll once a minute, so video handlers cap the caller interval at 2 minutes instead of 30 s (agnes-provider expected a 60 s interval). Job presets have no deadline, so caller max_polls or interval may no longer stretch maxPolls x interval past the larger of the preset's own window and the 10-minute caller ceiling (CodeQL #1389).
2026-11-21 08:11:47 -03:00
diegosouzapw
63db262cc6 chore(changelog): number the remaining media polling fragment for #20867 2026-11-21 02:57:10 -03:00
diegosouzapw
d6c64656eb fix(security): clamp caller polling values at the remaining media handlers (CodeQL #1389)
Kie image/video/music, Runway, DashScope, Novita, MiniMax video, the video
job presets, RenderHour video/speech and UC image/video now read
poll_interval_ms and timeout_ms through pollBounds.ts (30 s / 10 min, or the
built-in default when longer). Defaults are unchanged. renderhourNumber and
resolvePositiveInteger lost their last callers and are removed.
2026-11-21 02:49:51 -03:00
diegosouzapw
2a48a0a823 Merge remote-tracking branch 'origin/release/v3.8.55' into fix/codeql-redos-compression
# Conflicts:
#	open-sse/services/compression/engines/headroom/gcf/scalar.ts
#	open-sse/services/compression/engines/rtk/rawOutput.ts
2026-11-21 00:25:29 -03:00
diegosouzapw
6441b5b6f3 Merge remote-tracking branch 'origin/release/v3.8.55' into fix/codeql-redos-model-ids
# Conflicts:
#	open-sse/executors/context7-fetch.ts
#	src/shared/utils/modelDisplayName.ts
#	src/sse/services/githubResponsesFallback.ts
2026-11-21 00:23:19 -03:00
diegosouzapw
c13cee2357 chore(changelog): prefix the fragment with PR #20825 2026-11-20 18:33:25 -03:00
diegosouzapw
eca9826d29 fix(security): bound regex work in compression engines (CodeQL #1301, #1302, #1349)
- headroom GCF needsQuote: inline-array regex excludes '[' from the bracket body (same .test verdict, linear on '[' runs).
- RTK raw-output: cut the tool_use command to 256 chars before the slug replaces.
- CCR grep: reject patterns with more than one unbounded quantifier and run the scan under a 1000 ms vm timeout.
2026-11-20 18:31:14 -03:00
diegosouzapw
b03f265540 chore(changelog): number the fragment for #20823 2026-11-20 18:30:47 -03:00
diegosouzapw
909af20270 fix(security): linear model id regexes (CodeQL #1325, #1324, #1296)
Rewrite three regexes that backtracked in O(n^2) on crafted ids with no length cap:
- githubResponsesFallback: /^(?:.*codex.*|gpt-(?:[6-9]|5\.[5-9]).*)$/i becomes a codex
  substring check, an anchored gpt prefix check and an explicit line-terminator reject.
- modelDisplayName VERSION_MARKER: /^v\d+([.\d]*)$/i becomes /^v\d[.\d]*$/i.
- isValidContext7LibraryId: /^\/(.+)\/(.+)$/ becomes /^\/([^/]+)\/([^/]+)$/.

A truth table generated from the base versions is pinned in the new test and passes
unchanged; 50k-char pathological ids now return in milliseconds.
2026-11-20 18:22:39 -03:00
serenity
59471c8d58 fix(cli): refuse restore while the server runs before asking for confirmation
omniroute restore asked [y/N] and then refused because a server answered,
so the user confirmed a restore that never ran. The running-server check now
comes right after the backup-id and backup-path checks, before the prompt;
message, exit code 1 and --yes behaviour are unchanged and nothing is
written.

The release notes now say that Apply and omniroute config set stop without
writing when an existing Claude, Cline, Kilo or Continue config file cannot
be parsed.
2026-11-20 14:58:21 +03:30
serenity
a91c7b8c06 fix(monitoring): judge pool health on the exact unhealthy ratio
The pool verdict compared the ratio after rounding it to two decimals,
so 1 of 3 unhealthy (0.333...) passed a 0.33 threshold and answered 200.
Compare the exact ratio and round only the value shown in the body.
2026-11-19 10:44:00 -03:00
diegosouzapw
83e890018d Merge remote-tracking branch 'origin/release/v3.8.55' into HEAD 2026-11-19 10:16:56 -03:00
diegosouzapw
10c3883ef4 Merge remote-tracking branch 'origin/release/v3.8.55' into HEAD 2026-11-19 07:21:39 -03:00
diegosouzapw
658402ca7f fix(ocr): drop retired Vertex deepseek-ocr-maas model, take self-deployed model id (#20423) 2026-11-19 05:19:58 -03:00
diegosouzapw
638e676ceb fix(claude): gate opted-in accounts whose plan windows and extra-usage cap are both spent (#18059) 2026-11-19 04:38:57 -03:00
serenity
ca5e0e680c docs(oauth): describe retry jitter as spreading accounts, list Google ids
The jitter is derived from the account id and attempt, so it spreads
different accounts, not replicas of one account. The Google refresh gap
covers antigravity, agy and gemini.
2026-11-19 00:01:23 -03:00
serenity
d17d44fffd fix(oauth): space Google refresh starts from the previous actual grant
Grants are serialized and each wait is measured from the last real start,
so a host sleep that makes several waits overdue no longer starts them
together. agy and gemini OAuth accounts get the same spacing.
2026-11-19 00:00:37 -03:00
serenity
73f02b9d74 fix(translator): read Responses usage names in the non-stream Gemini path and pair Cursor tool_result ids
- responseTranslator: the non-streaming OpenAI to Gemini-family converter falls
  back to input_tokens / output_tokens, so prompt and candidate counts are not
  zero while thoughtsTokenCount is set from output_tokens_details.
- openai-to-cursor: in a Cursor agent session, a Claude tool_result block carries
  the same first-line id as the assistant tool call it answers.
2026-11-18 23:49:07 -03:00
diegosouzapw
8176f09487 Merge remote-tracking branch 'origin/release/v3.8.55' into HEAD 2026-11-18 23:27:02 -03:00
diegosouzapw
b02e282ac7 Merge remote-tracking branch 'origin/release/v3.8.55' into HEAD 2026-11-18 23:18:47 -03:00
serenity
8fb3258b83 fix(cli): stage the restored database and refuse unparsable Continue YAML
- restore copies the backup database to a staging file next to the live one
  before touching anything live, so a failed copy (disk full, I/O error)
  leaves storage.sqlite and its WAL intact; only then are the stale sidecars
  removed and the staged copy renamed into place.
- The Continue generator no longer turns an unparsable config.yaml into an
  empty document that Apply would write over the user's file: it aborts like
  the JSON generators, and read errors such as the symlink guard propagate.
2026-11-18 22:29:41 -03:00
diegosouzapw
5bfc0c0aa6 Merge remote-tracking branch 'origin/release/v3.8.55' into HEAD 2026-11-18 22:23:59 -03:00
Kiaro-Sama
eaef73624b docs(changelog): record usage log colour repair 2026-11-19 01:52:02 +03:30
Kiaro-Sama
0813d37fd5 fix(logging): keep usage cache fields inside the green region 2026-11-19 01:50:55 +03:30
serenity
687f7effea Merge release/v3.8.54 into this branch
# Conflicts:
#	src/app/api/cli-tools/codex-settings/route.ts
2026-11-17 16:17:47 +03:30
serenity
ea623362f8 docs(changelog): number the fragment (#20380) 2026-11-16 21:41:02 +03:30
serenity
cdafb29e24 fix(memory): do not learn from a non-streaming reply the client never gets
In the non-streaming path, memory extraction ran before the post-call guardrail
and the malformed-reply gate. A reply that a guardrail blocked (the client gets
400) or that failed the malformed gate (502) was still offered to extractFacts,
so blocked content could enter durable Memory and be injected into later
prompts.

Move the extraction below both gates, next to the cache store, so it runs only
for a reply that goes back to the client. Nothing else moves. The wiring
characterization test pins the new order.

Finding: F-C2-12 (memory part).
2026-11-16 19:45:34 +03:30
xiaoyaner0201
91906d5532 docs(changelog): add fragment for #20359
Signed-off-by: xiaoyaner0201 <xiaoyaner0201@users.noreply.github.com>
2026-11-16 21:57:13 +08:00
xiaoyaner0201
9e0ea19e9d style(test): format the Business Premium selector case with Prettier
Signed-off-by: xiaoyaner0201 <xiaoyaner0201@users.noreply.github.com>
2026-11-16 21:23:30 +08:00
serenity
5a021bf4ca docs(changelog): number the fragment (#20341) 2026-11-16 14:52:58 +03:30
serenity
cb2f162029 docs(changelog): number the fragment (#20339) 2026-11-16 14:31:12 +03:30
xiaoyaner0201
82ff9b48d1 fix(codex): let Business Premium accounts serve Sol and Astra
The paid-plan allow-list in codexPlanEligibility normalizes plan types by
stripping separators, but has no entry for self_serve_business_prolite, the
plan type ChatGPT reports for Business Premium seats. Those connections were
therefore filtered out (codexPlanIneligible) for every Sol/Astra request while
Team and Pro Lite accounts were accepted. quotaPlanCapacity.ts already treats
the same plan as Business Premium.

Add the normalized plan to the allow-list and cover it with a selector-level
regression test.

Signed-off-by: xiaoyaner0201 <xiaoyaner0201@users.noreply.github.com>
2026-11-16 18:18:30 +08:00
serenity
4f24fe900f fix(kiro): send a tool result that has no matching tool call as text
openai-to-kiro already moved a tool result to the message text when the turn
before it had no toolUses at all. It never checked the ids. A result whose id
was not among the toolUses of the assistant turn right before it (a duplicate
or stray result in a later turn) stayed in toolResults, next to results that
do match. Kiro validates that pairing, and the orphan toolUse strip only
looks at toolUses, so the unpaired entry went upstream.

Move the pairing check into one helper used for history turns and for the
current message: unmatched entries become message text, matched entries stay
toolResults.

Finding: F-C5-81.
2026-11-16 11:40:44 +03:30
serenity
3933f8c3b0 fix(responses): send an empty object schema for a Chat tool without parameters
openaiToOpenAIResponsesRequest copied fn.parameters as it was, so a Chat
function tool that declares no parameters (a zero-argument tool such as
get_time) went out as a Responses function tool with no `parameters` field.
The Responses function tool schema lists `parameters`, and the Codex path
already defaults it to { type: "object", properties: {} }. Use the same
default on the generic OpenAI to Responses path.

Finding: F-C5-67.
2026-11-16 11:23:54 +03:30
serenity
a91df305a9 Merge release/v3.8.54 into this branch
# Conflicts:
#	tests/unit/db-migrationrunner-constants-split.test.ts
2026-11-15 21:01:14 +03:30
serenity
39fd3565e6 Merge release/v3.8.54 into this branch 2026-11-15 20:39:29 +03:30
serenity
52f4e527dd Merge release/v3.8.54 into this branch 2026-11-15 20:28:32 +03:30
serenity
a6a6694ac9 Merge release/v3.8.54 into this branch 2026-11-15 20:22:02 +03:30
diegosouzapw
ebc6182076 chore: leave translated catalogs, mirrors and generated files to the release refresh
Plan 2026-11-13 (derived values resolved only at release): a feature PR edits only the English
sources (src/i18n/messages/en.json, bin/cli/locales/en.json, the English docs) and the generators'
inputs. The other locale catalogs, the docs/i18n mirrors, .i18n-state.json, PROVIDER_REFERENCE.md,
the generated README SVGs and skills, and config/quality/e2e-timings.json are rewritten once by the
release refresh or a translation wave (config/quality/derived-paths/*.json). This commit restores
those files to the PR's merge base so the PR stops conflicting with every sibling that touched
them; the PR's own changes are untouched. Missing translations fall back to English at runtime
until the release refresh translates them.
2026-11-15 12:44:22 -03:00
serenity
3762f28f20 chore(db): convert the 239 migration to a timestamp name
#20169 froze the 001-241 series and 239 now belongs to
239_call_logs_pending_detail_index.sql on release/v3.8.54. Rename this
PR's migration with npm run db:new-migration (same description, same SQL)
and add a RENAMED_MIGRATION_COMPATIBILITY entry, so a database that ran a
build of this PR moves its 239 row to the new stamp instead of skipping
call_logs_pending_detail_index. The entry sits after the first entry, so
the positional spot-checks of the constants test stay put; the count goes
from 107 to 108.

Also from the review: the antiCheat.ts comment names the migration
instead of a number, and the anti-cheat index test closes its SQLite
handle and removes its DATA_DIR after the suite (createTempDataDir), so
an open handle cannot hang the runner.
2026-11-15 19:06:10 +03:30
serenity
eed69f0041 Merge release/v3.8.54 into this branch 2026-11-15 19:04:51 +03:30
diegosouzapw
272d1a73c9 chore: drop derived values the release refresh now owns
Plan 2026-11-13 (derived numbers resolved only at release): feature PRs no longer write values
that depend on the state of the base. This commit restores the lines this PR changed only to
update such values (counts in docs, the llm.txt mirrors, the Stryker test list, the package
description, counts in agent-instruction files) to the text of the PR's merge base, so merging
the current base brings the values `npm run release:refresh-derived` maintains. Every other
change of the PR is untouched.
2026-11-15 05:02:39 -03:00
diegosouzapw
e9548cb67d chore: drop derived values the release refresh now owns
Plan 2026-11-13 (derived numbers resolved only at release): feature PRs no longer write values
that depend on the state of the base. This commit restores the lines this PR changed only to
update such values (counts in docs, the llm.txt mirrors, the Stryker test list, the package
description, counts in agent-instruction files) to the text of the PR's merge base, so merging
the current base brings the values `npm run release:refresh-derived` maintains. Every other
change of the PR is untouched.
2026-11-15 05:01:54 -03:00
diegosouzapw
08e9c3ea72 chore: drop derived values the release refresh now owns
Plan 2026-11-13 (derived numbers resolved only at release): feature PRs no longer write values
that depend on the state of the base. This commit restores the lines this PR changed only to
update such values (counts in docs, the llm.txt mirrors, the Stryker test list, the package
description, counts in agent-instruction files) to the text of the PR's merge base, so merging
the current base brings the values `npm run release:refresh-derived` maintains. Every other
change of the PR is untouched.
2026-11-15 05:00:33 -03:00
diegosouzapw
3580391bd0 chore: drop derived values the release refresh now owns
Plan 2026-11-13 (derived numbers resolved only at release): feature PRs no longer write values
that depend on the state of the base. This commit restores the lines this PR changed only to
update such values (counts in docs, the llm.txt mirrors, the Stryker test list, the package
description, counts in agent-instruction files) to the text of the PR's merge base, so merging
the current base brings the values `npm run release:refresh-derived` maintains. Every other
change of the PR is untouched.
2026-11-15 04:59:31 -03:00
diegosouzapw
5fa63c10a8 chore: drop derived values the release refresh now owns
Plan 2026-11-13 (derived numbers resolved only at release): feature PRs no longer write values
that depend on the state of the base. This commit restores the lines this PR changed only to
update such values (counts in docs, the llm.txt mirrors, the Stryker test list, the package
description, counts in agent-instruction files) to the text of the PR's merge base, so merging
the current base brings the values `npm run release:refresh-derived` maintains. Every other
change of the PR is untouched.
2026-11-15 04:59:08 -03:00
diegosouzapw
511306251c chore: drop derived values the release refresh now owns
Plan 2026-11-13 (derived numbers resolved only at release): feature PRs no longer write values
that depend on the state of the base. This commit restores the lines this PR changed only to
update such values (counts in docs, the llm.txt mirrors, the Stryker test list, the package
description, counts in agent-instruction files) to the text of the PR's merge base, so merging
the current base brings the values `npm run release:refresh-derived` maintains. Every other
change of the PR is untouched.
2026-11-15 04:45:48 -03:00
diegosouzapw
53555c8fd3 chore: restore derived counts in their original digits
The previous maintainer commit put the derived counts in the translated
README mirrors back to the merge-base values, but wrote them as ASCII
numbers where the mirror uses native digits (for example Persian). The
lines still differed from the base and kept conflicting. This commit
writes the merge-base text back exactly. No other change.
2026-11-15 04:38:48 -03:00
diegosouzapw
c79305e945 chore: drop derived values the release refresh now owns
Plan 2026-11-13 (derived numbers resolved only at release): feature PRs no longer write values
that depend on the state of the base. This commit restores the lines this PR changed only to
update such values (counts in docs, the llm.txt mirrors, the Stryker test list, the package
description, counts in agent-instruction files) to the text of the PR's merge base, so merging
the current base brings the values `npm run release:refresh-derived` maintains. Every other
change of the PR is untouched.
2026-11-15 04:29:42 -03:00
serenity
561ff51c2d docs(changelog): number the fragment (#20229) 2026-11-15 03:43:20 +03:30
serenity
1f1c8c0d93 docs(changelog): number the fragment (#20224) 2026-11-15 02:51:05 +03:30
serenity
78c76407e5 docs(changelog): number the fragment (#20197) 2026-11-14 17:02:10 +03:30
serenity
871017e0d5 chore(changelog): name the new fragments 0000-<slug> for the publisher 2026-11-14 14:18:48 +03:30
serenity
7a1b9d198e fix(combo): record the session model once per successful target
The universal-handoff block in executeTargetAttempt called recordSessionModelUsage
before and after maybeGenerateUniversalHandoff with identical arguments. Each call
is a separate INSERT INTO session_model_history. When context_cache_protection is
also on, its own block writes a third row for the same session key.

The previous-model read still happens before the write, and the model that served
the response (including a fallback target) is still the one recorded. The
universal-handoff write is skipped only when the context-cache block already wrote
the same row for the same session key. getLastSessionModel reads the latest row,
so the removed rows carried no information.

Finding: ordata-47.
(cherry picked from commit 0fcd81c6e6a1679998936d5a256bc5a0be3c64c2)
2026-11-14 14:18:48 +03:30
serenity
c40aaac629 fix(combo): keep scoped auto candidates when the connection read fails
buildAutoCandidates, for an API key with a connection allowlist, set the
expansion targets to an empty list when the active-connection read threw.
No candidate was scored, and the failure was not logged. The unscoped branch
of the same function already records an empty pool and keeps going.

Keep the targets in the scoped branch too and log a warning with the
sanitized error. The targets were already bound to permitted connections by
expandAutoComboCandidatePool, and credential selection applies the key's
allowlist again at dispatch.

Finding: F-C4-11.
(cherry picked from commit 6a90e774860170a2a3493f30d92cc60c290a8dcd)
2026-11-14 14:18:48 +03:30
serenity
3588f5ca79 fix(sse): resolve provider aliases in clearProviderFailure, filter dead accounts
recordProviderFailure stores its 5 s dedupe keys under the canonical provider
id, but clearProviderFailure matched the raw argument, so a reset through an
alias left them behind and swallowed the next failure. Resolve the alias first.

filterAvailableAccounts checked rateLimitedUntil only, so a banned, expired or
credits-exhausted account passed. Drop those statuses too.

Finding: F-C4-19.
(cherry picked from commit bb5c5be86ebe5324e042ff259e77e8d190c8edab)
2026-11-14 14:18:48 +03:30
serenity
7e69860ab1 fix(providers): mark Muse Spark on OpenCode Zen and OpenCode Server as vision models
What: add supportsVision: true to muse-spark-1.2, muse-spark-1.2-contributor-free,
muse-spark-1.3 and muse-spark-1.3-contributor-free on opencode-zen, and to
muse-spark-1.3-contributor-free on opencode-server.

Why: these rows had no vision flag, so getResolvedModelCapabilities gave null and
combos and /v1/models treated them as text-only. The opencode-go Muse Spark rows
already set the flag, and OpenCode's own catalog on models.dev lists image input
for these ids.

Finding: e0260 (comparison re-check).
(cherry picked from commit e84e3016d7b5972fb57382ca075fb74c31eb1fa0)
2026-11-14 14:18:48 +03:30
serenity
63599ad10f fix(embeddings): send the configured API key on ollama-local embeddings
What: the ollama-local embedding registry entry now uses bearer auth.
A configured API key is sent as Authorization; without a key no header is
sent (authType stays none).

Why: the entry used authHeader none, so a key on the connection (for example
an authenticating reverse proxy in front of Ollama) was never sent. llama-cpp
and lemonade already use bearer with an optional key.

Finding: e0014 (comparison re-check).
(cherry picked from commit f16406f108fd45afd13a09f3764893dd7f241713)
2026-11-14 14:18:47 +03:30
serenity
b2e4554446 chore(changelog): name the new fragments 0000-<slug> for the publisher 2026-11-14 14:15:17 +03:30
serenity
3aaeec83d8 fix(sse): keep the caller's max_tokens when thinking is dropped
fitThinkingToMaxTokens dropped thinking when the fitted budget fell under the
Anthropic minimum, and returned the bare model cap as max_tokens. A 256-token
request with a 512-token budget went out with max_tokens 64000. Clamp the
caller's value to the model cap, as the no-thinking branch already does.

Finding: F-C5-76.
(cherry picked from commit b50587f38113720002b2551dd95c21ebb4b1caa3)
2026-11-14 14:15:17 +03:30
serenity
5f21cec083 fix(clova): keep the assistant text that precedes a tool call
toClovaToolModeMessage sent `content: ""` for every assistant turn that carried
tool_calls, so any text written before the call was lost from the history. Use
contentToString(record.content), which is "" when there is no text.

Finding: F-C5-78 (the assistant-text half; the tool_choice downgrade is left:
no CLOVA document naming a stronger value was read).

(cherry picked from commit abe797d3946f3bc72cb96ef512bfa781b3243a43)
2026-11-14 14:15:17 +03:30
serenity
abd4533a39 fix(responses): keep long call ids distinct when they are clamped to 64 characters
clampCallId cut an over-long id at 64 characters. Ids that differ only at the end, such as
functions.<long_tool_name>:0 and :1, became equal, so parallel calls collapsed to one id and
the orphan filter paired the wrong outputs. Keep 55 characters, then "_" and 8 hex of the
sha256 of the full id. The result is deterministic, so a call and its output still match.

Re-check id: F-C5-66.

(cherry picked from commit 5ba67a39c807e9a1ed57403fc9017a760fbd2fb2)
2026-11-14 14:15:17 +03:30
serenity
2d0d3112ad fix(gemini): count reasoning once in usageMetadata and read Responses usage names
candidatesTokenCount excludes thoughts in the Gemini API, but OpenAI completion_tokens
includes reasoning. buildGeminiUsageMetadata and the non-streaming Gemini-family path
now subtract thoughtsTokenCount, so prompt + candidates + thoughts = total. Both also
read input_tokens / output_tokens / input_tokens_details when the Chat names are absent.
Four neighbour tests pinned the old doubled count; they now expect the corrected value.

Re-check ids: F-C5-46, F-C5-54.

(cherry picked from commit cc88c2f6afbf99774a32e5f28737580a32d7cb03)
2026-11-14 14:15:17 +03:30
serenity
6bb7f88d98 fix(gemini): stop emitting Claude events after message_stop on a repeated finishReason
geminiToClaudeResponse emits message_delta and message_stop for every chunk with a
finishReason and has no finish flag. A trailing chunk that repeats finishReason produced
events after message_stop and a second message_stop. Set claudeFinishEmitted at the finish
and ignore later chunks, as openai-to-claude does.

Re-check id: F-C5-50 (part a). Part b (no flush for a stream without finishReason) was not
traced to the stream layer and is not changed.

(cherry picked from commit f8c46292c663262b2248ba9ea5462d3a16ed80c6)
2026-11-14 14:15:17 +03:30
serenity
799279a67a fix(gemini): do not emit tool calls twice when an OpenAI upstream repeats the finish chunk
The OpenAI to Antigravity and OpenAI to Gemini SSE converters flush the accumulated tool
calls at finish_reason but never clear them. A repeated finish chunk then emits every
functionCall again, and the client can run the tool twice. Clear the accumulator after
the flush.

Re-check id: F-C5-49.

(cherry picked from commit 94c9ac05416d82896363968942a0fe4d220bdee6)
2026-11-14 14:15:17 +03:30
serenity
d23a4fd5b2 fix(cursor): give the assistant tool call the same id as its structured tool result
With a Cursor agent session the tool message id is cut at the first newline, but the assistant
tool_calls id (and a tool_use id in assistant content) was copied unchanged. An id such as
"call_a\nfc_b" then gave two different ids, and the later orphan pass dropped the result. Apply
the same normalization to the assistant side when tool results stay structured.
Reach is inferred: it needs a Cursor session and an id with a newline.

Re-check id: F-C5-43.

(cherry picked from commit b756924c80fcfce43cdfde4bbdab940a2da96c0e)
2026-11-14 14:15:17 +03:30
serenity
5cbee02707 chore(changelog): name the bundle fragments 0000-<slug> and make each a bullet
The publisher renames the 0000- placeholders to the PR number.
2026-11-14 14:09:11 +03:30
serenity
3249965f8a fix(sse): count systemInstruction in the final-input estimate
estimateFinalInputTokenBreakdown counted messages, top-level tools, system and
instructions. A Gemini-shaped body keeps its system prompt in systemInstruction
(or system_instruction, or request.systemInstruction for Cloud Code), and its
tools under request.tools, so a 40k-character system prompt added 0 tokens.
That estimate feeds the last-resort compaction guard and the estimator
calibration, which pairs it with the provider's real prompt_tokens.

Finding: F-C2-42.
(cherry picked from commit 208c66b117db2e6b89f9d341d6089fc880527df2)
2026-11-14 14:09:11 +03:30
serenity
38dc13c18b fix(sse): do not cache a failed combo or proxy-config read
getCombosCached kept a rejected promise for the 10 s TTL, so every caller
re-threw the same transient error. getUpstreamProxyConfigCached turned a read
error into the native default and cached it for 10 s without a log line, so a
provider set to the upstream proxy went direct for 10 s after one failed read.
Drop the rejected promise, and return the default for the failed call only,
with a warning.

Finding: F-C2-44.
(cherry picked from commit 4084a767c9c163bd88d769456d7a214b4c9a6b11)
2026-11-14 14:09:11 +03:30
serenity
d56a18406b fix(sse): default a falsy Claude tool type to custom
defaultClaudeToolType guards on a falsy `type` but built the default as
`{ type: "custom", ...tool }`, so an own `type: null`, `""` or `undefined`
overwrote it and the tool went out without a usable type. Put `type` after the
spread.

Finding: F-C2-43.
(cherry picked from commit 3e14a38daf1aad86075901dc3e3e88e91d886e28)
2026-11-14 14:09:11 +03:30
serenity
62c7b123e5 fix(sse): treat undefined cache usage keys as not reported
hasCacheUsageFields used the `in` operator. The usage extractors create the
cache keys with the value `undefined` when the provider sent nothing, so every
OpenAI-shaped response logged cacheReadTokens 0 and cacheCreationTokens 0, and
Gemini cache evidence read "invalid" instead of "unreported". Test the value.

Finding: F-C2-37.
(cherry picked from commit e5495de0e2a5864cc9bf2bdcd13be8838c6c764d)
2026-11-14 14:09:11 +03:30
serenity
648192b7dd fix(sse): keep forced and already-called tools when the default tool cap applies
capToolList kept the first N tools in order and pinned only the web fallback tools. The
promise in toolDisclosure ("never dropped: tools already called, a forced tool_choice
tool") holds only when tool disclosure is configured, but the default cap (128) applies to
every non-Claude target. A forced tool past position 128 was cut, which gives an upstream
400 or a wrong answer, and so was a tool the history had already called. Reuse the
disclosure module's own collectHistoryToolNames to pin those names.

Finding: F-C3-16
(cherry picked from commit f19c8ca24598ef71268f8d477b6132c5bc0d2c90)
2026-11-14 14:09:11 +03:30
serenity
bd1e271be3 fix(plugins): a block with an unserializable response must still block
runPluginOnRequestHook built the 403 Response inside the same try as the hook run. A
blocking hook whose response held a BigInt or a cycle made JSON.stringify throw; the
fail-open catch then returned blocked:false and the request went to the provider, so a
plugin's block decision was lost. Build the block response in its own guarded step and
fall back to the generic plugin_block body.

Not changed here: the plugin's `status` field is still ignored (always 403) and the
onRequest metadata is still not handed to onResponse. Both need an SDK decision.

Finding: F-C3-32 (block-to-allow part)
(cherry picked from commit 7bac0b633d51071e475b54b3346196efa3012045)
2026-11-14 14:09:11 +03:30
serenity
95248b1b11 fix(sse): do not refresh the OAuth token on a Claude "Request not allowed" 403
The error classifier maps a Claude OAuth 403 "Request not allowed" to REQUEST_REJECTED:
the upstream refused this request, not the credential. The refresh gate
(shouldSkipCredentialRefresh) did not know that case, so every refusal cost a refresh
of the rotating refresh token and one more send into the enforcement that the refusal
streak is built to avoid. Skip the refresh for it, using the classifier's own predicates.

Finding: F-C3-34
(cherry picked from commit f82210e2200016ad0dc65de403f118ee5840d768)
2026-11-14 14:09:10 +03:30
serenity
568c680261 chore(skills): regenerate cli-backup-sync for restore --key-file
check:agent-skills-sync failed on the restore decrypt commit because the generated skill did not list the new --key-file option. Output of scripts/skills/generate-agent-skills.mjs --apply; one line added.
2026-11-13 13:24:03 +03:30
serenity
2185c7a8db docs(changelog): number the fragment (#20122) 2026-11-13 13:18:32 +03:30
serenity
89186157dc fix(cli): decrypt encrypted backup archives during restore
backup create --encrypt writes only <name>.enc payloads (scrypt, AES-256-GCM, salt16 + iv12 + tag16 + ciphertext). After the refuse-and-fail change restore exits 1 on such a backup, so the product still cannot restore an archive it made.

restore now takes --key-file <path> or asks for the passphrase. It decrypts every payload into a private temp dir first and copies into the data dir only after all payloads decrypted and the database passes the integrity check. A wrong passphrase or a damaged payload fails the GCM tag check, prints one message, exits 1 and leaves the live files unchanged. The temp dir is removed on every path. An empty passphrase or end of input exits 1. Plain backups restore as before.

New i18n key backup.restoreDecryptFailed in en, zh-CN and zh-TW; other locales fall back to en.
2026-11-13 12:54:04 +03:30
serenity
a2897f3505 Merge remote-tracking branch 'origin/release/v3.8.54' into fix/or9r-restore-decrypt-v2 2026-11-13 12:52:04 +03:30
serenity
da0e3c2f4c perf(guardrails): skip PII work while masking is off 2026-11-13 12:26:36 +03:30
serenity
74b42d209d docs: restore the ETH donation address in the README mirrors
The migration-count bump in this PR also changed one digit of the ETH
donation address (...102337a84 -> ...102347a84) in 66 README files.
Put the original address back; the address now matches the base branch.
2026-11-13 11:06:25 +03:30
serenity
024882f804 chore(changelog): name the refresh-health fragments by slug
The repo names unnumbered fragments by slug. The PR number is not known yet.
2026-11-12 22:46:32 +03:30
serenity
f253d9c2cc feat(resilience): opt-in cap on the Retry-After sent to clients
What: with CLIENT_RETRY_AFTER_MAX_SECONDS set, the chat handler wrapper
lowers any Retry-After header above that many seconds on a 4xx or 5xx
response. Seconds and HTTP-date values both count.

Why: a client with a fallback chain waited hours on one long upstream
Retry-After before it moved to the next provider. The account rest is
computed from the upstream header inside the handler, so it keeps its full
length. Only the copy that leaves the gateway is capped.

Default: off. Unset or invalid keeps today's behaviour. The JSON body
retry_after field is not rewritten.

(cherry picked from commit e44ee91d40aee7c99095aba1fb913545b3d8e050)
2026-11-12 22:46:25 +03:30
serenity
d6c39585fd feat(cliproxy): read CPA account health from the v8 route when v0 is gone
What: the account health probe still asks /v0/management/auth-files first.
On HTTP 404 it asks /v8/management/credentials with the same key and reads
the same payload. 401, 403 and other statuses do not trigger the fallback.

Why: CPA marks its v0 management routes deprecated and unmaintained. When
they are removed, the health card would show "unsupported" for a working CPA.

Default state: no flag. A CPA that still serves v0 gets the same single
request as before. Only a 404 costs one extra request.

(cherry picked from commit c5b728dbe2eb4e4fb137f535333f3f414e79b346)
2026-11-12 22:46:13 +03:30
serenity
8478ee6cb6 feat(network): opt-in wake recovery that flushes pooled upstream sockets
What: a 5 s heartbeat compares wall-clock time. A gap above 30 s means the host
slept, so the dispatcher cache is cleared once. The timer is unref-ed and the
callback cannot throw into the timer. Started from the optional boot table.

Why: sockets pooled before a laptop sleeps are dead after resume. The first
requests reuse them and fail. A flush makes them open fresh sockets.

Default state: off. Set OMNIROUTE_WAKE_RECOVERY=1 to enable. Headless mode skips
it with the other optional subsystems. Key re-probing is not part of this slice.

(cherry picked from commit 8dabc80d816cb72be1f6e16f3bf9b1335d3a03b9)
2026-11-12 22:45:59 +03:30
serenity
b8ac709829 feat(auth): opt-in per-provider cap on proactive token refreshes
What: with HEALTHCHECK_PER_PROVIDER_CONCURRENCY=N, the token healthcheck sweep
runs at most N refreshes in flight per provider. The rest of that provider's
accounts in the batch wait their turn. Providers do not wait on each other.

Why: the sweep refreshes connections in batches of 20 with no per-provider
limit, so a provider with many accounts sends all its refreshes to one identity
endpoint at once. Other LLM gateways queue refreshes per provider.

Default state: off. With the variable unset, 0 or invalid, nothing changes.
Not in this slice: a global cap across providers, a dedupe buffer, a refresh
timeout, and marking a node unhealthy after repeated failures.

(cherry picked from commit 3d54e3c944a76b9414b4293705ff4b80dd945783)
2026-11-12 22:45:47 +03:30
serenity
d04c1541ff feat(oauth): opt-in spacing between Google background token refreshes
What: with BG_REFRESH_GOOGLE_DELAY_MS set, the token health sweep waits
for a slot before it refreshes an antigravity or gemini-cli account. Each
refresh starts at least the base gap after the previous one, plus up to one
third of the base as jitter (12000 gives a 12 s gap and up to 4 s jitter).

Why: the sweep refreshes up to 20 accounts at once, and Google accounts are
not serialized. A burst of refreshes from one host can trip anti-abuse
limits.

Default: off. Unset or 0 keeps today's behaviour. The gap clock lives in
one process; it is not shared across replicas.

(cherry picked from commit 7efa0e0acefe1ab6fff8e0d16875242281140314)
2026-11-12 22:45:34 +03:30
serenity
5333e6a223 feat(oauth): opt-in deterministic jitter for token-refresh retries
What: refreshWithRetry waits attempt * 1000 ms between retries for every
account. With TOKEN_REFRESH_RETRY_JITTER=1 the wait is scaled by 75-125
percent. The factor comes from a hash of the account id and the attempt
number.

Why: replicas and accounts that fail together retried together. A hash
spreads the delays without random flakiness: the same id and attempt always
give the same delay.

Default: off. Without the env var the delay is unchanged.
(cherry picked from commit b6ffe2b0a7a4bf127a2dc787687184947cb7274d)
2026-11-12 22:45:21 +03:30
serenity
aa0501aa49 refactor(cli-tools): move the probe slot counter into a small helper
The complexity ratchet counted one new violation in all-statuses/route.ts:
the inline slot counter made the per-tool callback pass the complexity
limit. Move it into createSlots with acquire and release so the file is back
at its base count. Behaviour is unchanged: at most four uncached checks run
at once and a slot is freed in finally.
2026-11-11 09:24:52 +03:30
serenity
7d8f2ed96e Merge remote-tracking branch 'origin/release/v3.8.54' into ci/19716 2026-11-11 09:21:32 +03:30
serenity
aaa6c2dc47 Merge remote-tracking branch 'origin/release/v3.8.54' into ci/19633 2026-11-11 09:14:24 +03:30
serenity
37dc6e6a9b docs(changelog): number the fragment (#19741) 2026-11-10 19:39:41 +03:30
serenity
55cb20e500 perf(gamification): add a created_at-first covering index for the hourly XP audit range
validateScoreChange runs on every completed keyed chat. Its global mean and
variance query groups the last hour of xp_audit_log by key. The only index
starts with api_key_id, and SQLite prefers it for the GROUP BY. Without
sqlite_stat1 the plan is a scan of every retained audit row.

Add migration 238: an index on (created_at, api_key_id, xp_earned). Write the
GROUP BY as +api_key_id so SQLite cannot pick the key-first index to avoid a
sort. The plan becomes a covering range search on created_at. Results are
unchanged. The per-key checks keep using the existing key-first index.
2026-11-10 19:28:59 +03:30
serenity
4e4bc8f799 docs(changelog): number the fragment (#19716) 2026-11-10 17:36:32 +03:30
serenity
b06e40e5a0 perf(cli-tools): cap the CLI status probes at four at once
A cold GET /api/cli-tools/all-statuses started one detection and config
check per catalog tool, 39 at once. Each check can spawn a login-shell
lookup and a version probe, so a cold batch launched dozens of child
processes together.

Run the uncached checks through four slots. A tool waits for a free slot
before its 5 second limit starts, so a queued tool does not time out
while it waits. Cache hits skip the queue. The result map still holds
every tool, and a failed check still frees its slot.

(cherry picked from commit d87976359a1ce0dd5ea7ae31252ccb0d4fd0ab4a)
2026-11-10 17:25:32 +03:30
serenity
97379a6c7e perf(analytics): run the daily cost grain scan once per analytics cache miss
GET /api/usage/analytics asked for four row sets: daily cost, model usage,
provider cost and service-tier usage. All four grouped the same unified
source by day, provider, model and service tier and summed the same token and
cost columns, so one analytics build ran the same grouped scan four times.

getDailyCostRows now returns the superset of the four row shapes (requests,
total tokens, average latency, successful requests, last used, plus the token
and cost sums). The route reads it once and derives the other three views:
the model view sorts the same rows by request count, and the provider cost
and service-tier views read them unchanged. Their consumers already merge rows
by model, provider and tier, so the output does not change.

getModelUsageRows, getProviderCostRows and getServiceTierUsageRows had no
other caller. They are removed with their row types. Tests that called them now
call getDailyCostRows, and the function-list test drops the removed names.

Measured on 200000 usage rows over 90 days (720 grain rows): the four queries
took 1245 ms median, the one query takes 342 ms.

(cherry picked from commit 023147fe510253ea4db55b88641969da42e81b70)
2026-11-10 17:25:32 +03:30
serenity
55b62e9356 fix(monitoring): report one provider pool as counts and one verdict
An uptime monitor that watches an account pool had to fetch and parse
the full health payload. The payload has no per-pool ratio, so no
plain HTTP check could tell a degraded pool from a healthy one.

Add ?provider=<id>[&unhealthRatioThreshold=0..1] to the health route.
It counts the active accounts of that provider, marks an account
unhealthy when its stored status is a known non-ok or it is cooling
down, and answers with total, healthy, unhealthy, the ratio and
summaryHealth. HTTP status is 200 when the ratio is within the
threshold (default 0.5) and 503 when it is not. A pool with no active
account has ratio 1. The answer needs management auth and carries
counts only, never an account name, id or key.

The hard-lease inventory test counts getProviderConnections calls per
file; the route now has two read-only calls (class C), so its expected
count is 2.

(cherry picked from commit f4ae5f53a5597058007b75daa25043fb1e05132e)
2026-11-10 17:25:32 +03:30
serenity
4c1c02f408 fix(codex): keep a user's root openai_base_url on apply and remove
The codex-settings route deleted the root openai_base_url key on every Apply
and on every Remove, whatever its value. A user who routes the built-in OpenAI
provider through their own proxy lost that line, and nothing recorded that the
key was ever OmniRoute's.

OmniRoute writes the same URL into [model_providers.omniroute].base_url. Treat
a root openai_base_url as OmniRoute's only when it equals that recorded URL (or
the URL this Apply is about to write), ignoring trailing slashes. Any other
value stays. Remove no longer needs a provider section to be safe: without one
the key is kept.

The provider section is still replaced on Apply; only the root key is now
guarded.

(cherry picked from commit 4dda0fd7e3d1cdebf2a7c4042546bfeaa0c4758b)
2026-11-10 17:25:32 +03:30
serenity
04596e0281 docs(changelog): number the fragment (#19633) 2026-11-10 09:22:40 +03:30
serenity
70993506ee fix(cli-tools): keep unrelated settings when applying Claude, Cline, Kilo and Continue configs
These four generators returned a new document and were not path-aware,
so Apply and config set replaced the whole file. A small JSONC merge
helper now edits only the managed keys and keeps comments; Continue
replaces only its OmniRoute model entry. An unparseable existing file
aborts Apply, as Codex and OpenCode already do.

(cherry picked from commit 252efa932ae805e98326effd188fe3880637a86f)
2026-11-10 09:12:10 +03:30
serenity
65b5bdf7b5 fix(cli): restore the database only with the server stopped and no stale WAL
The CLI restore copied storage.sqlite over the live file and left the
-wal file in place, so SQLite replayed the old WAL over the restored
database. Refuse while a server answers on the base URL, run
PRAGMA integrity_check on the backup first, and remove -wal, -shm and
-journal just before the copy.

(cherry picked from commit 085276eb90debb1059948329034ad6ce951bd428)
2026-11-10 09:12:10 +03:30
203 changed files with 6441 additions and 917 deletions

View File

@@ -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
# ═══════════════════════════════════════════════════════════════════════════════

View File

@@ -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)

View File

@@ -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".
---

View File

@@ -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

View File

@@ -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 });
}
}

View File

@@ -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`

View File

@@ -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": {

View File

@@ -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}`);
}
}

View File

@@ -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) {

View File

@@ -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);

View 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).

View 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.

View 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).

View 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.

View 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).

View 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.

View File

@@ -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)

View 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))

View File

@@ -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))

View File

@@ -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))

View 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))

View 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))

View 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))

View 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))

View 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))

View 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))

View File

@@ -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))

View 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))

View 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))

View 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))

View 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))

View 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))

View 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))

View 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))

View 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))

View File

@@ -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))

View 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))

View 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))

View 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))

View 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))

View 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))

View 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))

View File

@@ -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))

View 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))

View 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))

View 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)

View 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.

View 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)

View 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)

View File

@@ -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))

View File

@@ -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))

View File

@@ -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)

View 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.

View 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

View File

@@ -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))

View 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))

View 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))

View File

@@ -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))

View File

@@ -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.",

View File

@@ -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,

View File

@@ -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.

View File

@@ -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:

View File

@@ -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. |

View File

@@ -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" },

View File

@@ -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,
},
};

View File

@@ -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",

View File

@@ -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 ────────────────────────────────────────────────

View File

@@ -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))
);
}

View File

@@ -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;
});

View File

@@ -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;
}

View File

@@ -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) };

View File

@@ -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,

View File

@@ -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);

View File

@@ -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;

View File

@@ -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(", ");

View File

@@ -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;

View File

@@ -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)
);

View File

@@ -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) {

View File

@@ -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 ?? "");

View File

@@ -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

View File

@@ -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));

View File

@@ -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()}`),

View File

@@ -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

View File

@@ -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" ||

View File

@@ -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;

View File

@@ -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(

View File

@@ -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 };
}

View File

@@ -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
);

View File

@@ -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,
});

View File

@@ -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

View File

@@ -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;

View File

@@ -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",

View File

@@ -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(

View File

@@ -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,

View File

@@ -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:

View File

@@ -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));
}

View File

@@ -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[] {

View File

@@ -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"

View File

@@ -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 };

View File

@@ -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