7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(vision): end-to-end image input — Responses translation, Gemini signature fallback, body limits, inbound normalization (#852)
熬夜砍树8f27336b6ee4
diff --git a/.env.example b/.env.exampleindex 41c03917..9d3c4321 100644--- a/.env.example+++ b/.env.example@@ -38,6 +38,27 @@ PORT=3001# tighter cap. Set to 0 to disable.# ADMIN_RATE_LIMIT_RPM=600+# JSON body limit in MB for the inference surfaces (/v1, /v1beta, /mcp,+# Ollama /api/*) — default: 25. Vision requests embed base64 images in the+# body and replay them with every turn, so large sessions can clear 10MB;+# this ceiling only gates parsing — inbound image normalization (below)+# shrinks the payload afterwards. Raise it if bigger payloads are rejected+# with 413 'request_too_large'.+# REQUEST_BODY_LIMIT_MB=25++# Inbound image normalization: data-URL images over the threshold are+# downscaled to the long-edge cap and re-encoded (JPEG, or PNG only when the+# alpha channel carries real transparency) before routing, shrinking replayed+# screenshots ~6-10x. Also normalizes exotic formats upstreams reject+# (bmp/gif/tiff/avif/webp → jpeg/png); gif keeps its first frame only. Every+# upstream resizes internally anyway (OpenAI to 2048px, Anthropic to 1568px),+# so pixels beyond the cap are transport waste. Set IMAGE_NORMALIZE=off to+# disable entirely.+# IMAGE_NORMALIZE=on+# IMAGE_NORMALIZE_MAX_DIMENSION=2048+# IMAGE_NORMALIZE_THRESHOLD_KB=1024+# IMAGE_NORMALIZE_QUALITY=90+# Outbound proxy for provider requests. Normally set in the dashboard# (Keys → Outbound proxy); these env vars are for headless installs.# Schemes: http, https, socks4, socks4a, socks5, socks5h. The `h`/`a` variantsdiff --git a/package-lock.json b/package-lock.jsonindex 6e1e6422..1222f18a 100644--- a/package-lock.json+++ b/package-lock.json@@ -1531,6 +1531,564 @@"url": "https://github.com/sponsors/nzakas"}},+ "node_modules/@img/colour": {+ "version": "1.1.0",+ "resolved": "https://registry.npmmirror.com/@img/colour/-/colour-1.1.0.tgz",+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@img/sharp-darwin-arm64": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.3.tgz",+ "integrity": "sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-arm64": "1.3.2"+ }+ },+ "node_modules/@img/sharp-darwin-x64": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.3.tgz",+ "integrity": "sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-x64": "1.3.2"+ }+ },+ "node_modules/@img/sharp-freebsd-wasm32": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.3.tgz",+ "integrity": "sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg==",+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "dependencies": {+ "@img/sharp-wasm32": "0.35.3"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-arm64": {+ "version": "1.3.2",+ "resolved": "https://registry.npmmirror.com/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.2.tgz",+ "integrity": "sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg==",+ "cpu": [+ "arm64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-x64": {+ "version": "1.3.2",+ "resolved": "https://registry.npmmirror.com/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.2.tgz",+ "integrity": "sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw==",+ "cpu": [+ "x64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm": {+ "version": "1.3.2",+ "resolved": "https://registry.npmmirror.com/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.2.tgz",+ "integrity": "sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ==",+ "cpu": [+ "arm"+ ],+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm64": {+ "version": "1.3.2",+ "resolved": "https://registry.npmmirror.com/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.2.tgz",+ "integrity": "sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA==",+ "cpu": [+ "arm64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-ppc64": {+ "version": "1.3.2",+ "resolved": "https://registry.npmmirror.com/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.2.tgz",+ "integrity": "sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw==",+ "cpu": [+ "ppc64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-riscv64": {+ "version": "1.3.2",+ "resolved": "https://registry.npmmirror.com/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.2.tgz",+ "integrity": "sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w==",+ "cpu": [+ "riscv64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-s390x": {+ "version": "1.3.2",+ "resolved": "https://registry.npmmirror.com/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.2.tgz",+ "integrity": "sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ==",+ "cpu": [+ "s390x"+ ],+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-x64": {+ "version": "1.3.2",+ "resolved": "https://registry.npmmirror.com/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.2.tgz",+ "integrity": "sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w==",+ "cpu": [+ "x64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {+ "version": "1.3.2",+ "resolved": "https://registry.npmmirror.com/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.2.tgz",+ "integrity": "sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw==",+ "cpu": [+ "arm64"+ ],+ "libc": [+ "musl"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {+ "version": "1.3.2",+ "resolved": "https://registry.npmmirror.com/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.2.tgz",+ "integrity": "sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ==",+ "cpu": [+ "x64"+ ],+ "libc": [+ "musl"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-linux-arm": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.3.tgz",+ "integrity": "sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA==",+ "cpu": [+ "arm"+ ],+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm": "1.3.2"+ }+ },+ "node_modules/@img/sharp-linux-arm64": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.3.tgz",+ "integrity": "sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ==",+ "cpu": [+ "arm64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm64": "1.3.2"+ }+ },+ "node_modules/@img/sharp-linux-ppc64": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.3.tgz",+ "integrity": "sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA==",+ "cpu": [+ "ppc64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-ppc64": "1.3.2"+ }+ },+ "node_modules/@img/sharp-linux-riscv64": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.3.tgz",+ "integrity": "sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ==",+ "cpu": [+ "riscv64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-riscv64": "1.3.2"+ }+ },+ "node_modules/@img/sharp-linux-s390x": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.3.tgz",+ "integrity": "sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw==",+ "cpu": [+ "s390x"+ ],+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-s390x": "1.3.2"+ }+ },+ "node_modules/@img/sharp-linux-x64": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.3.tgz",+ "integrity": "sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA==",+ "cpu": [+ "x64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-x64": "1.3.2"+ }+ },+ "node_modules/@img/sharp-linuxmusl-arm64": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.3.tgz",+ "integrity": "sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w==",+ "cpu": [+ "arm64"+ ],+ "libc": [+ "musl"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.2"+ }+ },+ "node_modules/@img/sharp-linuxmusl-x64": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.3.tgz",+ "integrity": "sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg==",+ "cpu": [+ "x64"+ ],+ "libc": [+ "musl"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-x64": "1.3.2"+ }+ },+ "node_modules/@img/sharp-wasm32": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-wasm32/-/sharp-wasm32-0.35.3.tgz",+ "integrity": "sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w==",+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/runtime": "^1.11.1"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-wasm32/node_modules/@emnapi/runtime": {+ "version": "1.11.3",+ "resolved": "https://registry.npmmirror.com/@emnapi/runtime/-/runtime-1.11.3.tgz",+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@img/sharp-webcontainers-wasm32": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.3.tgz",+ "integrity": "sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q==",+ "cpu": [+ "wasm32"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "dependencies": {+ "@img/sharp-wasm32": "0.35.3"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-arm64": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.3.tgz",+ "integrity": "sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-ia32": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.3.tgz",+ "integrity": "sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw==",+ "cpu": [+ "ia32"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-x64": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.3.tgz",+ "integrity": "sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },"node_modules/@inquirer/ansi": {"version": "2.0.5","resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.5.tgz",@@ -9566,6 +10124,67 @@"shadcn": "dist/index.js"}},+ "node_modules/sharp": {+ "version": "0.35.3",+ "resolved": "https://registry.npmmirror.com/sharp/-/sharp-0.35.3.tgz",+ "integrity": "sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@img/colour": "^1.1.0",+ "detect-libc": "^2.1.2",+ "semver": "^7.8.5"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-darwin-arm64": "0.35.3",+ "@img/sharp-darwin-x64": "0.35.3",+ "@img/sharp-freebsd-wasm32": "0.35.3",+ "@img/sharp-libvips-darwin-arm64": "1.3.2",+ "@img/sharp-libvips-darwin-x64": "1.3.2",+ "@img/sharp-libvips-linux-arm": "1.3.2",+ "@img/sharp-libvips-linux-arm64": "1.3.2",+ "@img/sharp-libvips-linux-ppc64": "1.3.2",+ "@img/sharp-libvips-linux-riscv64": "1.3.2",+ "@img/sharp-libvips-linux-s390x": "1.3.2",+ "@img/sharp-libvips-linux-x64": "1.3.2",+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.2",+ "@img/sharp-libvips-linuxmusl-x64": "1.3.2",+ "@img/sharp-linux-arm": "0.35.3",+ "@img/sharp-linux-arm64": "0.35.3",+ "@img/sharp-linux-ppc64": "0.35.3",+ "@img/sharp-linux-riscv64": "0.35.3",+ "@img/sharp-linux-s390x": "0.35.3",+ "@img/sharp-linux-x64": "0.35.3",+ "@img/sharp-linuxmusl-arm64": "0.35.3",+ "@img/sharp-linuxmusl-x64": "0.35.3",+ "@img/sharp-webcontainers-wasm32": "0.35.3",+ "@img/sharp-win32-arm64": "0.35.3",+ "@img/sharp-win32-ia32": "0.35.3",+ "@img/sharp-win32-x64": "0.35.3"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ }+ }+ },+ "node_modules/sharp/node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmmirror.com/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },"node_modules/shebang-command": {"version": "2.0.0","resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",@@ -12225,6 +12844,7 @@"express": "^5.1.0","helmet": "^8.1.0","multer": "^2.2.0",+ "sharp": "^0.35.3","socks-proxy-agent": "^10.0.0","undici": "^6.21.0","zod": "^3.24.4"diff --git a/server/package.json b/server/package.jsonindex e0cf1711..5cbf7822 100644--- a/server/package.json+++ b/server/package.json@@ -26,6 +26,7 @@"express": "^5.1.0","helmet": "^8.1.0","multer": "^2.2.0",+ "sharp": "^0.35.3","socks-proxy-agent": "^10.0.0","undici": "^6.21.0","zod": "^3.24.4"diff --git a/server/src/__tests__/lib/image-normalize-no-sharp.test.ts b/server/src/__tests__/lib/image-normalize-no-sharp.test.tsnew file mode 100644index 00000000..a1df01b9--- /dev/null+++ b/server/src/__tests__/lib/image-normalize-no-sharp.test.ts@@ -0,0 +1,71 @@+import { describe, it, expect, vi } from 'vitest';+import type { ChatMessage } from '@freellmapi/shared/types.js';++// sharp is a NATIVE module. It is loaded with a dynamic import precisely so a+// missing or mismatched prebuilt libvips cannot take the gateway down at+// import time — the desktop build only electron-rebuilds better-sqlite3, and+// slim/musl containers routinely ship without the matching binary. This is the+// degraded path: images must ride through untouched and the request must still+// be served.+//+// Own file because the resolved module is cached in module state after the+// first call; vitest isolates the registry per file, so the failure is only+// observable from a file that has never loaded the real sharp.+vi.mock('sharp', () => ({+ get default(): never {+ throw new Error(+ "Could not load the 'sharp' module using the linux-x64 runtime",+ );+ },+}));++const { normalizeMessageImages } = await import('../../lib/image-normalize.js');++// A data URL big enough to clear every threshold — it must survive byte-for-byte.+const BIG_IMAGE = `data:image/png;base64,${'A'.repeat(2_000_000)}`;++function imageTurn(url: string): ChatMessage[] {+ return [{+ role: 'user',+ content: [+ { type: 'text', text: 'what is this?' },+ { type: 'image_url', image_url: { url } },+ ],+ } as any];+}++describe('inbound image normalization without sharp', () => {+ it('passes images through untouched instead of throwing', async () => {+ const messages = imageTurn(BIG_IMAGE);++ const summary = await normalizeMessageImages(messages, { thresholdBytes: 0 });++ expect(summary.normalized).toBe(0);+ expect(summary.bytesBefore).toBe(0);+ expect(summary.bytesAfter).toBe(0);+ // Same array, same bytes: the request is served exactly as it was before+ // this module existed.+ expect(summary.messages).toBe(messages);+ expect((messages[0].content as any[])[1].image_url.url).toBe(BIG_IMAGE);+ });++ it('warns once, not once per image', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ await normalizeMessageImages(imageTurn(BIG_IMAGE), { thresholdBytes: 0 });+ await normalizeMessageImages(imageTurn(BIG_IMAGE), { thresholdBytes: 0 });+ // The failed load is remembered, so a busy gateway does not reprint the+ // warning (or retry the import) on every vision request.+ expect(warn).not.toHaveBeenCalled();+ } finally {+ warn.mockRestore();+ }+ });++ it('still honours the disable switch', async () => {+ const messages = imageTurn(BIG_IMAGE);+ const summary = await normalizeMessageImages(messages, { enabled: false });+ expect(summary.normalized).toBe(0);+ expect(summary.messages).toBe(messages);+ });+});diff --git a/server/src/__tests__/lib/image-normalize.test.ts b/server/src/__tests__/lib/image-normalize.test.tsnew file mode 100644index 00000000..6c7dfa2b--- /dev/null+++ b/server/src/__tests__/lib/image-normalize.test.ts@@ -0,0 +1,227 @@+import { describe, it, expect } from 'vitest';+import sharp from 'sharp';+import type { ChatMessage } from '@freellmapi/shared/types.js';+import { normalizeMessageImages } from '../../lib/image-normalize.js';++async function solidPng(width: number, height: number, alpha: false | number = false): Promise<string> {+ const buf = await sharp({+ create: {+ width,+ height,+ channels: alpha === false ? 3 : 4,+ background: alpha === false+ ? { r: 255, g: 0, b: 0 }+ : { r: 255, g: 0, b: 0, alpha },+ },+ }).png().toBuffer();+ return `data:image/png;base64,${buf.toString('base64')}`;+}++// Random-noise fixture so lossy re-encoding has real bytes to squeeze+// (solid colors compress to nothing and hide compression regressions).+async function noiseJpeg(width: number, height: number, quality: number): Promise<string> {+ const raw = Buffer.alloc(width * height * 3);+ for (let i = 0; i < raw.length; i++) raw[i] = Math.floor(Math.random() * 256);+ const buf = await sharp(raw, { raw: { width, height, channels: 3 } })+ .jpeg({ quality })+ .toBuffer();+ return `data:image/jpeg;base64,${buf.toString('base64')}`;+}++async function smallJpeg(width = 64, height = 64): Promise<string> {+ const buf = await sharp({+ create: { width, height, channels: 3, background: { r: 0, g: 128, b: 255 } },+ }).jpeg({ quality: 80 }).toBuffer();+ return `data:image/jpeg;base64,${buf.toString('base64')}`;+}++async function dims(dataUrl: string): Promise<{ width?: number; height?: number }> {+ const meta = await sharp(Buffer.from(dataUrl.split(',')[1]!, 'base64')).metadata();+ return { width: meta.width, height: meta.height };+}++// thresholdBytes: 0 forces the decode path for every image regardless of+// size, keeping fixtures tiny; dimension behavior is what's under test.+const FORCE = { thresholdBytes: 0 };++describe('inbound image normalization', () => {+ it('downscales an oversized image to the long-edge cap and re-encodes to JPEG', async () => {+ const url = await solidPng(3000, 2000);+ const messages: ChatMessage[] = [{+ role: 'user',+ content: [+ { type: 'text', text: 'what is this?' },+ { type: 'image_url', image_url: { url, detail: 'high' } },+ ],+ } as any];++ const summary = await normalizeMessageImages(messages, FORCE);+ expect(summary.normalized).toBe(1);++ const block = (messages[0].content as any[])[1];+ expect(block.image_url.url.startsWith('data:image/jpeg;base64,')).toBe(true);+ // detail hint and the sibling text block survive untouched.+ expect(block.image_url.detail).toBe('high');+ expect((messages[0].content as any[])[0]).toEqual({ type: 'text', text: 'what is this?' });+ const d = await dims(block.image_url.url);+ expect(d.width).toBeLessThanOrEqual(2048);+ expect(d.height).toBeLessThanOrEqual(2048);+ });++ it('handles the shorthand string image_url form', async () => {+ const url = await solidPng(2600, 1300);+ const messages: ChatMessage[] = [{+ role: 'user',+ content: [{ type: 'image_url', image_url: url }],+ } as any];++ const summary = await normalizeMessageImages(messages, FORCE);+ expect(summary.normalized).toBe(1);+ const next = (messages[0].content as any[])[0].image_url;+ expect(typeof next).toBe('string');+ expect(next.startsWith('data:image/jpeg;base64,')).toBe(true);+ });++ it('keeps PNG when the alpha channel actually carries transparency', async () => {+ const url = await solidPng(3000, 2000, 0.5);+ const messages: ChatMessage[] = [{+ role: 'user',+ content: [{ type: 'image_url', image_url: { url } }],+ } as any];++ await normalizeMessageImages(messages, FORCE);+ const next = (messages[0].content as any[])[0].image_url.url;+ expect(next.startsWith('data:image/png;base64,')).toBe(true);+ const d = await dims(next);+ expect(d.width).toBeLessThanOrEqual(2048);+ });++ it('flattens opaque RGBA screenshots to JPEG (the macOS-screenshot shape)', async () => {+ // RGBA PNG, fully opaque, already under the dimension cap — exactly the+ // shape that used to stay on PNG and "compress" 2.0MB → 1.9MB.+ const url = await solidPng(1920, 1080, 1.0);+ const messages: ChatMessage[] = [{+ role: 'user',+ content: [{ type: 'image_url', image_url: { url } }],+ } as any];++ const summary = await normalizeMessageImages(messages, FORCE);+ expect(summary.normalized).toBe(1);+ const next = (messages[0].content as any[])[0].image_url.url;+ expect(next.startsWith('data:image/jpeg;base64,')).toBe(true);+ });++ it('re-encodes an over-threshold JPEG that is already under the dimension cap', async () => {+ // Noisy q100 JPEG at 400px: no resize needed, but a q90 re-encode wins.+ const url = await noiseJpeg(400, 300, 100);+ const messages: ChatMessage[] = [{+ role: 'user',+ content: [{ type: 'image_url', image_url: { url } }],+ } as any];++ const summary = await normalizeMessageImages(messages, FORCE);+ const next = (messages[0].content as any[])[0].image_url.url;+ expect(next.startsWith('data:image/jpeg;base64,')).toBe(true);+ if (summary.normalized === 1) {+ expect(summary.bytesAfter).toBeLessThan(summary.bytesBefore);+ } else {+ // The never-grow guard kept the original — it must be byte-identical.+ expect(next).toBe(url);+ }+ });++ it('leaves small compact JPEGs under the threshold untouched', async () => {+ const url = await smallJpeg();+ const messages: ChatMessage[] = [{+ role: 'user',+ content: [{ type: 'image_url', image_url: { url } }],+ } as any];++ const summary = await normalizeMessageImages(messages); // default 1MB threshold+ expect(summary.normalized).toBe(0);+ expect((messages[0].content as any[])[0].image_url.url).toBe(url);+ });++ it('converts webp and tiff inputs to JPEG (formats most upstreams reject)', async () => {+ const raw = Buffer.alloc(300 * 200 * 3);+ for (let i = 0; i < raw.length; i++) raw[i] = Math.floor(Math.random() * 256);+ const make = (encoder: (s: any) => any) => encoder(sharp(raw, { raw: { width: 300, height: 200, channels: 3 } })).toBuffer();+ const [webpBuf, tiffBuf] = await Promise.all([make(s => s.webp({ quality: 95 })), make(s => s.tiff({ quality: 95 }))]);++ for (const buf of [webpBuf, tiffBuf]) {+ const url = `data:image/${buf[0] === 0x52 ? 'webp' : 'tiff'};base64,${buf.toString('base64')}`;+ const messages: ChatMessage[] = [{+ role: 'user',+ content: [{ type: 'image_url', image_url: { url } }],+ } as any];+ const summary = await normalizeMessageImages(messages, FORCE);+ expect(summary.normalized).toBe(1);+ expect((messages[0].content as any[])[0].image_url.url.startsWith('data:image/jpeg;base64,')).toBe(true);+ }+ });++ it('clamps an out-of-range quality instead of failing', async () => {+ const url = await solidPng(1920, 1080, 1.0);+ const messages: ChatMessage[] = [{+ role: 'user',+ content: [{ type: 'image_url', image_url: { url } }],+ } as any];++ // 999 must not reach sharp as-is; the pipeline still produces a JPEG.+ const summary = await normalizeMessageImages(messages, { thresholdBytes: 0, quality: 999 });+ expect(summary.normalized).toBe(1);+ expect((messages[0].content as any[])[0].image_url.url.startsWith('data:image/jpeg;base64,')).toBe(true);+ });++ it('leaves http(s) URLs alone (providers fetch them themselves)', async () => {+ const messages: ChatMessage[] = [{+ role: 'user',+ content: [{ type: 'image_url', image_url: { url: 'https://example.com/x.png' } }],+ } as any];++ const summary = await normalizeMessageImages(messages, FORCE);+ expect(summary.normalized).toBe(0);+ expect((messages[0].content as any[])[0].image_url.url).toBe('https://example.com/x.png');+ });++ it('is a no-op when disabled', async () => {+ const url = await solidPng(3000, 2000);+ const messages: ChatMessage[] = [{+ role: 'user',+ content: [{ type: 'image_url', image_url: { url } }],+ } as any];++ const summary = await normalizeMessageImages(messages, { ...FORCE, enabled: false });+ expect(summary.normalized).toBe(0);+ expect((messages[0].content as any[])[0].image_url.url).toBe(url);+ });++ it('never throws on a corrupt image and keeps the original', async () => {+ const bad = 'data:image/png;base64,not-really-base64-image-bytes';+ const messages: ChatMessage[] = [+ { role: 'user', content: [{ type: 'image_url', image_url: { url: bad } }] } as any,+ { role: 'assistant', content: null, tool_calls: [{ id: 'c1', type: 'function', function: { name: 'f', arguments: '{}' } }] },+ ];++ const summary = await normalizeMessageImages(messages, FORCE);+ expect(summary.normalized).toBe(0);+ expect((messages[0].content as any[])[0].image_url.url).toBe(bad);+ // Non-image messages pass through byte-identical.+ expect(messages[1].tool_calls?.[0].id).toBe('c1');+ });++ it('respects IMAGE_NORMALIZE env knobs read lazily', async () => {+ process.env.IMAGE_NORMALIZE = 'off';+ try {+ const url = await solidPng(3000, 2000);+ const messages: ChatMessage[] = [{+ role: 'user',+ content: [{ type: 'image_url', image_url: { url } }],+ } as any];+ const summary = await normalizeMessageImages(messages); // no overrides: env wins+ expect(summary.normalized).toBe(0);+ } finally {+ delete process.env.IMAGE_NORMALIZE;+ }+ });+});diff --git a/server/src/__tests__/providers/google.test.ts b/server/src/__tests__/providers/google.test.tsindex 32ea5900..cdbc4308 100644--- a/server/src/__tests__/providers/google.test.ts+++ b/server/src/__tests__/providers/google.test.ts@@ -579,6 +579,51 @@ describe('GoogleProvider', () => {expect(assistantEntry.parts[0].functionCall.id).toBe('toolu_rewritten_by_bridge');});+ it('falls back to Google\'s documented dummy sentinel when no signature exists', async () => {+ // Signature-less replay — history this proxy never produced (another+ // provider, a restart, TTL expiry). Gemini 3 400s on a MISSING signature+ // and only accepts its two documented sentinel strings as a substitute;+ // a fabricated value (e.g. a hash) is not one of them.+ let capturedBody: any;+ vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => {+ capturedBody = JSON.parse((init as any).body);+ return {+ ok: true,+ json: () => Promise.resolve({+ candidates: [{+ content: { parts: [{ text: 'ok' }] },+ finishReason: 'STOP',+ }],+ usageMetadata: { promptTokenCount: 1, candidatesTokenCount: 1, totalTokenCount: 2 },+ }),+ } as any;+ });++ await provider.chatCompletion(+ 'test-key',+ [+ { role: 'user', content: 'Weather in Nairobi?' },+ {+ role: 'assistant',+ content: null,+ tool_calls: [{+ id: 'call_sentinel_fallback',+ type: 'function',+ // Unique name/args: nothing in the module-level signature cache+ // can match, so the fallback path is exercised for real.+ function: { name: 'get_weather_sentinel', arguments: '{"city":"Nairobi"}' },+ }],+ },+ { role: 'tool', tool_call_id: 'call_sentinel_fallback', content: '{"temp": 21}' },+ ],+ 'gemini-3-pro-preview',+ );++ const assistantEntry = capturedBody.contents.find((c: any) => c.role === 'model');+ expect(assistantEntry.parts[0].thoughtSignature).toBe('context_engineering_is_the_way_to_go');+ expect(assistantEntry.parts[0].functionCall.name).toBe('get_weather_sentinel');+ });+// ── Streaming ──────────────────────────────────────────────────────────────// Build a Response-shaped object backed by a ReadableStream so the provider's// `res.body.getReader()` path executes for real (Node 20+ has both globally).diff --git a/server/src/__tests__/routes/body-limit.test.ts b/server/src/__tests__/routes/body-limit.test.tsnew file mode 100644index 00000000..bf44011b--- /dev/null+++ b/server/src/__tests__/routes/body-limit.test.ts@@ -0,0 +1,98 @@+import { describe, it, expect, beforeAll } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { loadConfig } from '../../lib/config.js';+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';++async function post(app: Express, path: string, body: unknown, key: string) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },+ body: JSON.stringify(body),+ });+ const text = await res.text();+ server.close();+ let json: any = null;+ try { json = JSON.parse(text); } catch {}+ return { status: res.status, body: json };+}++// ~11.5MB base64 payload — the shape that used to die at the global 10mb+// express.json limit BEFORE routing (opaque 413, no fallback, no analytics+// row). Sized past 10MB on purpose: the regression only reproduces above it.+const BIG_IMAGE = `data:image/png;base64,${'A'.repeat(11_500_000)}`;++describe('Inference body limits (vision payloads)', () => {+ let app: Express;+ let key: string;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ key = getUnifiedApiKey();+ });++ it('accepts an >10mb vision payload on /v1/chat/completions (no parser 413)', async () => {+ // Seed has vision models enabled but no provider keys, so routing+ // exhausts → 429. The point: it is NOT the parser's 413, proving the+ // body reached routing and the fallback loop owns the failure from here.+ const { status } = await post(app, '/v1/chat/completions', {+ messages: [{+ role: 'user',+ content: [+ { type: 'text', text: 'what is in this image?' },+ { type: 'image_url', image_url: { url: BIG_IMAGE } },+ ],+ }],+ }, key);+ expect(status).not.toBe(413);+ }, 30_000);++ it('accepts an >10mb vision payload on /v1/responses too', async () => {+ const { status } = await post(app, '/v1/responses', {+ input: [{+ role: 'user',+ content: [+ { type: 'input_text', text: 'what is in this image?' },+ { type: 'input_image', image_url: BIG_IMAGE },+ ],+ }],+ }, key);+ expect(status).not.toBe(413);+ }, 30_000);+});++describe('Over-limit bodies (configurable ceiling)', () => {+ let app: Express;+ let key: string;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ // Tiny ceiling so the rejection path is testable without a 50MB body.+ app = createApp({ ...loadConfig(), requestBodyLimitBytes: 1024 });+ key = getUnifiedApiKey();+ });++ it('returns a normalized OpenAI-style 413 and logs it for the dashboard', async () => {+ const { status, body } = await post(app, '/v1/chat/completions', {+ messages: [{ role: 'user', content: 'x'.repeat(4096) }],+ }, key);+ expect(status).toBe(413);+ expect(body.error.type).toBe('invalid_request_error');+ expect(body.error.code).toBe('request_too_large');+ expect(body.error.message).toContain('REQUEST_BODY_LIMIT_MB');++ // The rejection is visible in request analytics like any failed request,+ // not only in the container log.+ const row = getDb().prepare(+ "SELECT platform, model_id, status, error FROM requests WHERE model_id = 'payload-too-large' ORDER BY id DESC LIMIT 1",+ ).get() as { platform: string; model_id: string; status: string; error: string } | undefined;+ expect(row?.platform).toBe('proxy');+ expect(row?.status).toBe('error');+ expect(row?.error).toContain('Request body too large');+ });+});diff --git a/server/src/__tests__/routes/responses-translate.test.ts b/server/src/__tests__/routes/responses-translate.test.tsindex aa1f5531..c19382c4 100644--- a/server/src/__tests__/routes/responses-translate.test.ts+++ b/server/src/__tests__/routes/responses-translate.test.ts@@ -4,8 +4,8 @@ import {toChatTools,toChatToolChoice,buildResponseObject,- responsesInputHasImage,responsesInputRequestsComputerUse,+ responsesInputHasFileIdImage,} from '../../routes/responses.js';describe('Responses → chat translation (#96)', () => {@@ -34,6 +34,65 @@ describe('Responses → chat translation (#96)', () => {]);});+ it('translates image parts into image_url content blocks (keeps all-text content a string)', () => {+ const msgs = toChatMessages({+ input: [+ { type: 'message', role: 'user', content: [+ { type: 'input_text', text: 'what is this?' },+ { type: 'input_image', image_url: 'data:image/png;base64,AA==' },+ ] },+ { type: 'message', role: 'user', content: 'plain text stays a string' },+ ],+ } as any);+ expect(msgs[0]).toEqual({+ role: 'user',+ content: [+ { type: 'text', text: 'what is this?' },+ { type: 'image_url', image_url: { url: 'data:image/png;base64,AA==' } },+ ],+ });+ expect(msgs[1]).toEqual({ role: 'user', content: 'plain text stays a string' });+ });++ it('accepts chat-style image_url and computer_screenshot parts', () => {+ const msgs = toChatMessages({+ input: [+ { type: 'message', role: 'user', content: [+ { type: 'image_url', image_url: { url: 'https://example.com/x.png' } },+ ] },+ ],+ } as any);+ expect(msgs[0]).toEqual({+ role: 'user',+ content: [{ type: 'image_url', image_url: { url: 'https://example.com/x.png' } }],+ });+ });++ it('preserves the Responses detail hint on image parts', () => {+ const msgs = toChatMessages({+ input: [+ { type: 'message', role: 'user', content: [+ { type: 'input_image', image_url: 'https://example.com/x.png', detail: 'high' },+ ] },+ ],+ } as any);+ expect(msgs[0]).toEqual({+ role: 'user',+ content: [{ type: 'image_url', image_url: { url: 'https://example.com/x.png', detail: 'high' } }],+ });+ });++ it('folds refusal parts into text so replayed assistant turns are not emptied', () => {+ const msgs = toChatMessages({+ input: [+ { type: 'message', role: 'assistant', content: [+ { type: 'refusal', refusal: 'I cannot help with that.' },+ ] },+ ],+ } as any);+ expect(msgs[0]).toEqual({ role: 'assistant', content: 'I cannot help with that.' });+ });+it('maps a function_call item to an assistant tool_call', () => {const msgs = toChatMessages({input: [{ type: 'function_call', call_id: 'call_1', name: 'get_weather', arguments: '{"city":"SF"}' }],@@ -174,10 +233,27 @@ describe('Responses → chat translation (#96)', () => {expect(responsesInputRequestsComputerUse({ input: 'plain text' } as any)).toBe(false);});- it('detects screenshots inside computer_call_output.output as image input', () => {- expect(responsesInputHasImage({- input: [{ type: 'computer_call_output', call_id: 'cc_1', output: [{ type: 'computer_screenshot', image_url: 'data:image/png;base64,AA==' }] }],+ it('flags unresolvable input_image parts (file_id-only, missing or empty url)', () => {+ expect(responsesInputHasFileIdImage({+ input: [{ type: 'message', role: 'user', content: [{ type: 'input_image', file_id: 'file_abc' }] }],+ } as any)).toBe(true);+ // No url at all — the lenient schema lets this through validation, so the+ // pre-check is the only thing standing between it and a blind answer.+ expect(responsesInputHasFileIdImage({+ input: [{ type: 'message', role: 'user', content: [{ type: 'input_image' }] }],+ } as any)).toBe(true);+ expect(responsesInputHasFileIdImage({+ input: [{ type: 'message', role: 'user', content: [{ type: 'input_image', image_url: '' }] }],} as any)).toBe(true);+ // A resolvable image_url alongside the file_id is fine.+ expect(responsesInputHasFileIdImage({+ input: [{ type: 'message', role: 'user', content: [{ type: 'input_image', file_id: 'file_abc', image_url: 'data:image/png;base64,AA==' }] }],+ } as any)).toBe(false);+ // Plain url images and string inputs never flag.+ expect(responsesInputHasFileIdImage({+ input: [{ type: 'message', role: 'user', content: [{ type: 'input_image', image_url: 'https://example.com/x.png' }] }],+ } as any)).toBe(false);+ expect(responsesInputHasFileIdImage({ input: 'plain text' } as any)).toBe(false);});it('converts flat Responses tools to nested chat tools', () => {diff --git a/server/src/__tests__/routes/responses.test.ts b/server/src/__tests__/routes/responses.test.tsindex 3c66651f..8c2a0c55 100644--- a/server/src/__tests__/routes/responses.test.ts+++ b/server/src/__tests__/routes/responses.test.ts@@ -50,9 +50,23 @@ describe('POST /v1/responses (#96)', () => {expect((await post(app, '/v1/responses', { model: 'auto' }, key)).status).toBe(400);});- // #118: image input isn't carried through the Responses translation yet, so- // it must hard-fail clearly rather than silently answer blind to the image.- it('rejects image input with a clear 422 pointing at /v1/chat/completions', async () => {+ // #118: image parts now translate to image_url content blocks, so an image+ // request must be routed with requireVision=true (only vision-capable models+ // are candidates; a text-only pinned model is skipped, falling back to a+ // vision-capable peer). The old unconditional 422 is gone.+ it('routes an image request through requireVision (vision-capable model)', async () => {+ mockRouteRequest.mockClear();+ mockRouteRequest.mockReturnValue(fakeRoute({+ async chatCompletion() {+ return {+ id: 'c', object: 'chat.completion', created: 0, model: 'fake-model',+ choices: [{ index: 0, message: { role: 'assistant', content: 'a red circle' }, finish_reason: 'stop' }],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+ };+ },+ async *streamChatCompletion() { /* unused */ },+ }));+const { status, text } = await post(app, '/v1/responses', {input: [{role: 'user',@@ -62,8 +76,65 @@ describe('POST /v1/responses (#96)', () => {],}],}, key);+ expect(status).toBe(200);+ expect(JSON.parse(text).output_text).toBe('a red circle');+ // routeRequest arg [3] is requireVision.+ expect(mockRouteRequest.mock.calls.at(-1)?.[3]).toBe(true);+ });++ it('rejects a file_id-only input_image with 422 before routing (no Files backend)', async () => {+ mockRouteRequest.mockClear();+ const { status, text } = await post(app, '/v1/responses', {+ input: [{+ role: 'user',+ content: [+ { type: 'input_text', text: 'what is this?' },+ { type: 'input_image', file_id: 'file_abc123' },+ ],+ }],+ }, key);expect(status).toBe(422);- expect(JSON.parse(text).error.code).toBe('no_vision_model');+ const body = JSON.parse(text);+ expect(body.error.code).toBe('unsupported_image_input');+ expect(body.error.type).toBe('invalid_request_error');+ expect(mockRouteRequest).not.toHaveBeenCalled();+ });++ it('rejects an input_image with no resolvable url instead of answering blind', async () => {+ mockRouteRequest.mockClear();+ // The lenient schema accepts this body; without the pre-check the image+ // part would translate to nothing and the request would route as plain+ // text — answering blind to an image the client believes was sent.+ const { status, text } = await post(app, '/v1/responses', {+ input: [{+ role: 'user',+ content: [+ { type: 'input_text', text: 'what is this?' },+ { type: 'input_image', detail: 'high' },+ ],+ }],+ }, key);+ expect(status).toBe(422);+ expect(JSON.parse(text).error.code).toBe('unsupported_image_input');+ expect(mockRouteRequest).not.toHaveBeenCalled();+ });++ it('rejects an image request with 422 no_vision_model when no vision model is enabled', async () => {+ mockRouteRequest.mockClear();+ getDb().prepare('UPDATE models SET enabled = 0 WHERE supports_vision = 1').run();+ try {+ const { status, text } = await post(app, '/v1/responses', {+ input: [{+ role: 'user',+ content: [{ type: 'input_image', image_url: 'data:image/png;base64,iVBORw0KGgo=' }],+ }],+ }, key);+ expect(status).toBe(422);+ expect(JSON.parse(text).error.code).toBe('no_vision_model');+ expect(mockRouteRequest).not.toHaveBeenCalled();+ } finally {+ getDb().prepare('UPDATE models SET enabled = 1 WHERE supports_vision = 1').run();+ }});// #103: the x-api-key header (Anthropic wire format) must authenticate herediff --git a/server/src/app.ts b/server/src/app.tsindex 7dcb7b2d..86d04216 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -171,9 +171,21 @@ export function createApp(config?: Config) {callback(null, !origin || allowedCorsOrigins.has(origin));},}));- // 10mb: code agents (OpenCode, AionUI, Qwen Code) ship very large system- // prompts + tool schemas + repo context; 1mb cut their sessions off- // mid-conversation with an opaque 413. (#200)+ // Two-tier JSON body limits. The LLM wire surfaces carry vision payloads —+ // base64 images inline in the body (~33% inflation; google.ts forwards+ // images up to 8MB apiece) — so a single-screenshot Codex turn can clear+ // 10MB and used to 413 HERE, before auth/routing: no fallback attempt, no+ // analytics row, just an opaque 'request entity too large'. Those surfaces+ // get the larger REQUEST_BODY_LIMIT_MB ceiling (default 25MB); everything+ // else keeps the #200 limit — code agents (OpenCode, AionUI, Qwen Code)+ // ship very large system prompts + tool schemas + repo context, and 1mb cut+ // their sessions off mid-conversation. body-parser skips requests whose+ // body was already parsed, so the second parser only sees what the first+ // didn't own; an over-limit body throws from whichever parser matched.+ app.use(+ ['/v1', '/v1beta', '/mcp', '/api/chat', '/api/generate', '/api/embed', '/api/embeddings'],+ express.json({ limit: cfg.requestBodyLimitBytes }),+ );app.use(express.json({ limit: '10mb' }));// Caller identity (IP + User-Agent) for request analytics, carried indiff --git a/server/src/lib/config.ts b/server/src/lib/config.tsindex fc3c59ed..d595b7df 100644--- a/server/src/lib/config.ts+++ b/server/src/lib/config.ts@@ -1,5 +1,24 @@const DEFAULT_RPM = 120;+// JSON body ceiling for the LLM wire surfaces (/v1, /v1beta, /mcp, Ollama+// /api/*). Vision requests inline base64 images (~33% inflation over the raw+// bytes; google.ts alone forwards images up to 8MB, ~10.7MB in base64), so a+// single-screenshot Codex turn easily clears 10MB, and history replay stacks+// several of them (an 11.85MB real-world request was observed). express.json+// buffers the whole body in memory (2-3x transiently during the parse), so+// this also bounds the per-request spike on small containers. Anything past+// the ceiling 413s before routing — no fallback, no analytics row — so it+// must sit above the largest payload we expect to serve. 25MB is the balance+// point: it clears the observed 11.85MB replayed session with room to spare,+// while keeping the worst case survivable on the small hosts this runs on (a+// Pi or a 512MB VPS — the limit is PER REQUEST, so a handful of concurrent+// maximal bodies is the number that actually has to fit in RAM). Inbound+// image normalization shrinks payloads ~6-10x right after the parse, so the+// steady state sits far below this. Raise REQUEST_BODY_LIMIT_MB on a bigger+// box if a client genuinely sends more. The dashboard/admin surface keeps its+// own smaller fixed ceiling.+const DEFAULT_REQUEST_BODY_LIMIT_MB = 25;+function parseRateLimitRpm(): number {const raw = process.env.PROXY_RATE_LIMIT_RPM;if (raw === undefined || raw.trim() === '') return DEFAULT_RPM;@@ -8,6 +27,14 @@ function parseRateLimitRpm(): number {return Math.floor(n);}+function parseRequestBodyLimitBytes(): number {+ const raw = process.env.REQUEST_BODY_LIMIT_MB;+ if (raw === undefined || raw.trim() === '') return DEFAULT_REQUEST_BODY_LIMIT_MB * 1024 * 1024;+ const n = Number(raw);+ if (!Number.isFinite(n) || n < 1) return DEFAULT_REQUEST_BODY_LIMIT_MB * 1024 * 1024;+ return Math.floor(n) * 1024 * 1024;+}+export interface Config {port: number | string;host: string;@@ -15,6 +42,9 @@ export interface Config {dashboardOrigins: string[];clientDist: string | null;proxyRateLimitRpm: number;+ /** JSON body limit (bytes) for the LLM wire surfaces — see+ * parseRequestBodyLimitBytes. REQUEST_BODY_LIMIT_MB overrides. */+ requestBodyLimitBytes: number;nodeEnv: string;serveStaticAssets: boolean;/**@@ -41,6 +71,7 @@ export function loadConfig(): Config {.filter(Boolean),clientDist: process.env.CLIENT_DIST ?? null,proxyRateLimitRpm: parseRateLimitRpm(),+ requestBodyLimitBytes: parseRequestBodyLimitBytes(),nodeEnv: process.env.NODE_ENV ?? 'development',serveStaticAssets: true,// CSP_UPGRADE_INSECURE_REQUESTS: true|false forces the directive on/off;diff --git a/server/src/lib/image-normalize.ts b/server/src/lib/image-normalize.tsnew file mode 100644index 00000000..0bdefb38--- /dev/null+++ b/server/src/lib/image-normalize.ts@@ -0,0 +1,259 @@+import type { ChatMessage } from '@freellmapi/shared/types.js';++// Inbound image normalization. Vision payloads ride inline as base64 data+// URLs, and agents replay their ENTIRE history every turn — one real Codex+// session accumulated 11.85MB of duplicated screenshots. Every upstream+// resizes internally anyway (OpenAI scales the long edge to 2048, Anthropic+// to 1568), so pixels beyond that cap are pure transport waste that still+// counts against payload limits (Gemini ~20MB/request, Anthropic 5MB/image)+// and our own buffering.+//+// Runs after body parsing on every chat-shaped surface (proxy, responses,+// anthropic, and the inbound-chat funnel behind Ollama/Gemini wire): data-URL+// images over the size threshold are decoded, downscaled to fit+// IMAGE_NORMALIZE_MAX_DIMENSION, and re-encoded — JPEG q<quality>, or PNG+// only when the alpha channel ACTUALLY carries transparency. Screenshots are+// the gotcha: macOS ships them as RGBA PNGs that are fully opaque, and+// honoring the bare hasAlpha flag kept them on PNG, "compressing" 2.0MB →+// 1.9MB. http(s) URLs are left alone — providers that need the bytes fetch+// them themselves (see google.ts). Failures anywhere in the pipeline keep the+// original image: a vision request must never be lost to a transcoding+// hiccup.+//+// Knobs (env):+// IMAGE_NORMALIZE off/false/0 disables entirely (default on)+// IMAGE_NORMALIZE_MAX_DIMENSION long-edge cap in px (default 2048)+// IMAGE_NORMALIZE_THRESHOLD_KB raw-bytes floor before touching an image+// (default 1024 — small images decode-free)+// IMAGE_NORMALIZE_QUALITY JPEG quality, 1-100 (default 90)+//+// Input formats: anything libvips decodes — jpeg, png, webp, gif (first+// frame only — animation is dropped), tiff (first page), bmp, svg (rasterized+// at native size), avif. Formats it can't decode (notably HEIC on standard+// builds) and any corrupt payload fall through untouched: the provider sees+// the original and decides.++const DEFAULT_MAX_DIMENSION = 2048;+const DEFAULT_THRESHOLD_KB = 1024;+const DEFAULT_QUALITY = 90;++// sharp is a NATIVE module: it ships a prebuilt libvips per platform+arch, and+// a static `import sharp from 'sharp'` makes a missing or mismatched binary an+// import-time crash — the whole gateway would fail to boot over an optional+// image optimization. The desktop build only runs electron-rebuild for+// better-sqlite3, and slim/musl containers routinely lack the matching+// prebuild, so load it on first use instead and degrade to pass-through when+// it isn't there: images ride through at original size, exactly as they did+// before this module existed.+type Sharp = typeof import('sharp').default;+let sharpModule: Sharp | null | undefined; // undefined = not yet attempted++async function loadSharp(): Promise<Sharp | null> {+ if (sharpModule !== undefined) return sharpModule;+ try {+ sharpModule = (await import('sharp')).default;+ } catch (err: any) {+ sharpModule = null;+ console.warn(+ '[ImageNormalize] sharp is unavailable, inbound images will not be resized ' ++ `(set IMAGE_NORMALIZE=off to silence this): ${err?.message ?? err}`,+ );+ }+ return sharpModule;+}++export interface ImageNormalizeOptions {+ enabled?: boolean;+ maxDimension?: number;+ thresholdBytes?: number;+ quality?: number;+}++interface ResolvedOptions {+ enabled: boolean;+ maxDimension: number;+ thresholdBytes: number;+ quality: number;+}++function envFlagOff(raw: string | undefined): boolean {+ if (!raw) return false;+ const lower = raw.trim().toLowerCase();+ return lower === 'off' || lower === 'false' || lower === '0' || lower === 'no';+}++function envNumber(raw: string | undefined, fallback: number, min: number): number {+ if (raw === undefined || raw.trim() === '') return fallback;+ const n = Number(raw);+ if (!Number.isFinite(n) || n < min) return fallback;+ return Math.floor(n);+}++// Read lazily (not at import) so tests can steer the knobs via process.env+// without module-reload gymnastics.+function resolveOptions(overrides?: ImageNormalizeOptions): ResolvedOptions {+ return {+ enabled: overrides?.enabled ?? !envFlagOff(process.env.IMAGE_NORMALIZE),+ maxDimension: overrides?.maxDimension+ ?? envNumber(process.env.IMAGE_NORMALIZE_MAX_DIMENSION, DEFAULT_MAX_DIMENSION, 16),+ thresholdBytes: overrides?.thresholdBytes+ ?? envNumber(process.env.IMAGE_NORMALIZE_THRESHOLD_KB, DEFAULT_THRESHOLD_KB, 0) * 1024,+ quality: Math.min(100, overrides?.quality+ ?? envNumber(process.env.IMAGE_NORMALIZE_QUALITY, DEFAULT_QUALITY, 1)),+ };+}++const DATA_URL_RE = /^data:([^;,]+)?(;base64)?,(.*)$/s;++interface ImageSlot {+ /** Rewrite the block in place with the new data URL. */+ set(url: string): void;+ url: string;+}++// Collect the mutable image slots of one message: OpenAI-style `image_url`+// blocks in both the shorthand (string) and object ({ url }) forms.+function imageSlots(message: ChatMessage): ImageSlot[] {+ if (!Array.isArray(message.content)) return [];+ const slots: ImageSlot[] = [];+ for (const block of message.content) {+ if (!block || typeof block !== 'object') continue;+ const b = block as { type?: string; image_url?: unknown };+ if (b.type !== 'image_url' && b.type !== 'image') continue;+ if (typeof b.image_url === 'string') {+ slots.push({ url: b.image_url, set: (url) => { (block as { image_url?: unknown }).image_url = url; } });+ } else if (b.image_url && typeof (b.image_url as { url?: unknown }).url === 'string') {+ const obj = b.image_url as { url: string };+ slots.push({ url: obj.url, set: (url) => { obj.url = url; } });+ }+ }+ return slots;+}++// Transcode one data URL; returns null when the image should ride along+// unchanged (under threshold, already compact, http URL, or any failure).+async function normalizeDataUrl(sharp: Sharp, url: string, opts: ResolvedOptions): Promise<{ url: string; before: number; after: number } | null> {+ const match = DATA_URL_RE.exec(url);+ if (!match) return null;+ const mime = (match[1] ?? '').toLowerCase();+ const isBase64 = Boolean(match[2]);+ const payload = match[3] ?? '';+ if (!isBase64 || !mime.startsWith('image/') || payload.length === 0) return null;++ const rawBytes = Math.floor(payload.length * 3 / 4);+ const alreadyCompact = mime === 'image/jpeg' || mime === 'image/webp';++ // Cheap pre-filter: under the threshold AND already a lossy format means+ // there is nothing to win — skip the decode entirely. Oversized-dimension+ // images under the threshold are rare enough (pixels ≈ bytes) that this+ // trade stays worth it.+ if (rawBytes < opts.thresholdBytes && alreadyCompact) return null;++ let buffer: Buffer;+ try {+ buffer = Buffer.from(payload, 'base64');+ } catch {+ return null;+ }++ try {+ const image = sharp(buffer);+ const meta = await image.metadata();+ const width = meta.width ?? 0;+ const height = meta.height ?? 0;+ const needsResize = width > opts.maxDimension || height > opts.maxDimension;+ // Small, right-sized, already-compact: nothing to win — skip the decode.+ if (!needsResize && alreadyCompact && rawBytes < opts.thresholdBytes) return null;+ // An over-threshold JPEG/WebP at the right size still gets re-encoded at+ // the target quality below (the never-grow guard keeps the original when+ // that can't win), so there is no early return for it.++ let pipeline = image;+ if (needsResize) {+ pipeline = pipeline.resize({+ width: opts.maxDimension,+ height: opts.maxDimension,+ fit: 'inside',+ withoutEnlargement: true,+ });+ }+ // Alpha is only worth keeping when it actually carries transparency.+ // Screenshots (the dominant vision payload here) are RGBA-but-fully-+ // opaque; honoring the bare hasAlpha flag kept them on PNG and squeezed+ // 2.0MB → 1.9MB instead of → ~300KB. stats() decodes, but we were about+ // to re-encode anyway.+ let keepAlpha = false;+ if (meta.hasAlpha) {+ try {+ keepAlpha = (await sharp(buffer).stats()).isOpaque === false;+ } catch {+ keepAlpha = true; // unknown opacity: stay lossless+ }+ }+ const out = keepAlpha+ ? { buffer: await pipeline.png().toBuffer(), mime: 'image/png' }+ : {+ buffer: await pipeline+ .flatten({ background: { r: 255, g: 255, b: 255 } })+ .jpeg({ quality: opts.quality })+ .toBuffer(),+ mime: 'image/jpeg',+ };++ // Never make it bigger (tiny paletted PNGs can lose to JPEG overhead).+ if (out.buffer.length >= buffer.length) return null;+ return {+ url: `data:${out.mime};base64,${out.buffer.toString('base64')}`,+ before: buffer.length,+ after: out.buffer.length,+ };+ } catch {+ // Corrupt/unsupported image: the provider gets the original and decides.+ return null;+ }+}++export interface ImageNormalizeSummary {+ messages: ChatMessage[];+ /** Number of images actually re-encoded. */+ normalized: number;+ bytesBefore: number;+ bytesAfter: number;+}++/**+ * Downscale + re-encode over-threshold inline images across a chat-message+ * list. Pure with respect to everything but the image blocks themselves+ * (text, tool calls, detail hints, block order all untouched). Never throws.+ */+export async function normalizeMessageImages(+ messages: ChatMessage[],+ overrides?: ImageNormalizeOptions,+): Promise<ImageNormalizeSummary> {+ const opts = resolveOptions(overrides);+ const summary: ImageNormalizeSummary = { messages, normalized: 0, bytesBefore: 0, bytesAfter: 0 };+ if (!opts.enabled) return summary;++ // No sharp (missing prebuild, unsupported platform): pass everything through+ // untouched rather than failing the request.+ const sharp = await loadSharp();+ if (!sharp) return summary;++ for (const message of messages) {+ for (const slot of imageSlots(message)) {+ if (!slot.url.startsWith('data:')) continue;+ const result = await normalizeDataUrl(sharp, slot.url, opts);+ if (!result) continue;+ slot.set(result.url);+ summary.normalized += 1;+ summary.bytesBefore += result.before;+ summary.bytesAfter += result.after;+ }+ }++ if (summary.normalized > 0) {+ const mb = (n: number) => (n / (1024 * 1024)).toFixed(1);+ console.log(`[ImageNormalize] re-encoded ${summary.normalized} image(s): ${mb(summary.bytesBefore)}MB → ${mb(summary.bytesAfter)}MB`);+ }+ return summary;+}diff --git a/server/src/lib/inbound-chat.ts b/server/src/lib/inbound-chat.tsindex 4e85dde1..50533940 100644--- a/server/src/lib/inbound-chat.ts+++ b/server/src/lib/inbound-chat.ts@@ -31,6 +31,7 @@ import {import { routedViaValue } from './header-value.js';import { applyTokenBudget, tokenBudgetMessage } from './guardrails.js';import { contentToString } from './content.js';+import { normalizeMessageImages } from './image-normalize.js';import { repairToolArguments, toolSchemaMap } from './tool-args.js';import { invalidToolArgumentsError, invalidToolCallReasons, isToolArgumentValidationEnabled } from './tool-validate.js';import {@@ -175,6 +176,10 @@ export async function runInboundChat(wire: InboundChatWire,): Promise<void> {const start = Date.now();+ // Downscale over-threshold inline images BEFORE estimation and routing so+ // token budgets, payload limits, and upstream transfers all see the shrunk+ // bytes (see lib/image-normalize.ts). Mutates the image blocks in place.+ await normalizeMessageImages(input.messages);const estimatedInputTokens = estimateTokens(input.messages);const budget = applyTokenBudget(estimatedInputTokens, input.maxTokens);if (budget.rejection) {diff --git a/server/src/lib/request-log.ts b/server/src/lib/request-log.tsindex e14af39c..74498d4c 100644--- a/server/src/lib/request-log.ts+++ b/server/src/lib/request-log.ts@@ -49,7 +49,9 @@ function setSettingIfMissing(db: LogTx, key: string, value: string): void {export function logRequest(platform: string,modelId: string,- keyId: number,+ // NULL for rejections that never reached routing (no key was involved),+ // e.g. an over-limit request body turned away at the parser.+ keyId: number | null,status: string,inputTokens: number,outputTokens: number,diff --git a/server/src/middleware/errorHandler.ts b/server/src/middleware/errorHandler.tsindex 567239a4..db023f95 100644--- a/server/src/middleware/errorHandler.ts+++ b/server/src/middleware/errorHandler.ts@@ -1,12 +1,43 @@import type { Request, Response, NextFunction } from 'express';+import { logRequest } from '../lib/request-log.js';-export function errorHandler(err: Error, _req: Request, res: Response, next: NextFunction) {+// The inference wire surfaces whose over-limit bodies deserve an analytics+// row — the dashboard renders them like any failed request instead of the+// rejection being visible only in the container log.+const INFERENCE_PATH_PREFIXES = ['/v1', '/v1beta', '/mcp'];++export function errorHandler(err: Error, req: Request, res: Response, next: NextFunction) {const isProduction = (process.env.NODE_ENV ?? 'development') === 'production';console.error('[Error]', isProduction ? err : err.message);if (res.headersSent) return next(err);const status = (err as any).status ?? 500;++ // body-parser rejects bodies over the configured limit with its own error+ // shape ('PayloadTooLargeError', type 'entity.too.large'). Agents reading+ // the OpenAI error contract saw an opaque 413; normalize it, and record the+ // rejection in request analytics so it shows up in the dashboard like the+ // upstream-413 path that the fallback loop already logs.+ if ((err as any).type === 'entity.too.large' || status === 413) {+ const limit = (err as any).limit;+ const received = (err as any).length ?? (err as any).expected;+ const message = `Request body too large${typeof received === 'number' ? ` (${received} bytes)` : ''}` ++ `${typeof limit === 'number' ? ` for the ${limit}-byte limit` : ''}. ` ++ 'Vision requests embed base64 images in the body; raise REQUEST_BODY_LIMIT_MB (default 25) to accept larger payloads.';+ if (INFERENCE_PATH_PREFIXES.some(prefix => req.path.startsWith(prefix))) {+ logRequest('proxy', 'payload-too-large', null, 'error', 0, 0, 0, message);+ }+ res.status(413).json({+ error: {+ message,+ type: 'invalid_request_error',+ code: 'request_too_large',+ },+ });+ return;+ }+const message = isProduction && status >= 500? 'Internal server error': err.message;diff --git a/server/src/providers/google.ts b/server/src/providers/google.tsindex 167b2e10..e2a62b8e 100644--- a/server/src/providers/google.ts+++ b/server/src/providers/google.ts@@ -46,6 +46,34 @@ function thoughtSigCallKey(name: string | undefined, args: unknown): string | unreturn `call:${name}:${canonicalThoughtSigArgs(args)}`;}+// Fallback for functionCall parts that have neither a client-preserved nor a+// cached signature (replayed history after a restart, TTL expiry, calls first+// produced by another provider). Gemini 3 strictly validates the field, but+// the signature is an encrypted blob the server checks — a fabricated value+// (e.g. a hash) is NOT accepted. Google documents exactly two sentinel+// strings for calls the API didn't produce; either tells the server to skip+// signature validation (at the cost of some reasoning quality), which is the+// official last resort for signature-less history.+const DUMMY_THOUGHT_SIGNATURE = 'context_engineering_is_the_way_to_go';++// The sentinel is a silent quality trade — Gemini stops validating and loses+// the reasoning thread for that call — so say so once per process. A steady+// stream of these means the cache is missing (restart loop, TTL too short, or+// history minted by another provider) rather than a one-off replay, and+// without a log there is nothing to correlate degraded tool-calling against.+let warnedDummyThoughtSig = false;++function noteDummyThoughtSignature(name: string | undefined): void {+ if (warnedDummyThoughtSig) return;+ warnedDummyThoughtSig = true;+ console.warn(+ `[Google] no thought_signature for a replayed tool call (${name ?? 'unknown'}); ` ++ 'falling back to the documented skip-validation sentinel — Gemini will not ' ++ 'validate the signature for these turns, at some reasoning-quality cost. ' ++ '(Logged once per process.)',+ );+}+function rememberThoughtSigKey(key: string | undefined, sig: string | undefined): void {if (!key || !sig) return;// Cheap eviction: when full, drop the oldest insertion (Map preserves order).@@ -390,7 +418,13 @@ async function toGeminiContents(messages: ChatMessage[]): Promise<{// Prefer a signature the client preserved; otherwise recover the one// we cached when this call was first produced (OpenAI-format clients// drop the field, so this is the common path for Gemini multi-turn).- const sig = call.thought_signature ?? recallThoughtSig(call.id, call.function.name, call.function.arguments);+ // If neither is available, fall back to Google's documented dummy+ // sentinel so a signature-less replay still passes the strict 400+ // check (parallel calls get it on every part — harmless, since the+ // sentinel means "skip validation").+ const known = call.thought_signature ?? recallThoughtSig(call.id, call.function.name, call.function.arguments);+ if (!known) noteDummyThoughtSignature(call.function.name);+ const sig = known ?? DUMMY_THOUGHT_SIGNATURE;parts.push({thoughtSignature: sig,functionCall: {diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.tsindex 39cf9677..e3c0df99 100644--- a/server/src/routes/anthropic.ts+++ b/server/src/routes/anthropic.ts@@ -27,6 +27,7 @@ import { resolveAnthropicModel } from '../services/anthropic-map.js';import type { ReasoningEffort } from '../lib/sampling-params.js';import { buildModelListing } from '../services/model-listing.js';import { compressRequest, formatCompressionHeader } from '../services/compression/pipeline.js';+import { normalizeMessageImages } from '../lib/image-normalize.js';// Anthropic-compatible Messages API (`POST /v1/messages`). This is a thin// translation layer over the SAME router/fallback/analytics machinery the@@ -472,6 +473,12 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {}let { messages } = converted;const { tools, tool_choice, hasImage, wantsTools } = converted;+ // Downscale over-threshold inline images before compression/estimation so+ // the budget, routing, and upstream transfer all see the shrunk bytes+ // (see lib/image-normalize.ts). The cache-control detection below reads the+ // RAW wire body, and normalization mutates urls in place keeping the blocks+ // (and any cache_control on them) intact — neither is disturbed.+ await normalizeMessageImages(messages);const systemHasCacheControl = Array.isArray(body.system)&& body.system.some(block => block && typeof block === 'object' && 'cache_control' in block);const messageHasCacheControl = body.messages.some(message =>diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex ea45b610..da511ee2 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -11,6 +11,7 @@ import multer from 'multer';import { getDb } from '../db/index.js';import { resolveAuth, prependSystemPrompt, type ResolvedAuth } from '../lib/system-prompt.js';import { contentToString, messageHasImage, normalizeOutboundContent, sanitizeResponse } from '../lib/content.js';+import { normalizeMessageImages } from '../lib/image-normalize.js';import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';import { invalidToolArgumentsError, invalidToolCallReasons, isToolArgumentValidationEnabled } from '../lib/tool-validate.js';import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';@@ -1388,6 +1389,11 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {// the unified key and for profiles without a prompt.messages = prependSystemPrompt(messages, auth.systemPrompt);+ // Downscale over-threshold inline images before estimation/routing so the+ // token budget, payload limits, and upstream transfer all see the shrunk+ // bytes (see lib/image-normalize.ts). Mutates the image blocks in place.+ await normalizeMessageImages(messages);+// Token estimation is intentionally a heuristic (~4 chars per token). Used// for routing decisions (skip a model whose budget is too small) and for// streaming bookkeeping where the provider doesn't echo a final usage count.diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.tsindex 83c18b43..a6e30fe5 100644--- a/server/src/routes/responses.ts+++ b/server/src/routes/responses.ts@@ -9,11 +9,12 @@ import type {ChatToolChoice,Platform,} from '@freellmapi/shared/types.js';-import { routeRequest, hasEnabledToolsModel, resolveStickyPreference, routingReserveTokens, resolveModelGroupCandidates, type RouteResult, type ChainRow } from '../services/router.js';+import { routeRequest, hasEnabledVisionModel, hasEnabledToolsModel, resolveStickyPreference, routingReserveTokens, resolveModelGroupCandidates, type RouteResult, type ChainRow } from '../services/router.js';import { getDb } from '../db/index.js';import { resolveAuth, prependSystemPrompt } from '../lib/system-prompt.js';import { isUnifyEnabled, getModelGroups, resolveRequestedIdForDispatch } from '../services/model-groups.js';-import { contentToString } from '../lib/content.js';+import { contentToString, messageHasImage } from '../lib/content.js';+import { normalizeMessageImages } from '../lib/image-normalize.js';import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';import { invalidToolArgumentsError, invalidToolCallReasons, isToolArgumentValidationEnabled } from '../lib/tool-validate.js';import { rescueInlineToolCalls, startsWithDialectMarker, couldBecomeDialectMarker, containsDialectMarker } from '../lib/tool-call-rescue.js';@@ -219,27 +220,80 @@ function partsToString(content: string | Array<{ type: string; text?: unknown }>.join('');}-// Image input via the Responses API isn't carried through translation yet-// (partsToString flattens to text). Detect it so we can hard-fail with a clear-// pointer to /v1/chat/completions rather than silently dropping the image-// (#118, #125). Recognizes the Responses `input_image` part plus the-// chat-style `image_url` / `image` parts some clients reuse here.-export function responsesInputHasImage(req: ResponsesRequest): boolean {+// Responses content parts → internal chat content. Text parts map to text+// blocks, image parts (Responses `input_image`, chat-style `image_url`/`image`,+// and computer-use `computer_screenshot`) map to `image_url` blocks so vision+// routing and the provider adapters see them (parity with /chat/completions).+// `refusal` parts (assistant history replay) fold into text so the turn isn't+// silently emptied. All-text content collapses back to a plain string (the+// shape upstream chat providers and compression expect); an array comes back+// only once a message actually carries an image.+function partsToChatContent(content: string | Array<{ type: string; [k: string]: unknown }>): string | Array<{ type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string; detail?: string } }> {+ if (typeof content === 'string') return content;+ const blocks: Array<{ type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string; detail?: string } }> = [];+ for (const p of content) {+ const type = p.type;+ const text = p.text;+ if (type === 'text' || type === 'input_text' || type === 'output_text' || type === 'summary_text' || (type === undefined && typeof text === 'string')) {+ if (typeof text === 'string') blocks.push({ type: 'text', text });+ continue;+ }+ if (type === 'refusal') {+ // The model's refusal text on a replayed assistant turn; chat providers+ // have no refusal concept, so carry it as ordinary text.+ const refusal = (p as { refusal?: unknown }).refusal;+ if (typeof refusal === 'string') blocks.push({ type: 'text', text: refusal });+ continue;+ }+ if (type === 'input_image' || type === 'computer_screenshot' || type === 'image_url' || type === 'image') {+ // The image lives under `image_url`, as a bare data URL string+ // (Responses `input_image` / `computer_screenshot`) or as+ // `{ url }` (chat-style `image_url`). The Responses `detail` hint+ // (low/high/auto/original) rides along; adapters without an equivalent+ // (Gemini inlineData) ignore it. Unresolvable shapes (missing/empty+ // url, file_id-only) are rejected up front by the route's pre-check,+ // so dropping here never answers blind.+ const url = extractPartImageUrl(p);+ if (url) {+ const detail = (p as { detail?: unknown }).detail;+ blocks.push({ type: 'image_url', image_url: { url, ...(typeof detail === 'string' ? { detail } : {}) } });+ }+ continue;+ }+ }+ if (blocks.every((b) => b.type === 'text')) {+ return blocks.map((b) => (b as { type: 'text'; text: string }).text).join('');+ }+ return blocks;+}++// Shared url extraction so the translation and the pre-check below always+// agree on what counts as a resolvable image.+function extractPartImageUrl(p: { [k: string]: unknown }): string | undefined {+ const raw = p.image_url;+ const url = typeof raw === 'string' ? raw : (raw as { url?: unknown } | undefined)?.url;+ return typeof url === 'string' && url.length > 0 ? url : undefined;+}++// Responses `input_image` references an image by `image_url` OR a Files API+// `file_id`. This proxy has no OpenAI Files backend, and the schema is+// deliberately lenient, so an image part with no resolvable url (file_id-only,+// or no url at all) can't survive translation — reject up front instead of+// silently dropping it and answering blind to an image the client believes+// was sent. (`computer_screenshot` shares these forms but is intentionally+// not checked: computer use is rejected wholesale up front, today and until+// it's a supported feature.)+export function responsesInputHasFileIdImage(req: ResponsesRequest): boolean {if (typeof req.input === 'string') return false;- for (const item of req.input) {+ return req.input.some((item) => {const content = (item as { content?: unknown }).content;- if (Array.isArray(content) && content.some((p) => {- const type = (p as { type?: string })?.type;- return type === 'input_image' || type === 'image_url' || type === 'image';- })) return true;- // computer_call_output carries screenshots under `output`, not `content`.- const output = (item as { output?: unknown }).output;- if (Array.isArray(output) && output.some((p) => {- const type = (p as { type?: string })?.type;- return type === 'input_image' || type === 'computer_screenshot' || type === 'image_url';- })) return true;- }- return false;+ if (!Array.isArray(content)) return false;+ return content.some((p) => {+ const part = p as { type?: string; [k: string]: unknown };+ if (part.type !== 'input_image') return false;+ return extractPartImageUrl(part) === undefined;+ });+ });}// Computer use (the Responses `computer` / `computer_use_preview` tool + its@@ -317,7 +371,7 @@ export function toChatMessages(req: ResponsesRequest): ChatMessage[] {const m = item as z.infer<typeof messageItemSchema>;// 'developer' is the Responses-era system role.const role = m.role === 'developer' ? 'system' : m.role;- const content = partsToString(m.content);+ const content = partsToChatContent(m.content);if (role === 'system') {// Hoist system/developer messages to the start of the conversation:@@ -480,28 +534,29 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {const reqData = parsed.data;- // Vision isn't carried through the Responses translation yet — fail clearly- // instead of answering blind to a dropped image (#118, #125).- if (responsesInputHasImage(reqData)) {+ // Computer use can't survive the chat-completions translation either (no+ // computer tool, no screenshot context). Fail clearly instead of silently+ // dropping the calls and breaking Codex's computer-use tool loop.+ if (responsesInputRequestsComputerUse(reqData)) {res.status(422).json({error: {- message: 'Image input is not yet supported on /v1/responses. Use /v1/chat/completions with an image_url content part instead.',+ message: 'Computer use is not yet supported on /v1/responses (the computer / computer_use_preview tool and computer_call items have no chat-completions equivalent).',type: 'invalid_request_error',- code: 'no_vision_model',+ code: 'no_computer_use_model',},});return;}- // Computer use can't survive the chat-completions translation either (no- // computer tool, no screenshot context). Fail clearly instead of silently- // dropping the calls and breaking Codex's computer-use tool loop.- if (responsesInputRequestsComputerUse(reqData)) {+ // Unresolvable image parts (file_id-only, or no usable url) can't survive+ // translation — fail clearly rather than dropping the image and answering+ // blind.+ if (responsesInputHasFileIdImage(reqData)) {res.status(422).json({error: {- message: 'Computer use is not yet supported on /v1/responses (the computer / computer_use_preview tool and computer_call items have no chat-completions equivalent).',+ message: "This request contains an image part that can't be resolved: input_image needs an image_url (an https URL or a base64 data URL); Files API file_id references aren't supported by this proxy.",type: 'invalid_request_error',- code: 'no_computer_use_model',+ code: 'unsupported_image_input',},});return;@@ -553,18 +608,44 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {// (`instructions` / system input items) follow it and cannot override it.messages = prependSystemPrompt(messages, auth.systemPrompt);+ // Downscale over-threshold inline images before estimation/routing so the+ // token budget, payload limits, and upstream transfer all see the shrunk+ // bytes (see lib/image-normalize.ts). Mutates the image blocks in place.+ await normalizeMessageImages(messages);+const estimatedInputTokens = messages.reduce((sum, m) => sum + Math.ceil(contentToString(m.content).length / 4),0,);++ // Image requests must route to a vision-capable model (mirrors+ // /chat/completions, proxy.ts). Reject up front with a clear message when+ // none is enabled; when vision models are available, requireVision routing+ // skips text-only models — including a pinned/sticky one — and falls back to+ // a vision-capable peer (#118, #125). A rough per-image token cost keeps+ // budget routing from being skewed by content the text heuristic can't see.+ const hasImage = messageHasImage(messages);+ if (hasImage && !hasEnabledVisionModel()) {+ res.status(422).json({+ error: {+ message: 'This request includes an image, but no vision-capable model is enabled. Enable a vision model (e.g. Gemini 2.5 Flash, Llama 4 Scout) in the Fallback Chain.',+ type: 'invalid_request_error',+ code: 'no_vision_model',+ },+ });+ return;+ }+ const IMAGE_TOKEN_ESTIMATE = 1000;+ const imageCount = messages.reduce((n, m) =>+ n + (Array.isArray(m.content) ? m.content.filter(b => (b as { type?: string })?.type === 'image_url' || (b as { type?: string })?.type === 'image').length : 0), 0);// Capped output reserve so a large max_output_tokens can't falsely exclude the// model pool (#470); input counts in full.- const estimatedTotal = estimatedInputTokens + routingReserveTokens(reqData.max_output_tokens);+ const estimatedTotal = estimatedInputTokens + imageCount * IMAGE_TOKEN_ESTIMATE + routingReserveTokens(reqData.max_output_tokens);// Guardrail: per-request token budget (request_max_tokens_budget, default// off). A request with no max_output_tokens gets its output capped to the// budget remainder instead of a rejection.- const budgetCheck = applyTokenBudget(estimatedInputTokens, completionOpts.max_tokens);+ const budgetCheck = applyTokenBudget(estimatedInputTokens + imageCount * IMAGE_TOKEN_ESTIMATE, completionOpts.max_tokens);if (budgetCheck.rejection) {res.status(413).json({error: { message: tokenBudgetMessage(budgetCheck.rejection), type: 'invalid_request_error', code: 'request_token_budget' },@@ -681,7 +762,7 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {state,attemptLog,clientGone: () => clientGone,- route: () => routeRequest(estimatedTotal, state.skipKeys.size > 0 ? state.skipKeys : undefined, preferredModel, false, wantsTools, state.skipModels.size > 0 ? state.skipModels : undefined, groupChain, completionOpts.response_format !== undefined, state.skipPlatforms.size > 0 ? state.skipPlatforms : undefined),+ route: () => routeRequest(estimatedTotal, state.skipKeys.size > 0 ? state.skipKeys : undefined, preferredModel, hasImage, wantsTools, state.skipModels.size > 0 ? state.skipModels : undefined, groupChain, completionOpts.response_format !== undefined, state.skipPlatforms.size > 0 ? state.skipPlatforms : undefined),dispatch: async (route, attempt) => {traceRouteEvent('Responses', {event: attempt === 0 ? 'start' : 'next',