Compare commits

...

2 Commits

Author SHA1 Message Date
jacob314
68e33a1103 fix(test): regenerate settings documentation and schema 2026-04-23 14:34:43 -07:00
jacob314
19601955fd feat(routing): availability-aware auto-routing with best-effort pro
Adds settings and logic to detect slow/hanging Pro model requests, marking them as temporarily unavailable and automatically triggering a fallback to Flash. Introduces a proTimeoutMinutes and bestEffortPro strategy configuration.
2026-04-23 13:50:24 -07:00
18 changed files with 324 additions and 51 deletions

View File

@ -99,13 +99,16 @@ they appear in the UI.
### Model ### Model
| UI Label | Setting | Description | Default | | UI Label | Setting | Description | Default |
| ----------------------------- | ---------------------------- | -------------------------------------------------------------------------------------- | ----------- | | --------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ----------- |
| Model | `model.name` | The Gemini model to use for conversations. | `undefined` | | Model | `model.name` | The Gemini model to use for conversations. | `undefined` |
| Max Session Turns | `model.maxSessionTurns` | Maximum number of user/model/tool turns to keep in a session. -1 means unlimited. | `-1` | | Max Session Turns | `model.maxSessionTurns` | Maximum number of user/model/tool turns to keep in a session. -1 means unlimited. | `-1` |
| Context Compression Threshold | `model.compressionThreshold` | The fraction of context usage at which to trigger context compression (e.g. 0.2, 0.3). | `0.5` | | Context Compression Threshold | `model.compressionThreshold` | The fraction of context usage at which to trigger context compression (e.g. 0.2, 0.3). | `0.5` |
| Disable Loop Detection | `model.disableLoopDetection` | Disable automatic detection and prevention of infinite loops. | `false` | | Disable Loop Detection | `model.disableLoopDetection` | Disable automatic detection and prevention of infinite loops. | `false` |
| Skip Next Speaker Check | `model.skipNextSpeakerCheck` | Skip the next speaker check. | `true` | | Skip Next Speaker Check | `model.skipNextSpeakerCheck` | Skip the next speaker check. | `true` |
| Best Effort Pro | `model.autoRouting.bestEffortPro` | Always prefer the Pro model unless it is unavailable (e.g., due to timeouts or quota), ignoring other routing hints. | `false` |
| Pro Timeout (Minutes) | `model.autoRouting.proTimeoutMinutes` | If a Pro request takes longer than this many minutes, it will be marked as temporarily unavailable and fallback to Flash. | `5` |
| Pro Timeout Fallback Duration (Minutes) | `model.autoRouting.proTimeoutFallbackDurationMinutes` | How long to route to Flash after Pro times out. | `60` |
### Agents ### Agents

View File

@ -483,6 +483,20 @@ their corresponding top-level category object in your `settings.json` file.
- **Description:** Skip the next speaker check. - **Description:** Skip the next speaker check.
- **Default:** `true` - **Default:** `true`
- **`model.autoRouting.bestEffortPro`** (boolean):
- **Description:** Always prefer the Pro model unless it is unavailable (e.g.,
due to timeouts or quota), ignoring other routing hints.
- **Default:** `false`
- **`model.autoRouting.proTimeoutMinutes`** (number):
- **Description:** If a Pro request takes longer than this many minutes, it
will be marked as temporarily unavailable and fallback to Flash.
- **Default:** `5`
- **`model.autoRouting.proTimeoutFallbackDurationMinutes`** (number):
- **Description:** How long to route to Flash after Pro times out.
- **Default:** `60`
#### `modelConfigs` #### `modelConfigs`
- **`modelConfigs.aliases`** (object): - **`modelConfigs.aliases`** (object):

35
package-lock.json generated
View File

@ -449,8 +449,7 @@
"version": "2.11.0", "version": "2.11.0",
"resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.11.0.tgz", "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.11.0.tgz",
"integrity": "sha512-sBXGT13cpmPR5BMgHE6UEEfEaShh5Ror6rfN3yEK5si7QVrtZg8LEPQb0VVhiLRUslD2yLnXtnRzG035J/mZXQ==", "integrity": "sha512-sBXGT13cpmPR5BMgHE6UEEfEaShh5Ror6rfN3yEK5si7QVrtZg8LEPQb0VVhiLRUslD2yLnXtnRzG035J/mZXQ==",
"license": "(Apache-2.0 AND BSD-3-Clause)", "license": "(Apache-2.0 AND BSD-3-Clause)"
"peer": true
}, },
"node_modules/@bundled-es-modules/cookie": { "node_modules/@bundled-es-modules/cookie": {
"version": "2.0.1", "version": "2.0.1",
@ -1474,7 +1473,6 @@
"resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.13.4.tgz", "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.13.4.tgz",
"integrity": "sha512-GsFaMXCkMqkKIvwCQjCrwH+GHbPKBjhwo/8ZuUkWHqbI73Kky9I+pQltrlT0+MWpedCoosda53lgjYfyEPgxBg==", "integrity": "sha512-GsFaMXCkMqkKIvwCQjCrwH+GHbPKBjhwo/8ZuUkWHqbI73Kky9I+pQltrlT0+MWpedCoosda53lgjYfyEPgxBg==",
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"dependencies": { "dependencies": {
"@grpc/proto-loader": "^0.7.13", "@grpc/proto-loader": "^0.7.13",
"@js-sdsl/ordered-map": "^4.4.2" "@js-sdsl/ordered-map": "^4.4.2"
@ -2152,7 +2150,6 @@
"integrity": "sha512-t54CUOsFMappY1Jbzb7fetWeO0n6K0k/4+/ZpkS+3Joz8I4VcvY9OiEBFRYISqaI2fq5sCiPtAjRDOzVYG8m+Q==", "integrity": "sha512-t54CUOsFMappY1Jbzb7fetWeO0n6K0k/4+/ZpkS+3Joz8I4VcvY9OiEBFRYISqaI2fq5sCiPtAjRDOzVYG8m+Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@octokit/auth-token": "^6.0.0", "@octokit/auth-token": "^6.0.0",
"@octokit/graphql": "^9.0.2", "@octokit/graphql": "^9.0.2",
@ -2333,7 +2330,6 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",
"integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==", "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"engines": { "engines": {
"node": ">=8.0.0" "node": ">=8.0.0"
} }
@ -2383,7 +2379,6 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.5.0.tgz", "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.5.0.tgz",
"integrity": "sha512-ka4H8OM6+DlUhSAZpONu0cPBtPPTQKxbxVzC4CzVx5+K4JnroJVBtDzLAMx4/3CDTJXRvVFhpFjtl4SaiTNoyQ==", "integrity": "sha512-ka4H8OM6+DlUhSAZpONu0cPBtPPTQKxbxVzC4CzVx5+K4JnroJVBtDzLAMx4/3CDTJXRvVFhpFjtl4SaiTNoyQ==",
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"dependencies": { "dependencies": {
"@opentelemetry/semantic-conventions": "^1.29.0" "@opentelemetry/semantic-conventions": "^1.29.0"
}, },
@ -2758,7 +2753,6 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.5.0.tgz", "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.5.0.tgz",
"integrity": "sha512-F8W52ApePshpoSrfsSk1H2yJn9aKjCrbpQF1M9Qii0GHzbfVeFUB+rc3X4aggyZD8x9Gu3Slua+s6krmq6Dt8g==", "integrity": "sha512-F8W52ApePshpoSrfsSk1H2yJn9aKjCrbpQF1M9Qii0GHzbfVeFUB+rc3X4aggyZD8x9Gu3Slua+s6krmq6Dt8g==",
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"dependencies": { "dependencies": {
"@opentelemetry/core": "2.5.0", "@opentelemetry/core": "2.5.0",
"@opentelemetry/semantic-conventions": "^1.29.0" "@opentelemetry/semantic-conventions": "^1.29.0"
@ -2792,7 +2786,6 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-2.5.0.tgz", "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-2.5.0.tgz",
"integrity": "sha512-BeJLtU+f5Gf905cJX9vXFQorAr6TAfK3SPvTFqP+scfIpDQEJfRaGJWta7sJgP+m4dNtBf9y3yvBKVAZZtJQVA==", "integrity": "sha512-BeJLtU+f5Gf905cJX9vXFQorAr6TAfK3SPvTFqP+scfIpDQEJfRaGJWta7sJgP+m4dNtBf9y3yvBKVAZZtJQVA==",
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"dependencies": { "dependencies": {
"@opentelemetry/core": "2.5.0", "@opentelemetry/core": "2.5.0",
"@opentelemetry/resources": "2.5.0" "@opentelemetry/resources": "2.5.0"
@ -2847,7 +2840,6 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.5.0.tgz", "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.5.0.tgz",
"integrity": "sha512-VzRf8LzotASEyNDUxTdaJ9IRJ1/h692WyArDBInf5puLCjxbICD6XkHgpuudis56EndyS7LYFmtTMny6UABNdQ==", "integrity": "sha512-VzRf8LzotASEyNDUxTdaJ9IRJ1/h692WyArDBInf5puLCjxbICD6XkHgpuudis56EndyS7LYFmtTMny6UABNdQ==",
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"dependencies": { "dependencies": {
"@opentelemetry/core": "2.5.0", "@opentelemetry/core": "2.5.0",
"@opentelemetry/resources": "2.5.0", "@opentelemetry/resources": "2.5.0",
@ -4054,7 +4046,6 @@
"integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==", "integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
"devOptional": true, "devOptional": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"csstype": "^3.0.2" "csstype": "^3.0.2"
} }
@ -4328,7 +4319,6 @@
"integrity": "sha512-/Zb/xaIDfxeJnvishjGdcR4jmr7S+bda8PKNhRGdljDM+elXhlvN0FyPSsMnLmJUrVG9aPO6dof80wjMawsASg==", "integrity": "sha512-/Zb/xaIDfxeJnvishjGdcR4jmr7S+bda8PKNhRGdljDM+elXhlvN0FyPSsMnLmJUrVG9aPO6dof80wjMawsASg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "8.58.2", "@typescript-eslint/scope-manager": "8.58.2",
"@typescript-eslint/types": "8.58.2", "@typescript-eslint/types": "8.58.2",
@ -5073,7 +5063,6 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"acorn": "bin/acorn" "acorn": "bin/acorn"
}, },
@ -7151,8 +7140,7 @@
"version": "0.0.1581282", "version": "0.0.1581282",
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1581282.tgz", "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1581282.tgz",
"integrity": "sha512-nv7iKtNZQshSW2hKzYNr46nM/Cfh5SEvE2oV0/SEGgc9XupIY5ggf84Cz8eJIkBce7S3bmTAauFD6aysMpnqsQ==", "integrity": "sha512-nv7iKtNZQshSW2hKzYNr46nM/Cfh5SEvE2oV0/SEGgc9XupIY5ggf84Cz8eJIkBce7S3bmTAauFD6aysMpnqsQ==",
"license": "BSD-3-Clause", "license": "BSD-3-Clause"
"peer": true
}, },
"node_modules/dezalgo": { "node_modules/dezalgo": {
"version": "1.0.4", "version": "1.0.4",
@ -7737,7 +7725,6 @@
"integrity": "sha512-GsGizj2Y1rCWDu6XoEekL3RLilp0voSePurjZIkxL3wlm5o5EC9VpgaP7lrCvjnkuLvzFBQWB3vWB3K5KQTveQ==", "integrity": "sha512-GsGizj2Y1rCWDu6XoEekL3RLilp0voSePurjZIkxL3wlm5o5EC9VpgaP7lrCvjnkuLvzFBQWB3vWB3K5KQTveQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.12.1", "@eslint-community/regexpp": "^4.12.1",
@ -8255,7 +8242,6 @@
"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"accepts": "^2.0.0", "accepts": "^2.0.0",
"body-parser": "^2.2.1", "body-parser": "^2.2.1",
@ -9522,7 +9508,6 @@
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.12.tgz", "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.12.tgz",
"integrity": "sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q==", "integrity": "sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q==",
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=16.9.0" "node": ">=16.9.0"
} }
@ -9782,7 +9767,6 @@
"resolved": "https://registry.npmjs.org/@jrichman/ink/-/ink-6.6.9.tgz", "resolved": "https://registry.npmjs.org/@jrichman/ink/-/ink-6.6.9.tgz",
"integrity": "sha512-RL9sSiLQZECnjbmBwjIHOp8yVGdWF7C/uifg7ISv/e+F3nLNsfl7FdUFQs8iZARFMJAYxMFpxW6OW+HSt9drwQ==", "integrity": "sha512-RL9sSiLQZECnjbmBwjIHOp8yVGdWF7C/uifg7ISv/e+F3nLNsfl7FdUFQs8iZARFMJAYxMFpxW6OW+HSt9drwQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"ansi-escapes": "^7.0.0", "ansi-escapes": "^7.0.0",
"ansi-styles": "^6.2.3", "ansi-styles": "^6.2.3",
@ -13496,7 +13480,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz",
"integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
} }
@ -13507,7 +13490,6 @@
"integrity": "sha512-ePrwPfxAnB+7hgnEr8vpKxL9cmnp7F322t8oqcPshbIQQhDKgFDW4tjhF2wjVbdXF9O/nyuy3sQWd9JGpiLPvA==", "integrity": "sha512-ePrwPfxAnB+7hgnEr8vpKxL9cmnp7F322t8oqcPshbIQQhDKgFDW4tjhF2wjVbdXF9O/nyuy3sQWd9JGpiLPvA==",
"devOptional": true, "devOptional": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"shell-quote": "^1.6.1", "shell-quote": "^1.6.1",
"ws": "^7" "ws": "^7"
@ -15627,7 +15609,6 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },
@ -15850,8 +15831,7 @@
"version": "2.8.1", "version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD", "license": "0BSD"
"peer": true
}, },
"node_modules/tsx": { "node_modules/tsx": {
"version": "4.20.3", "version": "4.20.3",
@ -15859,7 +15839,6 @@
"integrity": "sha512-qjbnuR9Tr+FJOMBqJCW5ehvIo/buZq7vH7qD7JziU98h6l3qGy0a/yPFjwO+y0/T7GFpNgNAvEcPPVfyT8rrPQ==", "integrity": "sha512-qjbnuR9Tr+FJOMBqJCW5ehvIo/buZq7vH7qD7JziU98h6l3qGy0a/yPFjwO+y0/T7GFpNgNAvEcPPVfyT8rrPQ==",
"devOptional": true, "devOptional": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"esbuild": "~0.25.0", "esbuild": "~0.25.0",
"get-tsconfig": "^4.7.5" "get-tsconfig": "^4.7.5"
@ -16025,7 +16004,6 @@
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"devOptional": true, "devOptional": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
"tsserver": "bin/tsserver" "tsserver": "bin/tsserver"
@ -16093,7 +16071,6 @@
"integrity": "sha512-6sMvZePQrnZH2/cJkwRpkT7DxoAWh+g6+GFRK6bV3YQo7ogi3SX5rgF6099r5Q53Ma5qeT7LGmOmuIutF4t3lA==", "integrity": "sha512-6sMvZePQrnZH2/cJkwRpkT7DxoAWh+g6+GFRK6bV3YQo7ogi3SX5rgF6099r5Q53Ma5qeT7LGmOmuIutF4t3lA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "8.35.0", "@typescript-eslint/scope-manager": "8.35.0",
"@typescript-eslint/types": "8.35.0", "@typescript-eslint/types": "8.35.0",
@ -16480,7 +16457,6 @@
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz", "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz",
"integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==", "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"esbuild": "^0.27.0", "esbuild": "^0.27.0",
"fdir": "^6.5.0", "fdir": "^6.5.0",
@ -17051,7 +17027,6 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },
@ -17064,7 +17039,6 @@
"resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz", "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz",
"integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==", "integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/chai": "^5.2.2", "@types/chai": "^5.2.2",
"@vitest/expect": "3.2.4", "@vitest/expect": "3.2.4",
@ -17703,7 +17677,6 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"funding": { "funding": {
"url": "https://github.com/sponsors/colinhacks" "url": "https://github.com/sponsors/colinhacks"
} }
@ -18139,7 +18112,6 @@
"resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.3.tgz", "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.3.tgz",
"integrity": "sha512-Iq8QQQ/7X3Sac15oB6p0FmUg/klxQvXLeileoqrTRGJYLV+/9tubbr9ipz0GKHjmXVsgFPo/+W+2cA8eNcR+XA==", "integrity": "sha512-Iq8QQQ/7X3Sac15oB6p0FmUg/klxQvXLeileoqrTRGJYLV+/9tubbr9ipz0GKHjmXVsgFPo/+W+2cA8eNcR+XA==",
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"dependencies": { "dependencies": {
"@grpc/proto-loader": "^0.8.0", "@grpc/proto-loader": "^0.8.0",
"@js-sdsl/ordered-map": "^4.4.2" "@js-sdsl/ordered-map": "^4.4.2"
@ -18258,7 +18230,6 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },

View File

@ -1044,6 +1044,7 @@ export async function loadCliConfig(
format: (argv.outputFormat ?? settings.output?.format) as OutputFormat, format: (argv.outputFormat ?? settings.output?.format) as OutputFormat,
}, },
gemmaModelRouter: settings.experimental?.gemmaModelRouter, gemmaModelRouter: settings.experimental?.gemmaModelRouter,
autoRouting: settings.model?.autoRouting,
adk: settings.experimental?.adk, adk: settings.experimental?.adk,
fakeResponses: argv.fakeResponses, fakeResponses: argv.fakeResponses,
recordResponses: argv.recordResponses, recordResponses: argv.recordResponses,

View File

@ -1112,6 +1112,46 @@ const SETTINGS_SCHEMA = {
description: 'Skip the next speaker check.', description: 'Skip the next speaker check.',
showInDialog: true, showInDialog: true,
}, },
autoRouting: {
type: 'object',
label: 'Auto Routing',
category: 'Model',
requiresRestart: false,
default: {},
description: 'Settings for automatic model routing.',
showInDialog: false,
properties: {
bestEffortPro: {
type: 'boolean',
label: 'Best Effort Pro',
category: 'Model',
requiresRestart: false,
default: false,
description:
'Always prefer the Pro model unless it is unavailable (e.g., due to timeouts or quota), ignoring other routing hints.',
showInDialog: true,
},
proTimeoutMinutes: {
type: 'number',
label: 'Pro Timeout (Minutes)',
category: 'Model',
requiresRestart: false,
default: 5,
description:
'If a Pro request takes longer than this many minutes, it will be marked as temporarily unavailable and fallback to Flash.',
showInDialog: true,
},
proTimeoutFallbackDurationMinutes: {
type: 'number',
label: 'Pro Timeout Fallback Duration (Minutes)',
category: 'Model',
requiresRestart: false,
default: 60,
description: 'How long to route to Flash after Pro times out.',
showInDialog: true,
},
},
},
}, },
}, },

View File

@ -124,6 +124,9 @@ export const createMockConfig = (overrides: Partial<Config> = {}): Config =>
getCompressionThreshold: vi.fn().mockResolvedValue(undefined), getCompressionThreshold: vi.fn().mockResolvedValue(undefined),
getUserCaching: vi.fn().mockResolvedValue(false), getUserCaching: vi.fn().mockResolvedValue(false),
getNumericalRoutingEnabled: vi.fn().mockResolvedValue(false), getNumericalRoutingEnabled: vi.fn().mockResolvedValue(false),
getBestEffortProEnabled: vi.fn().mockResolvedValue(false),
getProTimeoutMinutes: vi.fn().mockResolvedValue(5),
getProTimeoutFallbackDurationMinutes: vi.fn().mockResolvedValue(60),
getClassifierThreshold: vi.fn().mockResolvedValue(undefined), getClassifierThreshold: vi.fn().mockResolvedValue(undefined),
getBannerTextNoCapacityIssues: vi.fn().mockResolvedValue(''), getBannerTextNoCapacityIssues: vi.fn().mockResolvedValue(''),
getBannerTextCapacityIssues: vi.fn().mockResolvedValue(''), getBannerTextCapacityIssues: vi.fn().mockResolvedValue(''),

View File

@ -8,13 +8,15 @@ export type ModelId = string;
type TerminalUnavailabilityReason = 'quota' | 'capacity'; type TerminalUnavailabilityReason = 'quota' | 'capacity';
export type TurnUnavailabilityReason = 'retry_once_per_turn'; export type TurnUnavailabilityReason = 'retry_once_per_turn';
export type TemporaryUnavailabilityReason = 'timeout';
export type UnavailabilityReason = export type UnavailabilityReason =
| TerminalUnavailabilityReason | TerminalUnavailabilityReason
| TurnUnavailabilityReason | TurnUnavailabilityReason
| TemporaryUnavailabilityReason
| 'unknown'; | 'unknown';
export type ModelHealthStatus = 'terminal' | 'sticky_retry'; export type ModelHealthStatus = 'terminal' | 'sticky_retry' | 'temporary';
type HealthState = type HealthState =
| { status: 'terminal'; reason: TerminalUnavailabilityReason } | { status: 'terminal'; reason: TerminalUnavailabilityReason }
@ -22,6 +24,11 @@ type HealthState =
status: 'sticky_retry'; status: 'sticky_retry';
reason: TurnUnavailabilityReason; reason: TurnUnavailabilityReason;
consumed: boolean; consumed: boolean;
}
| {
status: 'temporary';
reason: TemporaryUnavailabilityReason;
untilMs: number;
}; };
export interface ModelAvailabilitySnapshot { export interface ModelAvailabilitySnapshot {
@ -48,6 +55,18 @@ export class ModelAvailabilityService {
}); });
} }
markTemporarilyUnavailable(
model: ModelId,
reason: TemporaryUnavailabilityReason,
durationMs: number,
) {
this.setState(model, {
status: 'temporary',
reason,
untilMs: Date.now() + durationMs,
});
}
markHealthy(model: ModelId) { markHealthy(model: ModelId) {
this.clearState(model); this.clearState(model);
} }
@ -95,6 +114,15 @@ export class ModelAvailabilityService {
return { available: false, reason: state.reason }; return { available: false, reason: state.reason };
} }
if (state.status === 'temporary') {
if (Date.now() < state.untilMs) {
return { available: false, reason: state.reason };
} else {
this.clearState(model);
return { available: true };
}
}
return { available: true }; return { available: true };
} }

View File

@ -679,6 +679,11 @@ export interface ConfigParameters {
policyUpdateConfirmationRequest?: PolicyUpdateConfirmationRequest; policyUpdateConfirmationRequest?: PolicyUpdateConfirmationRequest;
output?: OutputSettings; output?: OutputSettings;
gemmaModelRouter?: GemmaModelRouterSettings; gemmaModelRouter?: GemmaModelRouterSettings;
autoRouting?: {
bestEffortPro?: boolean;
proTimeoutMinutes?: number;
proTimeoutFallbackDurationMinutes?: number;
};
adk?: ADKSettings; adk?: ADKSettings;
disableModelRouterForAuth?: AuthType[]; disableModelRouterForAuth?: AuthType[];
continueOnFailedApiCall?: boolean; continueOnFailedApiCall?: boolean;
@ -963,6 +968,9 @@ export class Config implements McpContext, AgentLoopContext {
private readonly planEnabled: boolean; private readonly planEnabled: boolean;
private readonly trackerEnabled: boolean; private readonly trackerEnabled: boolean;
private readonly planModeRoutingEnabled: boolean; private readonly planModeRoutingEnabled: boolean;
private readonly autoRoutingBestEffortPro: boolean;
private readonly autoRoutingProTimeoutMinutes: number;
private readonly autoRoutingProTimeoutFallbackDurationMinutes: number;
private readonly modelSteering: boolean; private readonly modelSteering: boolean;
private memoryContextManager?: MemoryContextManager; private memoryContextManager?: MemoryContextManager;
private readonly contextManagement: ContextManagementConfig; private readonly contextManagement: ContextManagementConfig;
@ -1117,6 +1125,11 @@ export class Config implements McpContext, AgentLoopContext {
this.planEnabled = params.plan ?? true; this.planEnabled = params.plan ?? true;
this.trackerEnabled = params.tracker ?? false; this.trackerEnabled = params.tracker ?? false;
this.planModeRoutingEnabled = params.planSettings?.modelRouting ?? true; this.planModeRoutingEnabled = params.planSettings?.modelRouting ?? true;
this.autoRoutingBestEffortPro = params.autoRouting?.bestEffortPro ?? false;
this.autoRoutingProTimeoutMinutes =
params.autoRouting?.proTimeoutMinutes ?? 5;
this.autoRoutingProTimeoutFallbackDurationMinutes =
params.autoRouting?.proTimeoutFallbackDurationMinutes ?? 60;
this.enableEventDrivenScheduler = params.enableEventDrivenScheduler ?? true; this.enableEventDrivenScheduler = params.enableEventDrivenScheduler ?? true;
this.skillsSupport = params.skillsSupport ?? true; this.skillsSupport = params.skillsSupport ?? true;
this.disabledSkills = params.disabledSkills ?? []; this.disabledSkills = params.disabledSkills ?? [];
@ -3144,6 +3157,18 @@ export class Config implements McpContext, AgentLoopContext {
return flag?.boolValue ?? true; return flag?.boolValue ?? true;
} }
async getBestEffortProEnabled(): Promise<boolean> {
return this.autoRoutingBestEffortPro;
}
async getProTimeoutMinutes(): Promise<number> {
return this.autoRoutingProTimeoutMinutes;
}
async getProTimeoutFallbackDurationMinutes(): Promise<number> {
return this.autoRoutingProTimeoutFallbackDurationMinutes;
}
/** /**
* Returns the resolved complexity threshold for routing. * Returns the resolved complexity threshold for routing.
* If a remote threshold is provided and within range (0-100), it is returned. * If a remote threshold is provided and within range (0-100), it is returned.

View File

@ -109,6 +109,8 @@ describe('BaseLlmClient', () => {
.mockReturnValue({ authType: AuthType.USE_GEMINI }), .mockReturnValue({ authType: AuthType.USE_GEMINI }),
getEmbeddingModel: vi.fn().mockReturnValue('test-embedding-model'), getEmbeddingModel: vi.fn().mockReturnValue('test-embedding-model'),
isInteractive: vi.fn().mockReturnValue(false), isInteractive: vi.fn().mockReturnValue(false),
getProTimeoutMinutes: vi.fn().mockResolvedValue(5),
getProTimeoutFallbackDurationMinutes: vi.fn().mockResolvedValue(60),
modelConfigService: { modelConfigService: {
getResolvedConfig: vi getResolvedConfig: vi
.fn() .fn()

View File

@ -325,11 +325,19 @@ export class BaseLlmClient {
); );
}; };
const proTimeoutMinutes = await this.config.getProTimeoutMinutes();
const proTimeoutFallbackDurationMinutes =
await this.config.getProTimeoutFallbackDurationMinutes();
return await retryWithBackoff(apiCall, { return await retryWithBackoff(apiCall, {
shouldRetryOnContent, shouldRetryOnContent,
maxAttempts: maxAttempts:
availabilityMaxAttempts ?? maxAttempts ?? DEFAULT_MAX_ATTEMPTS, availabilityMaxAttempts ?? maxAttempts ?? DEFAULT_MAX_ATTEMPTS,
getAvailabilityContext, getAvailabilityContext,
timeoutFallback: {
timeoutMs: proTimeoutMinutes * 60 * 1000,
fallbackDurationMs: proTimeoutFallbackDurationMinutes * 60 * 1000,
},
onPersistent429: this.config.isInteractive() onPersistent429: this.config.isInteractive()
? (authType, error) => ? (authType, error) =>
handleFallback(this.config, currentModel, authType, error) handleFallback(this.config, currentModel, authType, error)

View File

@ -160,6 +160,8 @@ describe('GeminiChat', () => {
authType: 'oauth-personal', authType: 'oauth-personal',
model: currentModel, model: currentModel,
})), })),
getProTimeoutMinutes: vi.fn().mockResolvedValue(5),
getProTimeoutFallbackDurationMinutes: vi.fn().mockResolvedValue(60),
getModel: vi.fn().mockImplementation(() => currentModel), getModel: vi.fn().mockImplementation(() => currentModel),
setModel: vi.fn().mockImplementation((m: string) => { setModel: vi.fn().mockImplementation((m: string) => {
currentModel = m; currentModel = m;

View File

@ -687,6 +687,10 @@ export class GeminiChat {
); );
}; };
const proTimeoutMinutes = await this.context.config.getProTimeoutMinutes();
const proTimeoutFallbackDurationMinutes =
await this.context.config.getProTimeoutFallbackDurationMinutes();
const streamResponse = await retryWithBackoff(apiCall, { const streamResponse = await retryWithBackoff(apiCall, {
onPersistent429: onPersistent429Callback, onPersistent429: onPersistent429Callback,
onValidationRequired: onValidationRequiredCallback, onValidationRequired: onValidationRequiredCallback,
@ -696,6 +700,10 @@ export class GeminiChat {
maxAttempts: maxAttempts:
availabilityMaxAttempts ?? this.context.config.getMaxAttempts(), availabilityMaxAttempts ?? this.context.config.getMaxAttempts(),
getAvailabilityContext, getAvailabilityContext,
timeoutFallback: {
timeoutMs: proTimeoutMinutes * 60 * 1000,
fallbackDurationMs: proTimeoutFallbackDurationMinutes * 60 * 1000,
},
onRetry: (attempt, error, delayMs) => { onRetry: (attempt, error, delayMs) => {
coreEvents.emitRetryAttempt({ coreEvents.emitRetryAttempt({
attempt, attempt,

View File

@ -103,6 +103,8 @@ describe('GeminiChat Network Retries', () => {
authType: 'oauth-personal', authType: 'oauth-personal',
model: 'test-model', model: 'test-model',
}), }),
getProTimeoutMinutes: vi.fn().mockResolvedValue(5),
getProTimeoutFallbackDurationMinutes: vi.fn().mockResolvedValue(60),
getModel: vi.fn().mockReturnValue('gemini-pro'), getModel: vi.fn().mockReturnValue('gemini-pro'),
getActiveModel: vi.fn().mockReturnValue('gemini-pro'), getActiveModel: vi.fn().mockReturnValue('gemini-pro'),
setActiveModel: vi.fn(), setActiveModel: vi.fn(),

View File

@ -32,6 +32,9 @@ vi.mock('./strategies/overrideStrategy.js');
vi.mock('./strategies/approvalModeStrategy.js'); vi.mock('./strategies/approvalModeStrategy.js');
vi.mock('./strategies/classifierStrategy.js'); vi.mock('./strategies/classifierStrategy.js');
vi.mock('./strategies/numericalClassifierStrategy.js'); vi.mock('./strategies/numericalClassifierStrategy.js');
import { BestEffortProStrategy } from './strategies/bestEffortProStrategy.js';
vi.mock('./strategies/bestEffortProStrategy.js');
vi.mock('./strategies/gemmaClassifierStrategy.js'); vi.mock('./strategies/gemmaClassifierStrategy.js');
vi.mock('../telemetry/loggers.js'); vi.mock('../telemetry/loggers.js');
vi.mock('../telemetry/types.js'); vi.mock('../telemetry/types.js');
@ -74,6 +77,7 @@ describe('ModelRouterService', () => {
[ [
new FallbackStrategy(), new FallbackStrategy(),
new OverrideStrategy(), new OverrideStrategy(),
new BestEffortProStrategy(),
new ApprovalModeStrategy(), new ApprovalModeStrategy(),
new ClassifierStrategy(), new ClassifierStrategy(),
new NumericalClassifierStrategy(), new NumericalClassifierStrategy(),
@ -104,13 +108,14 @@ describe('ModelRouterService', () => {
const compositeStrategyArgs = vi.mocked(CompositeStrategy).mock.calls[0]; const compositeStrategyArgs = vi.mocked(CompositeStrategy).mock.calls[0];
const childStrategies = compositeStrategyArgs[0]; const childStrategies = compositeStrategyArgs[0];
expect(childStrategies.length).toBe(6); expect(childStrategies.length).toBe(7);
expect(childStrategies[0]).toBeInstanceOf(FallbackStrategy); expect(childStrategies[0]).toBeInstanceOf(FallbackStrategy);
expect(childStrategies[1]).toBeInstanceOf(OverrideStrategy); expect(childStrategies[1]).toBeInstanceOf(OverrideStrategy);
expect(childStrategies[2]).toBeInstanceOf(ApprovalModeStrategy); expect(childStrategies[2]).toBeInstanceOf(BestEffortProStrategy);
expect(childStrategies[3]).toBeInstanceOf(ClassifierStrategy); expect(childStrategies[3]).toBeInstanceOf(ApprovalModeStrategy);
expect(childStrategies[4]).toBeInstanceOf(NumericalClassifierStrategy); expect(childStrategies[4]).toBeInstanceOf(ClassifierStrategy);
expect(childStrategies[5]).toBeInstanceOf(DefaultStrategy); expect(childStrategies[5]).toBeInstanceOf(NumericalClassifierStrategy);
expect(childStrategies[6]).toBeInstanceOf(DefaultStrategy);
expect(compositeStrategyArgs[1]).toBe('agent-router'); expect(compositeStrategyArgs[1]).toBe('agent-router');
}); });
@ -133,14 +138,15 @@ describe('ModelRouterService', () => {
const compositeStrategyArgs = vi.mocked(CompositeStrategy).mock.calls[0]; const compositeStrategyArgs = vi.mocked(CompositeStrategy).mock.calls[0];
const childStrategies = compositeStrategyArgs[0]; const childStrategies = compositeStrategyArgs[0];
expect(childStrategies.length).toBe(7); expect(childStrategies.length).toBe(8);
expect(childStrategies[0]).toBeInstanceOf(FallbackStrategy); expect(childStrategies[0]).toBeInstanceOf(FallbackStrategy);
expect(childStrategies[1]).toBeInstanceOf(OverrideStrategy); expect(childStrategies[1]).toBeInstanceOf(OverrideStrategy);
expect(childStrategies[2]).toBeInstanceOf(ApprovalModeStrategy); expect(childStrategies[2]).toBeInstanceOf(BestEffortProStrategy);
expect(childStrategies[3]).toBeInstanceOf(GemmaClassifierStrategy); expect(childStrategies[3]).toBeInstanceOf(ApprovalModeStrategy);
expect(childStrategies[4]).toBeInstanceOf(ClassifierStrategy); expect(childStrategies[4]).toBeInstanceOf(GemmaClassifierStrategy);
expect(childStrategies[5]).toBeInstanceOf(NumericalClassifierStrategy); expect(childStrategies[5]).toBeInstanceOf(ClassifierStrategy);
expect(childStrategies[6]).toBeInstanceOf(DefaultStrategy); expect(childStrategies[6]).toBeInstanceOf(NumericalClassifierStrategy);
expect(childStrategies[7]).toBeInstanceOf(DefaultStrategy);
expect(compositeStrategyArgs[1]).toBe('agent-router'); expect(compositeStrategyArgs[1]).toBe('agent-router');
}); });

View File

@ -18,6 +18,7 @@ import { NumericalClassifierStrategy } from './strategies/numericalClassifierStr
import { CompositeStrategy } from './strategies/compositeStrategy.js'; import { CompositeStrategy } from './strategies/compositeStrategy.js';
import { FallbackStrategy } from './strategies/fallbackStrategy.js'; import { FallbackStrategy } from './strategies/fallbackStrategy.js';
import { OverrideStrategy } from './strategies/overrideStrategy.js'; import { OverrideStrategy } from './strategies/overrideStrategy.js';
import { BestEffortProStrategy } from './strategies/bestEffortProStrategy.js';
import { ApprovalModeStrategy } from './strategies/approvalModeStrategy.js'; import { ApprovalModeStrategy } from './strategies/approvalModeStrategy.js';
import { logModelRouting } from '../telemetry/loggers.js'; import { logModelRouting } from '../telemetry/loggers.js';
@ -43,6 +44,9 @@ export class ModelRouterService {
strategies.push(new FallbackStrategy()); strategies.push(new FallbackStrategy());
strategies.push(new OverrideStrategy()); strategies.push(new OverrideStrategy());
// Best Effort Pro is next.
strategies.push(new BestEffortProStrategy());
// Approval mode is next. // Approval mode is next.
strategies.push(new ApprovalModeStrategy()); strategies.push(new ApprovalModeStrategy());

View File

@ -0,0 +1,83 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type { Config } from '../../config/config.js';
import { isAutoModel, resolveModel } from '../../config/models.js';
import type {
RoutingStrategy,
RoutingDecision,
RoutingContext,
} from '../routingStrategy.js';
/**
* A routing strategy that respects the "Best Effort Pro" setting.
* If the setting is enabled and the Pro model is available, it routes to Pro
* regardless of complexity. If Pro is unavailable, it routes to Flash.
*/
export class BestEffortProStrategy implements RoutingStrategy {
name = 'best-effort-pro';
async route(
context: RoutingContext,
config: Config,
): Promise<RoutingDecision | null> {
const requestedModel = config.getModel();
if (!isAutoModel(requestedModel)) {
return null;
}
const isBestEffortProEnabled = await config.getBestEffortProEnabled();
if (!isBestEffortProEnabled) {
return null;
}
const useGemini3_1 = (await config.getGemini31Launched?.()) ?? false;
const useGemini3_1FlashLite =
(await config.getGemini31FlashLiteLaunched?.()) ?? false;
const hasAccessToPreview = config.getHasAccessToPreviewModel?.() ?? true;
const availabilityService = config.getModelAvailabilityService();
const proModel = resolveModel(
'gemini-3.1-pro',
useGemini3_1,
useGemini3_1FlashLite,
false,
hasAccessToPreview,
config,
);
const flashModel = resolveModel(
'gemini-3.1-flash',
useGemini3_1,
useGemini3_1FlashLite,
false,
hasAccessToPreview,
config,
);
const proSnapshot = availabilityService.snapshot(proModel);
if (proSnapshot.available) {
return {
model: proModel,
metadata: {
source: this.name,
latencyMs: 0,
reasoning:
'Best Effort Pro is enabled and the Pro model is available.',
},
};
} else {
return {
model: flashModel,
metadata: {
source: this.name,
latencyMs: 0,
reasoning: `Best Effort Pro is enabled, but Pro is unavailable (${proSnapshot.reason}). Falling back to Flash.`,
},
};
}
}
}

View File

@ -37,6 +37,10 @@ export interface RetryOptions {
signal?: AbortSignal; signal?: AbortSignal;
getAvailabilityContext?: () => RetryAvailabilityContext | undefined; getAvailabilityContext?: () => RetryAvailabilityContext | undefined;
onRetry?: (attempt: number, error: unknown, delayMs: number) => void; onRetry?: (attempt: number, error: unknown, delayMs: number) => void;
timeoutFallback?: {
timeoutMs: number;
fallbackDurationMs: number;
};
} }
const DEFAULT_RETRY_OPTIONS: RetryOptions = { const DEFAULT_RETRY_OPTIONS: RetryOptions = {
@ -240,6 +244,7 @@ export async function retryWithBackoff<T>(
signal, signal,
getAvailabilityContext, getAvailabilityContext,
onRetry, onRetry,
timeoutFallback,
} = { } = {
...DEFAULT_RETRY_OPTIONS, ...DEFAULT_RETRY_OPTIONS,
shouldRetryOnError: isRetryableError, shouldRetryOnError: isRetryableError,
@ -248,6 +253,7 @@ export async function retryWithBackoff<T>(
let attempt = 0; let attempt = 0;
let currentDelay = initialDelayMs; let currentDelay = initialDelayMs;
let startTime = Date.now();
const throwIfAborted = () => { const throwIfAborted = () => {
if (signal?.aborted) { if (signal?.aborted) {
throw createAbortError(); throw createAbortError();
@ -294,6 +300,42 @@ export async function retryWithBackoff<T>(
const errorCode = getErrorStatus(error); const errorCode = getErrorStatus(error);
const isTimeout =
(error instanceof Error &&
error.message.toLowerCase().includes('timeout')) ||
getRetryErrorType(error) === 'ETIMEDOUT' ||
getRetryErrorType(error) === 'FETCH_FAILED';
if (isTimeout && timeoutFallback) {
if (Date.now() - startTime >= timeoutFallback.timeoutMs) {
const successContext = getAvailabilityContext?.();
if (successContext) {
successContext.service.markTemporarilyUnavailable(
successContext.policy.model,
'timeout',
timeoutFallback.fallbackDurationMs,
);
}
if (onPersistent429) {
try {
const fallbackModel = await onPersistent429(
authType,
new Error('Request timed out'),
);
if (fallbackModel) {
attempt = 0;
currentDelay = initialDelayMs;
startTime = Date.now();
continue;
}
} catch (fallbackError) {
debugLogger.warn('Model fallback failed:', fallbackError);
}
}
throw error;
}
}
if ( if (
classifiedError instanceof TerminalQuotaError || classifiedError instanceof TerminalQuotaError ||
classifiedError instanceof ModelNotFoundError classifiedError instanceof ModelNotFoundError

View File

@ -702,6 +702,37 @@
"markdownDescription": "Skip the next speaker check.\n\n- Category: `Model`\n- Requires restart: `no`\n- Default: `true`", "markdownDescription": "Skip the next speaker check.\n\n- Category: `Model`\n- Requires restart: `no`\n- Default: `true`",
"default": true, "default": true,
"type": "boolean" "type": "boolean"
},
"autoRouting": {
"title": "Auto Routing",
"description": "Settings for automatic model routing.",
"markdownDescription": "Settings for automatic model routing.\n\n- Category: `Model`\n- Requires restart: `no`\n- Default: `{}`",
"default": {},
"type": "object",
"properties": {
"bestEffortPro": {
"title": "Best Effort Pro",
"description": "Always prefer the Pro model unless it is unavailable (e.g., due to timeouts or quota), ignoring other routing hints.",
"markdownDescription": "Always prefer the Pro model unless it is unavailable (e.g., due to timeouts or quota), ignoring other routing hints.\n\n- Category: `Model`\n- Requires restart: `no`\n- Default: `false`",
"default": false,
"type": "boolean"
},
"proTimeoutMinutes": {
"title": "Pro Timeout (Minutes)",
"description": "If a Pro request takes longer than this many minutes, it will be marked as temporarily unavailable and fallback to Flash.",
"markdownDescription": "If a Pro request takes longer than this many minutes, it will be marked as temporarily unavailable and fallback to Flash.\n\n- Category: `Model`\n- Requires restart: `no`\n- Default: `5`",
"default": 5,
"type": "number"
},
"proTimeoutFallbackDurationMinutes": {
"title": "Pro Timeout Fallback Duration (Minutes)",
"description": "How long to route to Flash after Pro times out.",
"markdownDescription": "How long to route to Flash after Pro times out.\n\n- Category: `Model`\n- Requires restart: `no`\n- Default: `60`",
"default": 60,
"type": "number"
}
},
"additionalProperties": false
} }
}, },
"additionalProperties": false "additionalProperties": false