Compare commits

...
66 Commits
Author SHA1 Message Date
ZyyandCodex e0b0ab14da fix(openai): preserve quota observation timestamps
Keep header and stream quota facts tied to their collection time so delayed responses cannot replace a newer refresh. Filter stale observations again on merge conflicts and retain timestamps through failure and warmup paths.

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 15:27:03 +08:00
b4bb97d1dc feat(accounts): add xAI and Antigravity API key upstreams (#816)
* feat(accounts): add xAI and Antigravity API key upstreams

Support native Responses and GenAI API key accounts with custom upstream URLs.
Reuse account management and isolate credentials, catalogs, and runtime connections by revision.

Refs #814

Co-authored-by: Codex <noreply@openai.com>

* refactor(antigravity): simplify API key account names

Use name consistently in API key account documents and verify the exported contract before reimport.

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 15:07:11 +08:00
ZyyandCodex 9f979110d2 fix(gateway): forward upstream retry headers regardless of error kind
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 13:33:10 +08:00
github-actions[bot] a5cddfe4a5 chore(release): update release channels to 3.60.5 2026-12-01 05:12:39 +00:00
ZyyandCodex 914c4c24d3 chore: bump version to 3.60.5
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:52:44 +08:00
ZyyandCodex 7251546c75 fix(gateway): preserve upstream retry headers across capacity rotation
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:52:24 +08:00
ZyyandCodex 3c38925716 docs(skills): clarify frontend tooltip and list loading guidance
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:33:02 +08:00
ZyyandCodex 43ca35b027 fix(antigravity): explain Google account connection test failures
Refs #805

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:18:47 +08:00
ZyyandCodex 95d545a7d8 perf(admin): show request error popovers without fetching details
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:17:35 +08:00
ZyyandCodex db3324f90a fix(admin): show upstream errors and retry waits in request popovers
Localize interrupted requests, align quota badges, and update the icon picker to the responsive UI revision.

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 11:56:13 +08:00
ZyyandCodex 30bcff3419 test(store): verify display names for accounts sharing an email
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 11:56:13 +08:00
329503d967 fix(admin): use account display names in sorting and usage (#815)
* fix(admin): use account display names in sorting and usage

Co-authored-by: Codex <noreply@openai.com>

* fix(ui): remove native tooltips from usage identity cells

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 11:10:24 +08:00
eae19e211e fix(openai): start weekly bucket warmup after reset-credit consume (#813)
* fix(openai): start weekly bucket warmup after reset-credit consume

After a successful reset or already_redeemed consume, refresh quota and
advance an already-enabled bucket warmup to the actual reset time. Pull
an early reset's registered future boundary back so due() is not blocked
until the original window ends. Keep the five-minute recheck and skip
warmup when the new round already has usage.

* fix(openai): make credit-triggered weekly warmup idempotent

Register confirmed redemptions with bucket progress and recheck usage in the warmup worker. Preserve precise usage evidence and keep rolling quota deadlines separate from confirmed resets.

Co-authored-by: Codex <noreply@openai.com>

* refactor(openai): keep only the latest warmup redemption

Reuse account warmup progress to recognize retries of the latest credit. Remove the receipt table and keep the existing storage contract.

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 10:56:06 +08:00
github-actions[bot] 294e9c8bd8 chore(release): update release channels to 3.60.4 2026-11-30 16:44:00 +00:00
ZyyandCodex 1b92c552b9 chore: bump version to 3.60.4
Co-authored-by: Codex <noreply@openai.com>
2026-11-30 23:53:30 +08:00
ZyyandCodex c9fb2ac465 test(openai): align request fixtures with empty defaults
Use the empty country default in content preservation assertions and configure residency explicitly in routing header coverage.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 23:48:12 +08:00
ZyyandCodex 6bf109e784 test(store): initialize configuration revision baseline
Initialize configuration and settings revisions after test migrations so functional assertions remain independent of migration revision increments.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 23:25:46 +08:00
ZyyandCodex fa187c5031 fix(settings): keep help controls transparent and consistent
Use a shared 24px square help trigger for request settings and automatic
approval details. Align the UI dependency and submodule with the disabled
link background fix.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 23:17:02 +08:00
ZyyandCodex 5f7e1723f3 fix(openai): default request country and residency to empty
Use the empty country policy and leave residency and account routing unset.
Migrate existing follow-location policies and us residency values while
preserving custom settings and advancing the settings revision.
Update the settings UI, existing contract tests, and deployment guidance.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 23:02:45 +08:00
ZyyandCodex 7d34be5d02 fix(antigravity): preserve native signatures across model switches
Recognize known Claude and Gemini signature envelopes without wrapping
response signatures. Remove foreign thinking history while preserving
compatible or unknown signatures, ordinary text, and tool history.

Integrate cleanup into request field editing and reuse unchanged history.
Keep counting and unknown model families untouched, without session caches.
Cover native JSON/SSE, escaped fields, malformed envelopes, and model
switches; document recognition and account compatibility boundaries.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 23:02:44 +08:00
github-actions[bot] ebb3c4b1fa chore(release): update release channels to 3.60.3 2026-11-30 12:57:31 +00:00
ZyyandCodex 2bf0ca146d chore: bump version to 3.60.3
Co-authored-by: Codex <noreply@openai.com>
2026-11-30 20:34:41 +08:00
ZyyandCodex 5c1e27fc47 fix(plugins): account for peer queues when awaiting cancellation
Use the existing queue timeout for cancellation confirmations so normal peer backpressure does not terminate healthy sessions. Cover delayed acknowledgements and bounded cleanup of unresponsive peers.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 20:33:31 +08:00
dependabot[bot] 03f21c26eb chore(deps): bump @lucide/vue in /frontend in the minor-and-patch group (#810)
Bumps the minor-and-patch group in /frontend with 1 update: [@lucide/vue](https://github.com/lucide-icons/lucide/tree/HEAD/packages/vue).


Updates `@lucide/vue` from 1.83.0 to 1.84.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.84.0/packages/vue)

---
updated-dependencies:
- dependency-name: "@lucide/vue"
  dependency-version: 1.84.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 20:33:31 +08:00
ZyyandCodex 280ded5707 chore(deps): pin h2 to the Codex baseline and hold Rust image updates
Co-authored-by: Codex <noreply@openai.com>
2026-11-30 18:44:09 +08:00
8fb07f993c fix(antigravity): repair missing native Claude tool IDs (#808)
Pair uniquely named calls and results in adjacent model/user turns before
sending native Claude requests. Preserve existing IDs and raw business
fields, avoid ID collisions, and leave ambiguous history unchanged.
Cover JSON/SSE transport, partial IDs, replay stability, and scope limits.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-30 17:56:45 +08:00
ZyyandCodex ee691246c7 fix(build): retain sha2 optimization across dependency updates
Match the sha2 package without pinning its patch version so dev and test builds retain the intended optimization after lockfile updates. Keep multipart concurrency assertions and timeouts unchanged.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 15:36:23 +08:00
ZyyandCodex e406a6bcd8 fix(plugins): separate cancellation send and confirmation deadlines
Start the confirmation deadline after the cancellation frame is written. Arbitrate acknowledgements and expiry in the reader and commit failures under the call table lock. Cover queued cancellation under backpressure and recovery at the default in-flight limit.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 15:13:22 +08:00
ZyyandCodex 4ffaeb3051 fix(xai): align Grok passthrough and client-owned history
Align the Grok 1.0.92 transport profile, retain only continuation routing metadata, and filter downstream environment headers at provider boundaries.

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 14:37:32 +08:00
github-actions[bot] a126c194f5 chore(release): update release channels to 3.60.2 2026-11-30 04:00:31 +00:00
ZyyandCodex 964e22eb91 chore: bump version to 3.60.2
Co-authored-by: Codex <noreply@openai.com>
2026-11-30 11:37:29 +08:00
ZyyandCodex 5a5d07d1c7 fix(openai): reset WebSocket upload timeout after each flushed fragment
Co-authored-by: Codex <noreply@openai.com>
2026-11-30 11:24:10 +08:00
ZyyandCodex a41a0498d1 fix(frontend): remove native title tooltips
Co-authored-by: Codex <noreply@openai.com>
2026-11-30 10:43:31 +08:00
dependabot[bot] 9aea228fa8 chore(deps): bump the minor-and-patch group with 2 updates (#797)
Bumps the minor-and-patch group with 2 updates: [taiki-e/install-action](https://github.com/taiki-e/install-action) and [sigstore/cosign-installer](https://github.com/sigstore/cosign-installer).


Updates `taiki-e/install-action` from 2.90.6 to 2.90.11
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/taiki-e/install-action/compare/75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f...073e1fd0bc889c9aee68dbaaa927cde1b5653a83)

Updates `sigstore/cosign-installer` from 4.1.3 to 4.1.4
- [Release notes](https://github.com/sigstore/cosign-installer/releases)
- [Commits](https://github.com/sigstore/cosign-installer/compare/756fe2d284c7292c4e9b62c8a28f1e5629c59532...881c63bd87e38389154debd8331404ce7ca8a3ab)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-version: 2.90.11
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: sigstore/cosign-installer
  dependency-version: 4.1.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 10:23:49 +08:00
dependabot[bot] 25965cbfb3 chore(deps): bump node from 5df7998 to 0042e17 in /deploy (#803)
Bumps node from `5df7998` to `0042e17`.

---
updated-dependencies:
- dependency-name: node
  dependency-version: 26.13.1-bookworm-slim
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 10:23:44 +08:00
dependabot[bot] fa0bedd28b chore(deps): bump debian from 734a72b to e67eeea in /deploy (#802)
Bumps debian from `734a72b` to `e67eeea`.

---
updated-dependencies:
- dependency-name: debian
  dependency-version: bookworm-slim
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 10:23:40 +08:00
dependabot[bot] 1bd27ef6c8 chore(deps): bump the minor-and-patch group in /frontend with 8 updates (#800)
Bumps the minor-and-patch group in /frontend with 8 updates:

| Package | From | To |
| --- | --- | --- |
| [@lucide/vue](https://github.com/lucide-icons/lucide/tree/HEAD/packages/vue) | `1.77.0` | `1.83.0` |
| [@vueuse/core](https://github.com/vueuse/vueuse/tree/HEAD/packages/core) | `15.0.0` | `15.1.0` |
| [@vueuse/integrations](https://github.com/vueuse/vueuse/tree/HEAD/packages/integrations) | `15.0.0` | `15.1.0` |
| [vue-i18n](https://github.com/intlify/vue-i18n/tree/HEAD/packages/vue-i18n) | `11.4.23` | `11.4.24` |
| [vue-router](https://github.com/vuejs/router) | `5.5.1` | `5.5.3` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.6.6` | `26.6.11` |
| [eslint](https://github.com/eslint/eslint) | `10.15.0` | `10.16.0` |
| [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `8.3.8` | `8.4.0` |


Updates `@lucide/vue` from 1.77.0 to 1.83.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.83.0/packages/vue)

Updates `@vueuse/core` from 15.0.0 to 15.1.0
- [Release notes](https://github.com/vueuse/vueuse/releases)
- [Commits](https://github.com/vueuse/vueuse/commits/v15.1.0/packages/core)

Updates `@vueuse/integrations` from 15.0.0 to 15.1.0
- [Release notes](https://github.com/vueuse/vueuse/releases)
- [Commits](https://github.com/vueuse/vueuse/commits/v15.1.0/packages/integrations)

Updates `vue-i18n` from 11.4.23 to 11.4.24
- [Release notes](https://github.com/intlify/vue-i18n/releases)
- [Changelog](https://github.com/intlify/vue-i18n/blob/v11.4.24/CHANGELOG.md)
- [Commits](https://github.com/intlify/vue-i18n/commits/v11.4.24/packages/vue-i18n)

Updates `vue-router` from 5.5.1 to 5.5.3
- [Release notes](https://github.com/vuejs/router/releases)
- [Commits](https://github.com/vuejs/router/compare/v5.5.1...v5.5.3)

Updates `@types/node` from 26.6.6 to 26.6.11
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `eslint` from 10.15.0 to 10.16.0
- [Release notes](https://github.com/eslint/eslint/releases)
- [Commits](https://github.com/eslint/eslint/compare/v10.15.0...v10.16.0)

Updates `vite` from 8.3.8 to 8.4.0
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v8.4.0/packages/vite)

---
updated-dependencies:
- dependency-name: "@lucide/vue"
  dependency-version: 1.83.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: "@vueuse/core"
  dependency-version: 15.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: "@vueuse/integrations"
  dependency-version: 15.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: vue-i18n
  dependency-version: 11.4.24
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: vue-router
  dependency-version: 5.5.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: "@types/node"
  dependency-version: 26.6.11
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: eslint
  dependency-version: 10.16.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: vite
  dependency-version: 8.4.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 10:23:36 +08:00
dependabot[bot] 0981996ef3 chore(deps): bump jsonschema from 0.61.2 to 0.63.2 in /backend (#799)
Bumps [jsonschema](https://github.com/Stranger6667/jsonschema) from 0.61.2 to 0.63.2.
- [Release notes](https://github.com/Stranger6667/jsonschema/releases)
- [Changelog](https://github.com/Stranger6667/jsonschema/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Stranger6667/jsonschema/compare/ruby-v0.61.2...ruby-v0.63.2)

---
updated-dependencies:
- dependency-name: jsonschema
  dependency-version: 0.63.2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 10:23:31 +08:00
dependabot[bot] 783e4578ba chore(deps): bump the minor-and-patch group in /backend with 12 updates (#798)
Bumps the minor-and-patch group in /backend with 12 updates:

| Package | From | To |
| --- | --- | --- |
| [clap](https://github.com/clap-rs/clap) | `4.6.8` | `4.6.10` |
| [sha2](https://github.com/RustCrypto/hashes) | `0.11.1` | `0.11.2` |
| [zip](https://github.com/zip-rs/zip2) | `9.8.0` | `9.8.2` |
| [yaml-rust2](https://github.com/Ethiraric/yaml-rust2) | `0.13.0` | `0.13.2` |
| [async-compression](https://github.com/Nullus157/async-compression) | `0.4.52` | `0.4.54` |
| [aws-sdk-s3](https://github.com/awslabs/aws-sdk-rust) | `1.161.0` | `1.162.0` |
| [aws-smithy-runtime-api](https://github.com/smithy-lang/smithy-rs) | `1.22.0` | `1.22.1` |
| [aws-smithy-types](https://github.com/smithy-lang/smithy-rs) | `1.9.4` | `1.9.5` |
| [redis](https://github.com/redis-rs/redis-rs) | `1.8.2` | `1.8.3` |
| [crc32fast](https://github.com/srijs/rust-crc32fast) | `1.5.5` | `1.5.6` |
| [lru](https://github.com/jeromefroe/lru-rs) | `0.19.0` | `0.19.2` |
| [h2](https://github.com/hyperium/h2) | `0.4.20` | `0.4.21` |


Updates `clap` from 4.6.8 to 4.6.10
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/main/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.6.8...clap_complete-v4.6.10)

Updates `sha2` from 0.11.1 to 0.11.2
- [Commits](https://github.com/RustCrypto/hashes/compare/sha2-v0.11.1...sha2-v0.11.2)

Updates `zip` from 9.8.0 to 9.8.2
- [Release notes](https://github.com/zip-rs/zip2/releases)
- [Changelog](https://github.com/zip-rs/zip2/blob/master/CHANGELOG.md)
- [Commits](https://github.com/zip-rs/zip2/compare/v9.8.0...v9.8.2)

Updates `yaml-rust2` from 0.13.0 to 0.13.2
- [Release notes](https://github.com/Ethiraric/yaml-rust2/releases)
- [Changelog](https://github.com/Ethiraric/yaml-rust2/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Ethiraric/yaml-rust2/compare/v0.13.0...v0.13.2)

Updates `async-compression` from 0.4.52 to 0.4.54
- [Release notes](https://github.com/Nullus157/async-compression/releases)
- [Commits](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.52...async-compression-v0.4.54)

Updates `aws-sdk-s3` from 1.161.0 to 1.162.0
- [Release notes](https://github.com/awslabs/aws-sdk-rust/releases)
- [Commits](https://github.com/awslabs/aws-sdk-rust/commits)

Updates `aws-smithy-runtime-api` from 1.22.0 to 1.22.1
- [Release notes](https://github.com/smithy-lang/smithy-rs/releases)
- [Changelog](https://github.com/smithy-lang/smithy-rs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/smithy-lang/smithy-rs/commits)

Updates `aws-smithy-types` from 1.9.4 to 1.9.5
- [Release notes](https://github.com/smithy-lang/smithy-rs/releases)
- [Changelog](https://github.com/smithy-lang/smithy-rs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/smithy-lang/smithy-rs/commits)

Updates `redis` from 1.8.2 to 1.8.3
- [Release notes](https://github.com/redis-rs/redis-rs/releases)
- [Commits](https://github.com/redis-rs/redis-rs/compare/redis-1.8.2...redis-1.8.3)

Updates `crc32fast` from 1.5.5 to 1.5.6
- [Commits](https://github.com/srijs/rust-crc32fast/compare/v1.5.5...v1.5.6)

Updates `lru` from 0.19.0 to 0.19.2
- [Changelog](https://github.com/jeromefroe/lru-rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/jeromefroe/lru-rs/compare/0.19.0...0.19.2)

Updates `h2` from 0.4.20 to 0.4.21
- [Release notes](https://github.com/hyperium/h2/releases)
- [Changelog](https://github.com/hyperium/h2/blob/master/CHANGELOG.md)
- [Commits](https://github.com/hyperium/h2/compare/v0.4.20...v0.4.21)

---
updated-dependencies:
- dependency-name: clap
  dependency-version: 4.6.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: sha2
  dependency-version: 0.11.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: zip
  dependency-version: 9.8.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: yaml-rust2
  dependency-version: 0.13.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: async-compression
  dependency-version: 0.4.54
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: aws-sdk-s3
  dependency-version: 1.162.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: aws-smithy-runtime-api
  dependency-version: 1.22.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: aws-smithy-types
  dependency-version: 1.9.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: redis
  dependency-version: 1.8.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: crc32fast
  dependency-version: 1.5.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: lru
  dependency-version: 0.19.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: h2
  dependency-version: 0.4.21
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 10:23:27 +08:00
ZyyandCodex 0db3c6a215 fix(ui): unify provider icon sizes and balance diagnostic table columns
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 20:28:27 +08:00
github-actions[bot] fe1c38aeb7 chore(release): update release channels to 3.60.1 2026-11-29 11:59:57 +00:00
ZyyandCodex 2cbdd62b4e chore: bump version to 3.60.1
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 19:44:01 +08:00
ZyyandCodex 39cc23d2f0 chore(ui): pin the host to the bundled UI revision
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 19:43:44 +08:00
ZyyandCodex 102131056b fix(ui): refine table spacing and provider icon sizes
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 19:38:54 +08:00
ZyyandCodex c94a443620 perf(store): reduce redundant persistence and write amplification
Reuse unchanged catalog TOAST values during refresh. Remove unused analytics source versions and duplicate artifact version storage, retire the covered charge-event index, and index artifact configuration cleanup.

Co-authored-by: Codex <noreply@openai.com>
2026-11-29 18:51:12 +08:00
github-actions[bot] ef870690e3 chore(release): update release channels to 3.60.0 2026-11-29 10:43:34 +00:00
ZyyandCodex f4254104c9 chore: bump version to 3.60.0
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 18:29:48 +08:00
ZyyandCodex 36136728c6 fix(usage): remove unused upstream column translations
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 18:29:30 +08:00
ZyyandCodex 0d731c5059 feat(usage): show platforms in hotspot diagnostics
Expose observed providers for models and account icons for account groups. Rebalance diagnostic table columns and leave missing reasoning effort blank.

Co-authored-by: Codex <noreply@openai.com>
2026-11-29 18:23:11 +08:00
3fe4248fd6 fix(api): separate model catalog protocol from authentication (#795)
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 18:03:25 +08:00
ZyyandCodex 3cc9c71ab5 feat(accounts): support custom platform icons
Store icon choices per account and display them across the admin views. Refine account form controls and simplify the API key setup dialog. Pin the UI library to v0.14.0.

Co-authored-by: Codex <noreply@openai.com>
2026-11-29 17:57:43 +08:00
ZyyandCodex 2dc3ba8d56 docs: apply development guidelines during acceptance checks
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 13:10:04 +08:00
Zyy 7c16190936 fix(frontend): refine login spacing and accessible form interactions 2026-11-29 12:14:43 +08:00
ZyyandCodex c89152ce08 fix(accounts): group account details and period controls in quota forecasts
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 11:29:28 +08:00
ZyyandCodex 4b8825a28f fix(keys): clarify reference account options and stabilize the alignment dialog
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 11:20:27 +08:00
github-actions[bot] 95a89e9010 chore(release): update release channels to 3.59.0 2026-11-28 17:50:20 +00:00
ZyyandCodex 4fc8f836be chore: bump version to 3.59.0
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 01:33:40 +08:00
ZyyandCodex ddd33da737 feat(settings): support regex prompt rewrites and match previews
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 01:33:23 +08:00
ZyyandCodex 1d875def09 test: align prompt rewrite fixtures and current-day group costs
Co-authored-by: Codex <noreply@openai.com>
2026-11-29 00:08:30 +08:00
ZyyandCodex e6def7b634 feat(settings): edit named prompt rewrite rules in a dialog
Co-authored-by: Codex <noreply@openai.com>
2026-11-28 23:52:35 +08:00
ZyyandCodex f5d3c55d75 chore(ui): upgrade component library to v0.13.6
Co-authored-by: Codex <noreply@openai.com>
2026-11-28 23:06:52 +08:00
ZyyandCodex 30487dfbf1 fix(ui): align reference account labels and update component library
Use the shared account identity label and avoid repeating the email in the reference picker. Update the UI submodule and document control item fill derivation.

Co-authored-by: Codex <noreply@openai.com>
2026-11-28 22:57:02 +08:00
ZyyandCodex 71cfdcb33e feat(settings): add provider-scoped prompt rewrite rules
Co-authored-by: Codex <noreply@openai.com>
2026-11-28 22:51:01 +08:00
ZyyandCodex 98954aefb6 fix(usage): show error codes before localized summaries
Co-authored-by: Codex <noreply@openai.com>
2026-11-28 19:34:27 +08:00
ZyyandCodex c74c570228 fix(usage): localize error summaries in request records
Co-authored-by: Codex <noreply@openai.com>
2026-11-28 19:33:29 +08:00
github-actions[bot] fbf1aa1d9b chore(release): update release channels to 3.58.0 2026-11-28 10:48:04 +00:00
427 changed files with 11544 additions and 3410 deletions
+7 -5
View File
@@ -1,6 +1,6 @@
--- ---
name: cpr-dev-guide name: cpr-dev-guide
description: Codex Proxy RS 的需求评估、排障、开发、代码审查与文档维护入口 description: Codex Proxy RS 的需求评估、排障、开发、代码审查与文档维护,包括对代码和文档改动的验收
--- ---
# 开发指南 # 开发指南
@@ -22,9 +22,9 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
## 先确定领域与必读规范 ## 先确定领域与必读规范
按受影响行为和实际文件执行下表所有命中项。流程引用首次完整读取,长文档按标题定位指定章节 确定方案前按受影响行为和实际文件执行下表所有命中项。流程引用首次完整读取,长文档按标题定位指定章节。单独验收和开发收尾采用同一组领域规范
| 领域或操作,行为影响与文件路径满足其一即可 | 确定方案前读取与执行 | | 领域或操作,行为影响与文件路径满足其一即可 | 必读规范与检查 |
| --- | --- | | --- | --- |
| 调整页面、弹窗、表单、按钮、文案、样式或交互;目标在 `frontend/`、`modules/ui/`、插件前端,或是 `.vue` 文件 | [前端流程](references/frontend.md),局部修改同样按影响范围检查组件复用、文案、Token、样式、视觉状态和运行证据 | | 调整页面、弹窗、表单、按钮、文案、样式或交互;目标在 `frontend/`、`modules/ui/`、插件前端,或是 `.vue` 文件 | [前端流程](references/frontend.md),局部修改同样按影响范围检查组件复用、文案、Token、样式、视觉状态和运行证据 |
| 插件接入、SDK、Runtime、扩展接口或独立网关插件,含账号、调度或 API 中为插件新增的处理;目标在 `backend/crates/gateway-plugin/`、`modules/plugins/` | [插件职责边界](references/plugin-boundaries.md)及所用 [SDK](../../../backend/crates/gateway-plugin/sdk/README.md) 类型与能力合同;独立插件开发、排查或审查同时执行 [cpr-plugin-dev](../cpr-plugin-dev/SKILL.md) | | 插件接入、SDK、Runtime、扩展接口或独立网关插件,含账号、调度或 API 中为插件新增的处理;目标在 `backend/crates/gateway-plugin/`、`modules/plugins/` | [插件职责边界](references/plugin-boundaries.md)及所用 [SDK](../../../backend/crates/gateway-plugin/sdk/README.md) 类型与能力合同;独立插件开发、排查或审查同时执行 [cpr-plugin-dev](../cpr-plugin-dev/SKILL.md) |
@@ -41,11 +41,13 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
## 执行与收尾 ## 执行与收尾
长任务按 [任务延续与收尾](../../../AGENTS.md#任务延续与收尾)恢复已匹配的领域、具体约束与验证进度。单独收到验收请求时,先确认待验收版本和范围,发现偏差按当前授权处理
1. 遵守已提供的 [AGENTS.md](../../../AGENTS.md),按其 CodeGraph 约定定位代码;确认工作区、任务范围与已有改动,找到事实归属、同类实现和调用链,补齐上表命中规范及[项目约定](../../../CONTRIBUTING.md#项目约定)对应条目后再修改 1. 遵守已提供的 [AGENTS.md](../../../AGENTS.md),按其 CodeGraph 约定定位代码;确认工作区、任务范围与已有改动,找到事实归属、同类实现和调用链,补齐上表命中规范及[项目约定](../../../CONTRIBUTING.md#项目约定)对应条目后再修改
2. 以最终差异重新匹配上表,补齐新增领域的规范并检查实际实现,再处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复 2. 按最终差异与受影响行为重新匹配上表,逐项对照适用条款检查实际实现。处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
3. 模块移动或重命名时,同步核对源码、测试、公开导出及配置、脚本中的名称和路径引用;在本任务内更新受影响的文档、示例和引用 3. 模块移动或重命名时,同步核对源码、测试、公开导出及配置、脚本中的名称和路径引用;在本任务内更新受影响的文档、示例和引用
4. 按变更范围执行[验证](../../../CONTRIBUTING.md#验证)及其停止条件,后端命令见[验证命令](../../../docs/architecture.md#验证命令);复用仍适用的验证证据与用户已确定的验收分工,区分通过、失败、跳过与未执行 4. 按变更范围执行[验证](../../../CONTRIBUTING.md#验证)及其停止条件,后端命令见[验证命令](../../../docs/architecture.md#验证命令);复用仍适用的验证证据与用户已确定的验收分工,区分通过、失败、跳过与未执行
5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。交代实际结果与验证缺口;前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期,不把构建通过当作行为验收 5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。验收结论同时依据规范核对结果与行为验证证据;有规范偏差或缺少必要证据时,指出具体位置或未验证场景。前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期
6. 按授权完成提交与交付;提交前按[提交约定](../../../CONTRIBUTING.md#项目约定)准备提交信息与实际共同作者署名,提交后核对实际提交消息,PR 的 AI 披露不能替代提交署名 6. 按授权完成提交与交付;提交前按[提交约定](../../../CONTRIBUTING.md#项目约定)准备提交信息与实际共同作者署名,提交后核对实际提交消息,PR 的 AI 披露不能替代提交署名
## 测试维护 ## 测试维护
@@ -1,6 +1,6 @@
interface: interface:
display_name: "cpr-dev-guide" display_name: "cpr-dev-guide"
short_description: "开发、排障与审查入口,按行为影响匹配领域边界并验证实现" short_description: "开发、排障、审查与验收入口,按受影响行为匹配并执行领域规范"
default_prompt: "使用 $cpr-dev-guide 按请求、行为影响和实际文件匹配领域必读规范,读完职责边界再确定方案,完成已授权的开发或审查、自审与验证。" default_prompt: "使用 $cpr-dev-guide 按受影响行为和实际文件匹配领域规范,开发时据此确定方案,验收时对照最终实现和验证证据。"
policy: policy:
allow_implicit_invocation: true allow_implicit_invocation: true
@@ -21,6 +21,9 @@
普通维护和新增业务页面沿用现有设计;设计技能中的配色、字体、布局探索不覆盖项目规范,主题算法只在涉及时读取 普通维护和新增业务页面沿用现有设计;设计技能中的配色、字体、布局探索不覆盖项目规范,主题算法只在涉及时读取
- 页面和组件不添加浏览器原生提示的 `title` 属性。确需补充说明时,按内容复用已有的 Tooltip 或 Popover
- 列表行需要快速展示少量字段时,先核对列表接口已返回的字段和后端查询已读取的数据。能随当前页低成本返回的字段直接用于展示,完整详情在用户打开详情时加载
## 验收范围与收尾 ## 验收范围与收尾
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围 验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
+3
View File
@@ -27,6 +27,7 @@ updates:
# 按官方 Codex 锁文件、协议指纹或已审计 fork 固定;完成对应核对与实测后再手动升级。 # 按官方 Codex 锁文件、协议指纹或已审计 fork 固定;完成对应核对与实测后再手动升级。
ignore: ignore:
- dependency-name: aws-lc-rs - dependency-name: aws-lc-rs
- dependency-name: h2
- dependency-name: hyper - dependency-name: hyper
- dependency-name: hyper-rustls - dependency-name: hyper-rustls
- dependency-name: hyper-tls - dependency-name: hyper-tls
@@ -71,6 +72,8 @@ updates:
directories: directories:
- /deploy - /deploy
labels: [] labels: []
ignore:
- dependency-name: rust
schedule: schedule:
interval: weekly interval: weekly
day: monday day: monday
+1 -1
View File
@@ -125,7 +125,7 @@ jobs:
run: cargo clippy --all-targets --all-features --locked -- -D warnings run: cargo clippy --all-targets --all-features --locked -- -D warnings
- name: Setup nextest - name: Setup nextest
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6 uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
with: with:
tool: cargo-nextest@0.9.143 tool: cargo-nextest@0.9.143
fallback: none fallback: none
+2 -2
View File
@@ -115,7 +115,7 @@ jobs:
cache-bin: false cache-bin: false
save-if: ${{ github.event_name != 'pull_request' }} save-if: ${{ github.event_name != 'pull_request' }}
- name: Setup nextest - name: Setup nextest
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6 uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
with: with:
tool: cargo-nextest@0.9.143 tool: cargo-nextest@0.9.143
fallback: none fallback: none
@@ -434,7 +434,7 @@ jobs:
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- name: Install Cosign - name: Install Cosign
uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3 uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4
- name: Login to GHCR - name: Login to GHCR
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
ref: ${{ inputs.ref || github.event.pull_request.head.sha || github.sha }} ref: ${{ inputs.ref || github.event.pull_request.head.sha || github.sha }}
- name: Install cargo-audit - name: Install cargo-audit
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6 uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
with: with:
tool: cargo-audit@0.22.2 tool: cargo-audit@0.22.2
fallback: none fallback: none
+3 -3
View File
@@ -4,13 +4,13 @@
| 任务意图与常见说法 | 必用技能 | | 任务意图与常见说法 | 必用技能 |
| --- | --- | | --- | --- |
| 需求评估、排障、开发、修复、代码审查、改文档,包括“看下这个 Issue”“改弹窗/样式/文案”“修接口/调度/数据库” | [cpr-dev-guide](.agents/skills/cpr-dev-guide/SKILL.md),按实际操作和文件匹配规范,跨前后端同时执行 | | 需求评估、排障、开发、修复、代码审查、改文档、验收实现,包括“看下这个 Issue”“改弹窗/样式/文案”“修接口/调度/数据库”“验收一下这次改动” | [cpr-dev-guide](.agents/skills/cpr-dev-guide/SKILL.md),按实际操作和文件匹配规范,跨前后端同时执行 |
| 提交/提个 PR、准备或更新 PR、看下 PR、回复 PR 讨论、处理 PR 审查意见 | [cpr-github-pr](.agents/skills/cpr-github-pr/SKILL.md);实现自审、审查或修改同时执行 cpr-dev-guide | | 提交/提个 PR、准备或更新 PR、看下 PR、回复 PR 讨论、处理 PR 审查意见 | [cpr-github-pr](.agents/skills/cpr-github-pr/SKILL.md);实现自审、审查或修改同时执行 cpr-dev-guide |
| 提 Issue、反馈到仓库、把问题或建议整理成 Issue、补充或回复 Issue | [cpr-github-issue](.agents/skills/cpr-github-issue/SKILL.md) | | 提 Issue、反馈到仓库、把问题或建议整理成 Issue、补充或回复 Issue | [cpr-github-issue](.agents/skills/cpr-github-issue/SKILL.md) |
| 写、修或审查独立网关插件,排查插件接入、打包插件 | [cpr-plugin-dev](.agents/skills/cpr-plugin-dev/SKILL.md),同时执行 cpr-dev-guide;仅改宿主能力时由 cpr-dev-guide 加载插件边界 | | 写、修或审查独立网关插件,排查插件接入、打包插件 | [cpr-plugin-dev](.agents/skills/cpr-plugin-dev/SKILL.md),同时执行 cpr-dev-guide;仅改宿主能力时由 cpr-dev-guide 加载插件边界 |
| 发版、准备版本、发布 beta/实验版、整理发布说明、打发行 tag | [cpr-release](.agents/skills/cpr-release/SKILL.md) | | 发版、准备版本、发布 beta/实验版、整理发布说明、打发行 tag | [cpr-release](.agents/skills/cpr-release/SKILL.md) |
结合上下文识别“提交吧”“看看这个问题”等省略说法:普通 Git 提交不自动变成 PR,代码排查不自动变成 Issue;审查与发版准备不代表获准远程写入 结合当前任务判断“继续”“验收一下”等省略说法。验收代码或文档改动时执行开发指南;核对发布产物时走发版技能。普通 Git 提交不自动变成 PR,代码排查不自动变成 Issue;审查与发版准备不代表获准远程写入
首次命中技能时完整读取其 `SKILL.md`,再读取领域必读规范,之后按当前步骤补充实现、命令和示例。技能名称、描述或入口摘要不能代替首次读取的正文与必读引用;引用中明确要求“先读”“必须读取”或“执行”的规范也要落实,其他资料按需读取 首次命中技能时完整读取其 `SKILL.md`,再读取领域必读规范,之后按当前步骤补充实现、命令和示例。技能名称、描述或入口摘要不能代替首次读取的正文与必读引用;引用中明确要求“先读”“必须读取”或“执行”的规范也要落实,其他资料按需读取
@@ -26,7 +26,7 @@ Issue 和 PR 回复统一按 [GitHub 回复口吻](CONTRIBUTING.md#github-回复
### 任务延续与收尾 ### 任务延续与收尾
- 在任务上下文和压缩摘要中保留目标、授权、当前阶段、已读规范的路径与关键约束、验证命令与结果及对应代码状态、剩余事项 - 在任务上下文和压缩摘要中保留目标、授权、当前阶段、已读规范的路径与关键约束、验证命令与结果及对应代码状态、剩余事项
- 同一任务可复用实际完成的读取与验证记录;仅在规范变更、进入未覆盖领域或具体决策缺少条款时补读对应内容。输出截断只补缺失部分,上下文压缩与阶段切换本身不触发重读或重验 - 续接任务时,从记录中恢复当前步骤适用的规范与待查项,核对已有证据对应的实现。规范变更、进入新领域或缺少具体约束时补读对应条款,输出截断只补缺失部分。已有证据仍适用的检查直接复用
- 远端更新或合并冲突后,按实际变更及其依赖影响补充自审和验证,复用未受影响的证据 - 远端更新或合并冲突后,按实际变更及其依赖影响补充自审和验证,复用未受影响的证据
- 实现、自审与必要验证完成后,按[验证停止条件](CONTRIBUTING.md#验证)停止扩围;完成已获授权的剩余交付步骤并确认结果后结束 - 实现、自审与必要验证完成后,按[验证停止条件](CONTRIBUTING.md#验证)停止扩围;完成已获授权的剩余交付步骤并确认结果后结束
+1 -1
View File
@@ -55,7 +55,7 @@ AI 开发和审查入口是根目录的 [AGENTS.md](AGENTS.md)。在仓库上下
### 项目技能 ### 项目技能
仓库技能位于 `.agents/skills/`,随代码共享。技能提供执行流程,协作与审查标准仍以本文和 `AGENTS.md` 为准。 仓库技能位于 `.agents/skills/`,随代码共享。技能提供执行流程,协作与审查标准仍以本文和 `AGENTS.md` 为准。
AI 开发、排查、代码审查和文档修改必须执行 `cpr-dev-guide`;准备、创建、更新及审查 PR 必须执行 `cpr-github-pr`,不以用户是否显式点名技能为条件。PR 内修复仍须经过开发流程,不能用填写 PR 正文代替实现自审与验证 AI 开发、排查、代码审查、文档修改及对这些改动的验收必须执行 `cpr-dev-guide`;准备、创建、更新及审查 PR 必须执行 `cpr-github-pr`,不以用户是否显式点名技能为条件。PR 内修复仍须经过开发流程,不能用填写 PR 正文代替实现自审与验证
| 技能 | 用途 | 调用示例 | | 技能 | 用途 | 调用示例 |
| --- | --- | --- | | --- | --- | --- |
+43 -40
View File
@@ -153,9 +153,9 @@ dependencies = [
[[package]] [[package]]
name = "async-compression" name = "async-compression"
version = "0.4.52" version = "0.4.54"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ad47a740fb906fffdd891e8b6d5fde2511600f7bfaebd68939fa08a14999459" checksum = "0c31224bd2c09447484a1143f2fc1d871eb405789859c8e5470a3e7f95f40a18"
dependencies = [ dependencies = [
"compression-codecs", "compression-codecs",
"compression-core", "compression-core",
@@ -292,9 +292,9 @@ dependencies = [
[[package]] [[package]]
name = "aws-sdk-s3" name = "aws-sdk-s3"
version = "1.161.0" version = "1.162.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c63e3ca6e56670513469e992759f4a51041603fde329471b29c5c1f5eaeefe" checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"aws-credential-types", "aws-credential-types",
@@ -483,9 +483,9 @@ dependencies = [
[[package]] [[package]]
name = "aws-smithy-runtime-api" name = "aws-smithy-runtime-api"
version = "1.22.0" version = "1.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0b79dbb5331ccd297686df811d50ab3f39db171f5c765372a69272a0990b014" checksum = "20b0ce5fd8f8ec576f6737cf9a3a02172fddad2b90b8874577a4647fab11425c"
dependencies = [ dependencies = [
"aws-smithy-async", "aws-smithy-async",
"aws-smithy-runtime-api-macros", "aws-smithy-runtime-api-macros",
@@ -522,9 +522,9 @@ dependencies = [
[[package]] [[package]]
name = "aws-smithy-types" name = "aws-smithy-types"
version = "1.9.4" version = "1.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aff4bf014c512840b2bba80a20417b723cbd6a0a65c02e2d81f50b4268aedfc7" checksum = "2085f9721fb3755821f8db7611a67ed15f4d6fdba6785b4db8ed7cd18eebee0f"
dependencies = [ dependencies = [
"base64-simd", "base64-simd",
"bytes", "bytes",
@@ -842,9 +842,9 @@ dependencies = [
[[package]] [[package]]
name = "clap" name = "clap"
version = "4.6.8" version = "4.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a" checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3"
dependencies = [ dependencies = [
"clap_builder", "clap_builder",
"clap_derive", "clap_derive",
@@ -852,9 +852,9 @@ dependencies = [
[[package]] [[package]]
name = "clap_builder" name = "clap_builder"
version = "4.6.7" version = "4.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590"
dependencies = [ dependencies = [
"anstream", "anstream",
"anstyle", "anstyle",
@@ -864,9 +864,9 @@ dependencies = [
[[package]] [[package]]
name = "clap_derive" name = "clap_derive"
version = "4.6.8" version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a" checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
dependencies = [ dependencies = [
"heck", "heck",
"proc-macro2", "proc-macro2",
@@ -961,9 +961,9 @@ dependencies = [
[[package]] [[package]]
name = "compression-codecs" name = "compression-codecs"
version = "0.4.47" version = "0.4.49"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84f840cff84d10085260e460023934d0af699e71212b09b2a41452e8bd9cda43" checksum = "f938fc0d88fbe2c8d6f0e1ba96ba1165d89ff698e98468cd019d92cff2ecd367"
dependencies = [ dependencies = [
"compression-core", "compression-core",
"flate2", "flate2",
@@ -1109,9 +1109,9 @@ dependencies = [
[[package]] [[package]]
name = "crc32fast" name = "crc32fast"
version = "1.5.5" version = "1.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
] ]
@@ -1820,6 +1820,7 @@ dependencies = [
"gateway-protocol", "gateway-protocol",
"http", "http",
"http-body-util", "http-body-util",
"regex-automata",
"semver", "semver",
"serde", "serde",
"serde_json", "serde_json",
@@ -1887,7 +1888,7 @@ dependencies = [
"tracing-appender", "tracing-appender",
"tracing-subscriber", "tracing-subscriber",
"wiremock", "wiremock",
"yaml-rust2 0.13.0", "yaml-rust2 0.13.2",
] ]
[[package]] [[package]]
@@ -2072,9 +2073,9 @@ dependencies = [
[[package]] [[package]]
name = "h2" name = "h2"
version = "0.4.20" version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
dependencies = [ dependencies = [
"atomic-waker", "atomic-waker",
"bytes", "bytes",
@@ -2550,9 +2551,9 @@ dependencies = [
[[package]] [[package]]
name = "jsonschema" name = "jsonschema"
version = "0.61.2" version = "0.63.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e37f27df77c7887edbc5f5a59ecd8e5ec4a669319266ec1b61068667a603183" checksum = "b0802aebc749a4ef12e76aee083622b100249be0dc6d2103d84bbb2f7936a1ae"
dependencies = [ dependencies = [
"ahash", "ahash",
"bytecount", "bytecount",
@@ -2578,18 +2579,18 @@ dependencies = [
[[package]] [[package]]
name = "jsonschema-regex" name = "jsonschema-regex"
version = "0.61.2" version = "0.63.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e41151614b6c927e21982be8bef5a26741ae5a0ae6a781eedee2aa930a980e6" checksum = "ba1527289dfcb1400df61b5c591218e8e30031376671f611faecb5b9a1ff4987"
dependencies = [ dependencies = [
"regex-syntax", "regex-syntax",
] ]
[[package]] [[package]]
name = "jsonschema-value" name = "jsonschema-value"
version = "0.61.2" version = "0.63.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1515b9a91134ef67d7bac95c2d76fbc7e383c4c55ee544204ceec8088f881fef" checksum = "a95285ab129d630f01cf2f1345c28662116340fac1a35eb0795e5dbbf0ef990d"
dependencies = [ dependencies = [
"ahash", "ahash",
"bytecount", "bytecount",
@@ -2693,9 +2694,9 @@ dependencies = [
[[package]] [[package]]
name = "lru" name = "lru"
version = "0.19.0" version = "0.19.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a9f71e3591c7ec44d3e563e87bf14ddc2bada8519dca046e5b0e560cd004e2d" checksum = "d4e2a1b977b42ee8b53a2a4adbd1183431c493f1d1960b7ccd893e2f0b9407ba"
dependencies = [ dependencies = [
"hashbrown 0.17.1", "hashbrown 0.17.1",
] ]
@@ -3443,7 +3444,7 @@ dependencies = [
"hyper", "hyper",
"hyper-rustls", "hyper-rustls",
"hyper-util", "hyper-util",
"lru 0.19.0", "lru 0.19.2",
"native-tls", "native-tls",
"openssl", "openssl",
"openssl-sys", "openssl-sys",
@@ -3498,6 +3499,8 @@ dependencies = [
"jsonwebtoken", "jsonwebtoken",
"p256", "p256",
"reqwest", "reqwest",
"rustls",
"rustls-native-certs",
"semver", "semver",
"serde", "serde",
"serde_json", "serde_json",
@@ -3691,9 +3694,9 @@ dependencies = [
[[package]] [[package]]
name = "redis" name = "redis"
version = "1.8.2" version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bef8fa589dd53a8a379a7856de1365d0a1be50c6b8aebb5c01c1ec441a2c509" checksum = "c85db9332bbc47e826283f0a6058d747c478ed2278976279cefd22154d541b98"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"arcstr", "arcstr",
@@ -3747,9 +3750,9 @@ dependencies = [
[[package]] [[package]]
name = "referencing" name = "referencing"
version = "0.61.2" version = "0.63.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a028057ef852c58a42d75e09da87b5e733f4030f4c7411728955e4f87203a577" checksum = "858eb92e3a3c1d120695a04d5c6e8861915ee4394b8f77c90adbf686d6ddbf6e"
dependencies = [ dependencies = [
"ahash", "ahash",
"fluent-uri", "fluent-uri",
@@ -4212,9 +4215,9 @@ checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"
[[package]] [[package]]
name = "sha2" name = "sha2"
version = "0.11.1" version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"cpufeatures 0.3.0", "cpufeatures 0.3.0",
@@ -5648,9 +5651,9 @@ dependencies = [
[[package]] [[package]]
name = "yaml-rust2" name = "yaml-rust2"
version = "0.13.0" version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57e5b818a27a4cd30884ea380857a5e56f7ec3ba24a3990a3cc0b95af3238e18" checksum = "4a8af4469040402b7fe43c26575bab9a3069f0717c4a2931ecf4fb8728ee4cec"
dependencies = [ dependencies = [
"arraydeque", "arraydeque",
"encoding_rs", "encoding_rs",
@@ -5776,9 +5779,9 @@ dependencies = [
[[package]] [[package]]
name = "zip" name = "zip"
version = "9.8.0" version = "9.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "721c8158b9503b2660291ad3056a20f722deaeed21bb908a9a363d7e17b34f0e" checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce"
dependencies = [ dependencies = [
"constant_time_eq", "constant_time_eq",
"crc32fast", "crc32fast",
+1 -1
View File
@@ -45,7 +45,7 @@ opt-level = 2
[profile.dev.package.blake2] [profile.dev.package.blake2]
opt-level = 2 opt-level = 2
[profile.dev.package."sha2@0.11.1"] [profile.dev.package.sha2]
opt-level = 2 opt-level = 2
[profile.dev.package."miniz_oxide@0.9.1"] [profile.dev.package."miniz_oxide@0.9.1"]
@@ -42,6 +42,7 @@ pub struct ProviderAccountCapabilities {
/// 导入时应用的账号设置;名称只覆盖单账号导入,其余设置统一应用 /// 导入时应用的账号设置;名称只覆盖单账号导入,其余设置统一应用
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountImportSettings { pub struct AccountImportSettings {
pub platform_icon: Option<String>,
pub name: Option<String>, pub name: Option<String>,
pub notes: Option<String>, pub notes: Option<String>,
pub enabled: bool, pub enabled: bool,
@@ -54,7 +55,7 @@ pub struct AccountImportSettings {
/// 账号列表排序字段 /// 账号列表排序字段
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccountSortField { pub enum AccountSortField {
Email, Name,
Status, Status,
PlanType, PlanType,
Usage, Usage,
@@ -222,6 +223,7 @@ pub struct AccountPage {
/// 同一状态快照下的账号事实与唯一状态投影 /// 同一状态快照下的账号事实与唯一状态投影
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountPageItem { pub struct AccountPageItem {
pub platform_icon: Option<String>,
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>, pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
pub account: AccountRecord, pub account: AccountRecord,
pub projection: AccountStatusProjection, pub projection: AccountStatusProjection,
@@ -240,6 +242,7 @@ pub struct AccountCapacity {
/// 账号可编辑事实的一次性替换命令 /// 账号可编辑事实的一次性替换命令
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpdateAccount { pub struct UpdateAccount {
pub platform_icon: Option<String>,
pub account_id: String, pub account_id: String,
/// 缺省保留名称,空字符串清除名称并使用邮箱展示 /// 缺省保留名称,空字符串清除名称并使用邮箱展示
pub name: Option<String>, pub name: Option<String>,
@@ -350,7 +350,9 @@ impl ClientKeyBudgetWindowPeriod {
/// 手动对齐只需要账号身份,列表不读取凭据、额度或用量 /// 手动对齐只需要账号身份,列表不读取凭据、额度或用量
#[derive(serde::Serialize, Debug)] #[derive(serde::Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct BudgetReferenceAccount { pub struct BudgetReferenceAccount {
pub platform_icon: Option<String>,
pub id: String, pub id: String,
pub name: String, pub name: String,
pub email: Option<String>, pub email: Option<String>,
@@ -783,6 +783,7 @@ pub struct AccountRequestBucket {
/// Dashboard 中一个账号的完整用量事实 /// Dashboard 中一个账号的完整用量事实
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct DashboardAccountUsage { pub struct DashboardAccountUsage {
pub platform_icon: Option<String>,
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>, pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
pub account_id: String, pub account_id: String,
pub provider_kind: String, pub provider_kind: String,
@@ -888,11 +889,14 @@ impl UsageErrorOrigin {
} }
/// 使用记录表格的窄读模型 /// 使用记录表格的窄读模型
#[derive(Debug, Clone, PartialEq)] #[derive(Clone, PartialEq)]
pub struct UsageListRecord { pub struct UsageListRecord {
pub platform_icon: Option<String>,
pub outcome: RequestOutcome, pub outcome: RequestOutcome,
/// 已保存的上游错误对象含非空字符串 code、type 或 message /// 已保存的上游错误对象含非空字符串 code、type 或 message
pub has_upstream_error: bool, pub has_upstream_error: bool,
pub upstream_error_message: Option<String>,
pub retry_after_ms: Option<u64>,
pub error_code: Option<String>, pub error_code: Option<String>,
pub error_message: Option<String>, pub error_message: Option<String>,
pub error_kind: Option<String>, pub error_kind: Option<String>,
@@ -959,6 +963,17 @@ pub struct UsageListRecord {
pub started_at: DateTime<Utc>, pub started_at: DateTime<Utc>,
} }
// 上游错误原文只交付给管理端,避免整行调试输出带出正文
impl std::fmt::Debug for UsageListRecord {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("UsageListRecord")
.field("id", &self.id)
.field("outcome", &self.outcome)
.finish_non_exhaustive()
}
}
/// 受控请求详情中的上游错误字段,不参与错误分类或普通日志输出 /// 受控请求详情中的上游错误字段,不参与错误分类或普通日志输出
#[derive(Clone, PartialEq)] #[derive(Clone, PartialEq)]
pub struct UsageUpstreamError { pub struct UsageUpstreamError {
@@ -1167,7 +1182,9 @@ pub struct DiagnosticsObservation {
pub struct DiagnosticObservation { pub struct DiagnosticObservation {
pub key: String, pub key: String,
pub name: String, pub name: String,
pub account_provider_kind: Option<String>, pub account_email: Option<String>,
pub providers: Vec<String>,
pub platform_icon: Option<String>,
pub account_authentication_kind: Option<String>, pub account_authentication_kind: Option<String>,
pub account_plan_type: Option<String>, pub account_plan_type: Option<String>,
pub account_plan_type_display: Option<String>, pub account_plan_type_display: Option<String>,
@@ -1640,8 +1657,11 @@ pub struct UsageInsight {
/// 已完成分母计算的诊断项 /// 已完成分母计算的诊断项
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct DiagnosticsItem { pub struct DiagnosticsItem {
pub providers: Vec<String>,
pub platform_icon: Option<String>,
pub key: String, pub key: String,
pub name: String, pub name: String,
pub account_email: Option<String>,
pub account_authentication_kind: Option<String>, pub account_authentication_kind: Option<String>,
pub account_plan_type: Option<String>, pub account_plan_type: Option<String>,
/// 仅账号维度补充当前互联识别结果 /// 仅账号维度补充当前互联识别结果
@@ -1319,6 +1319,7 @@ impl fmt::Debug for ProviderExport {
/// 统一账号目录的一行完整结果 /// 统一账号目录的一行完整结果
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct AccountDirectoryItem { pub struct AccountDirectoryItem {
pub platform_icon: Option<String>,
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>, pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
pub account: AccountRecord, pub account: AccountRecord,
pub capacity: super::accounts::AccountCapacity, pub capacity: super::accounts::AccountCapacity,
@@ -27,6 +27,7 @@ pub struct ProxyListQuery {
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProxyAccountRef { pub struct ProxyAccountRef {
pub platform_icon: Option<String>,
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>, pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
pub id: String, pub id: String,
pub name: String, pub name: String,
@@ -71,6 +71,7 @@ pub struct RuntimeSettingsValues {
pub usage_retention_days: u32, pub usage_retention_days: u32,
pub ops_event_retention_days: u32, pub ops_event_retention_days: u32,
pub audit_retention_days: u32, pub audit_retention_days: u32,
pub prompt_rewrite_rules: Vec<gateway_core::settings::prompt_rewrite::PromptRewriteRule>,
pub account_error_protection: gateway_core::account::AccountErrorProtection, pub account_error_protection: gateway_core::account::AccountErrorProtection,
pub account_warmup_enabled: bool, pub account_warmup_enabled: bool,
pub account_warmup_cron: String, pub account_warmup_cron: String,
@@ -192,6 +193,9 @@ impl From<RuntimeSettings> for ReplaceRuntimeSettings {
impl RuntimeSettingsValues { impl RuntimeSettingsValues {
/// 校验共同事实,返回字段名供边界转换错误;SQL 类型转换仍由 Store 处理 /// 校验共同事实,返回字段名供边界转换错误;SQL 类型转换仍由 Store 处理
pub fn validate(&self) -> Result<(), &'static str> { pub fn validate(&self) -> Result<(), &'static str> {
for rule in &self.prompt_rewrite_rules {
rule.validate().map_err(|_| "prompt_rewrite_rules")?;
}
if !(1..=1440).contains(&self.reset_credit_lead_minutes) { if !(1..=1440).contains(&self.reset_credit_lead_minutes) {
return Err("reset_credit_lead_minutes"); return Err("reset_credit_lead_minutes");
} }
@@ -25,6 +25,13 @@ pub(super) fn register(
}}; }};
} }
register!(Load, load, (), ()); register!(Load, load, (), ());
register!(
PreviewPromptRewrite,
preview_prompt_rewrite,
gateway_core::settings::prompt_rewrite::PromptRewritePreviewRequest,
request,
request
);
register!( register!(
PreviewPrivacyPolicy, PreviewPrivacyPolicy,
preview_privacy_policy, preview_privacy_policy,
@@ -513,6 +513,7 @@ impl DefaultAccountsService {
lookback, lookback,
); );
Ok(AccountDirectoryItem { Ok(AccountDirectoryItem {
platform_icon: stored.platform_icon,
protection_rules: stored.protection_rules, protection_rules: stored.protection_rules,
capacity: super::peer_link::upstream::account_capacity( capacity: super::peer_link::upstream::account_capacity(
&stored.account, &stored.account,
@@ -647,6 +648,7 @@ impl AccountsService for DefaultAccountsService {
lookback, lookback,
); );
Ok(AccountDirectoryItem { Ok(AccountDirectoryItem {
platform_icon: item.platform_icon,
protection_rules: item.protection_rules, protection_rules: item.protection_rules,
capacity: crate::model::accounts::AccountCapacity { capacity: crate::model::accounts::AccountCapacity {
used_slots: in_flight used_slots: in_flight
@@ -1340,7 +1342,8 @@ impl AccountsService for DefaultAccountsService {
.map(ToOwned::to_owned); .map(ToOwned::to_owned);
let upstream_body = error let upstream_body = error
.upstream_response() .upstream_response()
.map(|response| String::from_utf8_lossy(response.body()).into_owned()); .and_then(gateway_core::engine::probe::AccountProbeUpstreamResponse::body)
.map(|body| String::from_utf8_lossy(body).into_owned());
let message = error.client_message().to_owned(); let message = error.client_message().to_owned();
vec![AccountConnectionTestEvent::Failed { vec![AccountConnectionTestEvent::Failed {
source: error.source(), source: error.source(),
@@ -4,7 +4,7 @@ mod flow;
use std::sync::Arc; use std::sync::Arc;
use gateway_core::{routing::ProviderKind, runtime::SnapshotControl}; use gateway_core::{account::ProviderAccountId, routing::ProviderKind, runtime::SnapshotControl};
use crate::{ use crate::{
model::AdminError, model::AdminError,
@@ -40,6 +40,20 @@ impl CredentialsService {
} }
} }
/// 已有账号的凭据操作按已保存的归属选择 Provider
pub async fn for_account(
&self,
account_id: &ProviderAccountId,
) -> Result<ProviderCredentials, AdminError> {
let account = self
.accounts
.load_account_record(account_id)
.await
.map_err(|error| super::map_store_error(error, "provider credentials"))?
.ok_or_else(|| AdminError::not_found("账号不存在"))?;
self.for_provider(&account.provider_kind)
}
pub fn for_provider(&self, kind: &ProviderKind) -> Result<ProviderCredentials, AdminError> { pub fn for_provider(&self, kind: &ProviderKind) -> Result<ProviderCredentials, AdminError> {
let provider = self let provider = self
.providers .providers
@@ -379,12 +379,15 @@ impl ObservabilityService for DefaultObservabilityService {
account_upstream_peer: peers.get(&item.key).copied(), account_upstream_peer: peers.get(&item.key).copied(),
key: item.key, key: item.key,
name: item.name, name: item.name,
account_email: item.account_email,
account_authentication_kind: item.account_authentication_kind, account_authentication_kind: item.account_authentication_kind,
account_plan_type_display: self.historical_plan_display( account_plan_type_display: self.historical_plan_display(
item.account_plan_type_display, item.account_plan_type_display,
item.account_provider_kind.as_deref(), item.providers.first().map(String::as_str),
item.account_plan_type.as_deref(), item.account_plan_type.as_deref(),
), ),
providers: item.providers,
platform_icon: item.platform_icon,
account_plan_type: item.account_plan_type, account_plan_type: item.account_plan_type,
request_count: item.request_count, request_count: item.request_count,
success_count: item.success_count, success_count: item.success_count,
@@ -22,6 +22,17 @@ use super::{map_store_error, publish_committed};
/// API 消费的 Runtime settings 管理服务 /// API 消费的 Runtime settings 管理服务
#[async_trait] #[async_trait]
pub trait SettingsService: Send + Sync { pub trait SettingsService: Send + Sync {
async fn preview_prompt_rewrite(
&self,
request: gateway_core::settings::prompt_rewrite::PromptRewritePreviewRequest,
) -> Result<gateway_core::settings::prompt_rewrite::PromptRewritePreviewResult, AdminError>
{
request
.rule
.preview(&request.text)
.map_err(|_| AdminError::invalid("正则表达式无效或超出编译大小限制"))
}
async fn preview_privacy_policy( async fn preview_privacy_policy(
&self, &self,
_request: gateway_core::settings::privacy::PrivacyPreviewRequest, _request: gateway_core::settings::privacy::PrivacyPreviewRequest,
@@ -117,6 +128,7 @@ fn validate_settings(command: &ReplaceRuntimeSettings) -> Result<(), AdminError>
) )
.map_err(|_| AdminError::invalid("运行时设置不满足约束"))?; .map_err(|_| AdminError::invalid("运行时设置不满足约束"))?;
command.values.validate().map_err(|field| match field { command.values.validate().map_err(|field| match field {
"prompt_rewrite_rules" => AdminError::invalid("正则表达式无效或超出编译大小限制"),
"openai_websocket_pool.fast_path_budget_ms" => { "openai_websocket_pool.fast_path_budget_ms" => {
AdminError::invalid("WS 建连等待时间须为 1–15000 毫秒") AdminError::invalid("WS 建连等待时间须为 1–15000 毫秒")
} }
@@ -740,6 +740,7 @@ impl FakeAccountStore {
last_error_message: account.last_error_message.clone(), last_error_message: account.last_error_message.clone(),
}; };
AccountPageItem { AccountPageItem {
platform_icon: None,
protection_rules: Vec::new(), protection_rules: Vec::new(),
capacity: gateway_admin::model::accounts::AccountCapacity { capacity: gateway_admin::model::accounts::AccountCapacity {
used_slots: None, used_slots: None,
@@ -1229,6 +1230,7 @@ impl SettingsStore for StaticSettingsStore {
usage_retention_days: 30, usage_retention_days: 30,
ops_event_retention_days: 30, ops_event_retention_days: 30,
audit_retention_days: 30, audit_retention_days: 30,
prompt_rewrite_rules: Vec::new(),
account_error_protection: gateway_core::account::AccountErrorProtection::default(), account_error_protection: gateway_core::account::AccountErrorProtection::default(),
account_warmup_enabled: false, account_warmup_enabled: false,
account_warmup_cron: "0 8 * * *".to_owned(), account_warmup_cron: "0 8 * * *".to_owned(),
@@ -1894,6 +1896,7 @@ async fn accounts_update_should_commit_then_release_disabled_account_and_publish
.update( .update(
&context("update-request"), &context("update-request"),
UpdateAccount { UpdateAccount {
platform_icon: None,
name: None, name: None,
notes: None, notes: None,
model_access: Default::default(), model_access: Default::default(),
@@ -1934,6 +1937,7 @@ async fn accounts_update_should_not_notify_provider_when_store_commit_fails() {
.update( .update(
&context("update-failure"), &context("update-failure"),
UpdateAccount { UpdateAccount {
platform_icon: None,
name: None, name: None,
notes: None, notes: None,
model_access: Default::default(), model_access: Default::default(),
@@ -4016,6 +4020,7 @@ fn unsupported() -> ProviderAdminError {
pub(super) fn import_settings() -> gateway_admin::model::accounts::AccountImportSettings { pub(super) fn import_settings() -> gateway_admin::model::accounts::AccountImportSettings {
gateway_admin::model::accounts::AccountImportSettings { gateway_admin::model::accounts::AccountImportSettings {
platform_icon: None,
name: None, name: None,
notes: Some("团队备用".to_owned()), notes: Some("团队备用".to_owned()),
model_access: Default::default(), model_access: Default::default(),
@@ -1,5 +1,108 @@
//! 按 Provider 组织凭据导入、授权与提交边界测试 //! 验证账号归属分派,并组织凭据导入、授权与提交边界测试
mod openai; mod openai;
mod peer; mod peer;
mod xai; mod xai;
use gateway_admin::model::{
AdminErrorKind,
provider_credentials::{CredentialMutation, RotateCredential},
};
use gateway_core::account::ProviderAccountId;
use super::{
AdminHarness,
accounts::{
FakeAccountStore, FakeProviderAdmin, account_record, context, document, events, recorded,
revision,
},
};
#[tokio::test]
async fn account_rotation_should_dispatch_by_saved_provider_for_each_authentication_kind() {
for kind in ["openai", "xai", "antigravity"] {
for authentication in ["oauth", "api_key"] {
let store_events = events();
let mut account = account_record(kind);
account.authentication_kind = authentication.to_owned();
if authentication == "api_key" {
account.upstream_user_id = None;
account.has_refresh_token = false;
account.access_token_expires_at = None;
account.next_refresh_at = None;
}
let account_id = ProviderAccountId::new(account.id.clone()).unwrap();
let store = FakeAccountStore::with_account(account, store_events.clone());
let mut harness = AdminHarness::new().accounts(store.clone());
let mut provider_events = Vec::new();
for registered_kind in ["openai", "xai", "antigravity"] {
let calls = events();
harness = harness.provider(FakeProviderAdmin::new(registered_kind, calls.clone()));
provider_events.push((registered_kind, calls));
}
let services = harness.build().await;
let result = services
.credentials()
.for_account(&account_id)
.await
.expect("select saved provider")
.rotate(RotateCredential {
mutation: CredentialMutation {
context: context("rotate-account-connection"),
account_id: account_id.clone(),
},
settings: None,
provider_material: document(),
})
.await
.expect("rotate selected account");
assert_eq!(result.account_id, account_id);
assert_eq!(result.credential_revision, Some(revision(2)));
assert_eq!(store.audit_requests(), ["rotate-account-connection"]);
assert_eq!(
recorded(&store_events),
[
"store.load_account_record",
"store.credential_details",
"store.commit_rotation",
]
);
for (registered_kind, calls) in provider_events {
let expected: &[&str] = if registered_kind == kind {
&[
"provider.prepare_rotation",
"guard.finish",
"provider.account_facts_changed",
]
} else {
&[]
};
assert_eq!(recorded(&calls), expected, "{kind}/{authentication}");
}
}
}
}
#[tokio::test]
async fn missing_account_should_stop_credential_dispatch_before_provider_or_store_mutation() {
let store_events = events();
let provider_events = events();
let store = FakeAccountStore::new("openai", store_events.clone());
let mut harness = AdminHarness::new().accounts(store.clone());
for kind in ["openai", "xai", "antigravity"] {
harness = harness.provider(FakeProviderAdmin::new(kind, provider_events.clone()));
}
let services = harness.build().await;
let error = services
.credentials()
.for_account(&ProviderAccountId::new("acct_missing").unwrap())
.await
.err()
.expect("missing account must fail before selecting a provider");
assert_eq!(error.kind(), AdminErrorKind::NotFound);
assert_eq!(recorded(&store_events), ["store.load_account_record"]);
assert!(recorded(&provider_events).is_empty());
assert!(store.audit_requests().is_empty());
}
@@ -62,6 +62,7 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
usage_retention_days: 31, usage_retention_days: 31,
ops_event_retention_days: 30, ops_event_retention_days: 30,
audit_retention_days: 90, audit_retention_days: 90,
prompt_rewrite_rules: Vec::new(),
account_error_protection: gateway_core::account::AccountErrorProtection { account_error_protection: gateway_core::account::AccountErrorProtection {
enabled, enabled,
probe_enabled, probe_enabled,
@@ -516,6 +516,7 @@ async fn dashboard_should_preserve_provider_plan_names() {
*store.account_usage.lock().unwrap() = plans *store.account_usage.lock().unwrap() = plans
.iter() .iter()
.map(|(plan, _)| DashboardAccountUsage { .map(|(plan, _)| DashboardAccountUsage {
platform_icon: None,
upstream: None, upstream: None,
account_id: format!("account-{plan}"), account_id: format!("account-{plan}"),
provider_kind: "openai".to_owned(), provider_kind: "openai".to_owned(),
@@ -366,6 +366,7 @@ impl SettingsStore for FixtureSettingsStore {
usage_retention_days: 31, usage_retention_days: 31,
ops_event_retention_days: 30, ops_event_retention_days: 30,
audit_retention_days: 30, audit_retention_days: 30,
prompt_rewrite_rules: Vec::new(),
account_error_protection: gateway_core::account::AccountErrorProtection::default(), account_error_protection: gateway_core::account::AccountErrorProtection::default(),
account_warmup_enabled: false, account_warmup_enabled: false,
account_warmup_cron: "0 8 * * *".to_owned(), account_warmup_cron: "0 8 * * *".to_owned(),
@@ -450,8 +451,11 @@ fn total_record(
now: DateTime<Utc>, now: DateTime<Utc>,
) -> UsageListRecord { ) -> UsageListRecord {
UsageListRecord { UsageListRecord {
platform_icon: None,
provider_account_upstream_peer: None, provider_account_upstream_peer: None,
has_upstream_error: false, has_upstream_error: false,
upstream_error_message: None,
retry_after_ms: None,
error_code: None, error_code: None,
error_message: None, error_message: None,
error_kind: None, error_kind: None,
@@ -541,12 +545,14 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
caller_error_count: 0, caller_error_count: 0,
retry_count: 0, retry_count: 0,
retried_request_count: 0, retried_request_count: 0,
account_provider_kind: None, providers: vec![],
platform_icon: None,
account_authentication_kind: None, account_authentication_kind: None,
account_plan_type: None, account_plan_type: None,
account_plan_type_display: None, account_plan_type_display: None,
key: name.to_owned(), key: name.to_owned(),
name: name.to_owned(), name: name.to_owned(),
account_email: None,
request_count, request_count,
success_count: request_count, success_count: request_count,
failure_count: 0, failure_count: 0,
@@ -355,6 +355,7 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() {
.provider(provider.clone()) .provider(provider.clone())
.proxies(Arc::new(TestProxies { .proxies(Arc::new(TestProxies {
accounts: Some(vec![ProxyAccountRef { accounts: Some(vec![ProxyAccountRef {
platform_icon: None,
upstream: None, upstream: None,
id: "acct_plan".to_owned(), id: "acct_plan".to_owned(),
name: "套餐测试".to_owned(), name: "套餐测试".to_owned(),
@@ -56,7 +56,10 @@ impl VisitMut for WireTypes {
} }
let last = path.path.segments.last().unwrap().clone(); let last = path.path.segments.last().unwrap().clone();
*ty = match last.ident.to_string().as_str() { *ty = match last.ident.to_string().as_str() {
"DateTime" | "Tz" | "TokenPrice" | "AdminApiKey" => parse_quote!(String), "DateTime" | "Tz" | "TokenPrice" | "AdminApiKey" | "ProviderKind"
| "PromptPattern" => {
parse_quote!(String)
}
"Value" => parse_quote!(serde_json::Value), "Value" => parse_quote!(serde_json::Value),
"OpaqueProviderData" => parse_quote!(serde_json::Map<String, serde_json::Value>), "OpaqueProviderData" => parse_quote!(serde_json::Map<String, serde_json::Value>),
_ => Type::Path(syn::TypePath { _ => Type::Path(syn::TypePath {
@@ -80,6 +83,9 @@ fn contract_type(mut item: Item, name: &str) -> Item {
| "ReplaceRuntimeSettings" | "ReplaceRuntimeSettings"
| "AdminApiKeyMutation" | "AdminApiKeyMutation"
| "RegeneratedAdminApiKey" | "RegeneratedAdminApiKey"
| "PromptRewriteRule"
| "PromptRewritePreviewRequest"
| "PromptRewritePreviewResult"
| "CodexPrivacyPolicy" | "CodexPrivacyPolicy"
| "PrivacyRule" | "PrivacyRule"
| "PrivacyStep" | "PrivacyStep"
@@ -113,6 +119,15 @@ fn contract_type(mut item: Item, name: &str) -> Item {
if let Some(fields) = fields { if let Some(fields) = fields {
for field in fields { for field in fields {
field.vis = parse_quote!(pub); field.vis = parse_quote!(pub);
// 非空名称与前缀由宿主在接收设置时校验,SDK 只描述字符串合同
if name == "PromptRewriteRule"
&& field
.ident
.as_ref()
.is_some_and(|id| id == "pattern" || id == "name")
{
field.attrs.retain(|attr| !attr.path().is_ident("serde"));
}
} }
} }
if let Item::Enum(item) = &mut item { if let Item::Enum(item) = &mut item {
@@ -225,6 +240,15 @@ fn sdk_settings_contract_matches_host_declarations() {
"AccountErrorOperator", "AccountErrorOperator",
][..], ][..],
), ),
(
"../gateway-core/src/settings/prompt_rewrite.rs",
&[
"PromptRewriteRule",
"PromptMatchMode",
"PromptRewritePreviewRequest",
"PromptRewritePreviewResult",
][..],
),
( (
"../gateway-core/src/settings/websocket.rs", "../gateway-core/src/settings/websocket.rs",
&["OpenAiWebSocketPoolSettings"][..], &["OpenAiWebSocketPoolSettings"][..],
@@ -376,6 +376,7 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
usage_retention_days: 31, usage_retention_days: 31,
ops_event_retention_days: 30, ops_event_retention_days: 30,
audit_retention_days: 30, audit_retention_days: 30,
prompt_rewrite_rules: Vec::new(),
account_error_protection: account_error_protection:
gateway_core::account::AccountErrorProtection::default(), gateway_core::account::AccountErrorProtection::default(),
account_warmup_enabled: false, account_warmup_enabled: false,
@@ -2,6 +2,25 @@
use super::*; use super::*;
pub(super) async fn validate_platform_icons(
state: &impl crate::SessionState,
names: &[&str],
) -> Result<(), AdminError> {
if names.iter().any(|name| !name.is_empty()) {
let catalog = state
.platform_icon_names()
.await
.map_err(|_| AdminError::service_unavailable())?;
if names
.iter()
.any(|&name| !name.is_empty() && !catalog.contains(name))
{
return Err(map_wire_error(WireValidationError::new("platformIcon")));
}
}
Ok(())
}
fn validate_account_notes(notes: Option<&str>) -> Result<(), WireValidationError> { fn validate_account_notes(notes: Option<&str>) -> Result<(), WireValidationError> {
if notes.is_some_and(|notes| { if notes.is_some_and(|notes| {
notes.chars().count() > 500 notes.chars().count() > 500
@@ -22,6 +41,8 @@ fn parse_provider(value: &str) -> Result<ProviderKind, WireValidationError> {
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)] #[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AccountImportSettingsRequest { pub struct AccountImportSettingsRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_icon: Option<String>,
pub name: Option<String>, pub name: Option<String>,
pub notes: Option<String>, pub notes: Option<String>,
pub enabled: bool, pub enabled: bool,
@@ -52,6 +73,7 @@ impl AccountImportSettingsRequest {
.name .name
.map(|name| name.trim().to_owned()) .map(|name| name.trim().to_owned())
.filter(|name| !name.is_empty()), .filter(|name| !name.is_empty()),
platform_icon: self.platform_icon,
notes: self.notes, notes: self.notes,
enabled: self.enabled, enabled: self.enabled,
concurrency_limit: parse_concurrency_limit(self.concurrency_limit)?, concurrency_limit: parse_concurrency_limit(self.concurrency_limit)?,
@@ -213,6 +235,7 @@ fn validate_authorization_flow(
#[derive(Clone, Deserialize)] #[derive(Clone, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)] #[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UpdateAccountRequest { pub struct UpdateAccountRequest {
pub platform_icon: Option<String>,
pub connection: Option<AccountConnectionUpdateRequest>, pub connection: Option<AccountConnectionUpdateRequest>,
pub outbound_proxy_id: Option<String>, pub outbound_proxy_id: Option<String>,
pub account_id: String, pub account_id: String,
@@ -253,6 +276,7 @@ impl UpdateAccountRequest {
outbound_proxy: super::wire::proxy_selection(self.outbound_proxy_id)?, outbound_proxy: super::wire::proxy_selection(self.outbound_proxy_id)?,
account_id: self.account_id, account_id: self.account_id,
name: self.name.map(|name| name.trim().to_owned()), name: self.name.map(|name| name.trim().to_owned()),
platform_icon: self.platform_icon,
notes: self.notes, notes: self.notes,
enabled: self.enabled, enabled: self.enabled,
concurrency_limit: parse_concurrency_limit(self.concurrency_limit)?, concurrency_limit: parse_concurrency_limit(self.concurrency_limit)?,
@@ -264,13 +288,13 @@ impl UpdateAccountRequest {
} }
} }
/// 编辑 OpenAI 账号的连接设置;OAuth 仅接受传输方式 /// 连接字段由 Provider 按账号类型校验,未提供的选项不注入凭据文档
#[derive(Clone, Deserialize)] #[derive(Clone, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)] #[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AccountConnectionUpdateRequest { pub struct AccountConnectionUpdateRequest {
pub protocol: Option<String>, pub protocol: Option<String>,
pub base_url: Option<String>, pub base_url: Option<String>,
pub transport: String, pub transport: Option<String>,
pub api_key: Option<String>, pub api_key: Option<String>,
} }
@@ -286,7 +310,11 @@ impl AccountConnectionUpdateRequest {
if let Some(base_url) = &self.base_url { if let Some(base_url) = &self.base_url {
require_text(base_url, 2048, "connection.baseUrl")?; require_text(base_url, 2048, "connection.baseUrl")?;
} }
if !matches!(self.transport.as_str(), "http" | "prefer_websocket") { if self
.transport
.as_deref()
.is_some_and(|transport| !matches!(transport, "http" | "prefer_websocket"))
{
return Err(WireValidationError::new("connection.transport")); return Err(WireValidationError::new("connection.transport"));
} }
if self.api_key.as_ref().is_some_and(|key| { if self.api_key.as_ref().is_some_and(|key| {
@@ -300,8 +328,10 @@ impl AccountConnectionUpdateRequest {
} }
fn into_document(self) -> ProviderDocument { fn into_document(self) -> ProviderDocument {
let mut material = let mut material = Map::new();
Map::from_iter([("transport".to_owned(), Value::String(self.transport))]); if let Some(transport) = self.transport {
material.insert("transport".to_owned(), Value::String(transport));
}
if let Some(protocol) = self.protocol { if let Some(protocol) = self.protocol {
material.insert("protocol".to_owned(), Value::String(protocol)); material.insert("protocol".to_owned(), Value::String(protocol));
} }
@@ -182,6 +182,15 @@ async fn import_accounts<S>(
where where
S: SessionState + Send + Sync, S: SessionState + Send + Sync,
{ {
super::credentials::validate_platform_icons(
&state,
request
.settings
.as_ref()
.and_then(|settings| settings.platform_icon.as_deref())
.as_slice(),
)
.await?;
let (provider, command) = request let (provider, command) = request
.into_command(auth.context().mutation_context()) .into_command(auth.context().mutation_context())
.map_err(map_wire_error)?; .map_err(map_wire_error)?;
@@ -232,6 +241,15 @@ async fn complete_account_authorization<S>(
where where
S: SessionState + Send + Sync, S: SessionState + Send + Sync,
{ {
super::credentials::validate_platform_icons(
&state,
request
.settings
.as_ref()
.and_then(|settings| settings.platform_icon.as_deref())
.as_slice(),
)
.await?;
let (provider, command) = request let (provider, command) = request
.into_command(auth.context().mutation_context()) .into_command(auth.context().mutation_context())
.map_err(map_wire_error)?; .map_err(map_wire_error)?;
@@ -255,16 +273,21 @@ async fn update_account<S>(
where where
S: SessionState + Send + Sync, S: SessionState + Send + Sync,
{ {
super::credentials::validate_platform_icons(
&state,
request.platform_icon.as_deref().as_slice(),
)
.await?;
let (command, connection) = request.into_command().map_err(map_wire_error)?; let (command, connection) = request.into_command().map_err(map_wire_error)?;
let context = auth.context().mutation_context(); let context = auth.context().mutation_context();
let result = if let Some(provider_material) = connection { let result = if let Some(provider_material) = connection {
let provider = ProviderKind::new("openai").map_err(|_| AdminError::internal())?;
let account_id = ProviderAccountId::new(command.account_id.clone()) let account_id = ProviderAccountId::new(command.account_id.clone())
.map_err(|_| AdminError::internal())?; .map_err(|_| AdminError::internal())?;
let result = state let result = state
.admin_services() .admin_services()
.credentials() .credentials()
.for_provider(&provider) .for_account(&account_id)
.await
.map_err(map_service_error)? .map_err(map_service_error)?
.rotate(RotateCredential { .rotate(RotateCredential {
mutation: CredentialMutation { mutation: CredentialMutation {
@@ -149,6 +149,12 @@ where
if request.items.is_empty() || request.items.len() > MAX_IMPORT_TASK_ITEMS { if request.items.is_empty() || request.items.len() > MAX_IMPORT_TASK_ITEMS {
return Err(map_wire_error(WireValidationError::new("items"))); return Err(map_wire_error(WireValidationError::new("items")));
} }
let icons: Vec<_> = request
.items
.iter()
.filter_map(|item| item.settings.as_ref()?.platform_icon.as_deref())
.collect();
super::credentials::validate_platform_icons(&state, &icons).await?;
let encoded = serde_json::to_vec(&request.items) let encoded = serde_json::to_vec(&request.items)
.map_err(|_| map_wire_error(WireValidationError::new("items")))?; .map_err(|_| map_wire_error(WireValidationError::new("items")))?;
let fingerprint = Sha256::digest(&encoded).into(); let fingerprint = Sha256::digest(&encoded).into();
@@ -67,6 +67,7 @@ pub(super) fn account_view(
time: crate::time::TimePresenter, time: crate::time::TimePresenter,
) -> AccountView { ) -> AccountView {
let AccountDirectoryItem { let AccountDirectoryItem {
platform_icon,
account, account,
capacity, capacity,
capabilities, capabilities,
@@ -111,6 +112,7 @@ pub(super) fn account_view(
let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time); let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time);
quota.protection_rules = protection_rules; quota.protection_rules = protection_rules;
AccountView { AccountView {
platform_icon,
quota_settings: account.quota_settings, quota_settings: account.quota_settings,
auto_use_quota_credits: account.auto_use_quota_credits, auto_use_quota_credits: account.auto_use_quota_credits,
upstream, upstream,
@@ -203,7 +203,7 @@ fn parse_provider(value: &str) -> Result<Option<ProviderKind>, WireValidationErr
fn parse_sort_field(value: &str) -> Option<AccountSortField> { fn parse_sort_field(value: &str) -> Option<AccountSortField> {
match value.trim() { match value.trim() {
"email" => Some(AccountSortField::Email), "name" => Some(AccountSortField::Name),
"status" => Some(AccountSortField::Status), "status" => Some(AccountSortField::Status),
"planType" => Some(AccountSortField::PlanType), "planType" => Some(AccountSortField::PlanType),
"usage" => Some(AccountSortField::Usage), "usage" => Some(AccountSortField::Usage),
@@ -247,6 +247,7 @@ pub struct AccountSummaryView {
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct AccountView { pub struct AccountView {
pub platform_icon: Option<String>,
pub quota_settings: gateway_core::account::AccountQuotaSettings, pub quota_settings: gateway_core::account::AccountQuotaSettings,
pub auto_use_quota_credits: bool, pub auto_use_quota_credits: bool,
pub upstream: Option<super::AccountUpstreamInfoView>, pub upstream: Option<super::AccountUpstreamInfoView>,
@@ -263,6 +263,8 @@ pub(crate) fn usage_list_record_view(
upstream_status_code: record.upstream_status_code, upstream_status_code: record.upstream_status_code,
error_code: record.error_code, error_code: record.error_code,
error_message: record.error_message, error_message: record.error_message,
upstream_error_message: record.upstream_error_message,
retry_after_ms: record.retry_after_ms,
error_kind: record.error_kind, error_kind: record.error_kind,
websocket_close_code: record.websocket_close_code, websocket_close_code: record.websocket_close_code,
continuation_unavailable_reason: record.continuation_unavailable_reason, continuation_unavailable_reason: record.continuation_unavailable_reason,
@@ -276,6 +278,7 @@ pub(crate) fn usage_list_record_view(
account_id: record.provider_account_ref, account_id: record.provider_account_ref,
account_email: record.provider_account_email, account_email: record.provider_account_email,
account_name: record.provider_account_name, account_name: record.provider_account_name,
platform_icon: record.platform_icon,
account_notes: record.provider_account_notes, account_notes: record.provider_account_notes,
account_plan_type: record.provider_account_plan_type, account_plan_type: record.provider_account_plan_type,
account_plan_type_display: record.provider_account_plan_type_display, account_plan_type_display: record.provider_account_plan_type_display,
@@ -940,6 +943,7 @@ pub(crate) fn dashboard_view(
.email .email
.clone() .clone()
.unwrap_or_else(|| credential.name.clone()), .unwrap_or_else(|| credential.name.clone()),
platform_icon: credential.platform_icon,
notes: credential.notes, notes: credential.notes,
plan_type: credential.plan_type.clone(), plan_type: credential.plan_type.clone(),
plan_type_display: credential plan_type_display: credential
@@ -1350,13 +1354,16 @@ pub(crate) fn diagnostics_view(
.items .items
.into_iter() .into_iter()
.map(|item| DiagnosticItemView { .map(|item| DiagnosticItemView {
key: item.key, providers: item.providers,
platform_icon: item.platform_icon,
account_email: item.account_email,
authentication_kind: item.account_authentication_kind, authentication_kind: item.account_authentication_kind,
name: if item.name == "__none__" { name: if item.key == "__none__" {
"未知".to_owned() "未知".to_owned()
} else { } else {
item.name item.name
}, },
key: item.key,
request_count: item.request_count, request_count: item.request_count,
account_plan_type: item.account_plan_type, account_plan_type: item.account_plan_type,
account_plan_type_display: item.account_plan_type_display, account_plan_type_display: item.account_plan_type_display,
@@ -86,11 +86,14 @@ pub struct ImageBillingView {
#[derive(Serialize)] #[derive(Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct UsageListRecordView { pub struct UsageListRecordView {
pub platform_icon: Option<String>,
pub error_origin: &'static str, pub error_origin: &'static str,
pub client_status_code: Option<u16>, pub client_status_code: Option<u16>,
pub upstream_status_code: Option<u16>, pub upstream_status_code: Option<u16>,
pub error_code: Option<String>, pub error_code: Option<String>,
pub error_message: Option<String>, pub error_message: Option<String>,
pub upstream_error_message: Option<String>,
pub retry_after_ms: Option<u64>,
pub error_kind: Option<String>, pub error_kind: Option<String>,
pub websocket_close_code: Option<u16>, pub websocket_close_code: Option<u16>,
pub continuation_unavailable_reason: Option<String>, pub continuation_unavailable_reason: Option<String>,
@@ -432,6 +435,7 @@ pub enum DashboardAccountMetric {
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct DashboardAccountUsageView { pub struct DashboardAccountUsageView {
pub platform_icon: Option<String>,
pub upstream: Option<crate::admin::accounts::AccountUpstreamInfoView>, pub upstream: Option<crate::admin::accounts::AccountUpstreamInfoView>,
pub id: String, pub id: String,
pub provider: String, pub provider: String,
@@ -872,8 +876,11 @@ pub struct UsageCacheView {
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct DiagnosticItemView { pub struct DiagnosticItemView {
pub providers: Vec<String>,
pub platform_icon: Option<String>,
pub key: String, pub key: String,
pub name: String, pub name: String,
pub account_email: Option<String>,
pub authentication_kind: Option<String>, pub authentication_kind: Option<String>,
pub account_plan_type: Option<String>, pub account_plan_type: Option<String>,
pub account_plan_type_display: Option<String>, pub account_plan_type_display: Option<String>,
@@ -152,6 +152,7 @@ impl From<ProxyTestResult> for ProxyTestView {
#[derive(Serialize)] #[derive(Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct ProxyAccountView { struct ProxyAccountView {
platform_icon: Option<String>,
upstream: Option<super::accounts::AccountUpstreamInfoView>, upstream: Option<super::accounts::AccountUpstreamInfoView>,
id: String, id: String,
name: String, name: String,
@@ -345,6 +346,7 @@ where
.items .items
.into_iter() .into_iter()
.map(|account| ProxyAccountView { .map(|account| ProxyAccountView {
platform_icon: account.platform_icon,
upstream: account.upstream.map(|info| { upstream: account.upstream.map(|info| {
super::accounts::upstream_info_view( super::accounts::upstream_info_view(
info, info,
@@ -62,6 +62,7 @@ pub struct RuntimeSettingsFields {
pub usage_retention_days: u64, pub usage_retention_days: u64,
pub ops_event_retention_days: u64, pub ops_event_retention_days: u64,
pub audit_retention_days: u64, pub audit_retention_days: u64,
pub prompt_rewrite_rules: Vec<gateway_core::settings::prompt_rewrite::PromptRewriteRule>,
pub account_error_protection: gateway_core::account::AccountErrorProtection, pub account_error_protection: gateway_core::account::AccountErrorProtection,
pub account_warmup_enabled: bool, pub account_warmup_enabled: bool,
pub account_warmup_cron: String, pub account_warmup_cron: String,
@@ -283,6 +284,10 @@ where
post(preview_privacy::<S>), post(preview_privacy::<S>),
) )
.route("/api/admin/settings/update", post(update_settings::<S>)) .route("/api/admin/settings/update", post(update_settings::<S>))
.route(
"/api/admin/settings/prompt-rewrite/preview",
post(preview_prompt_rewrite::<S>),
)
.route( .route(
"/api/admin/settings/client-downloads/codex-desktop/windows", "/api/admin/settings/client-downloads/codex-desktop/windows",
get(codex_desktop_windows_downloads::<S>), get(codex_desktop_windows_downloads::<S>),
@@ -744,6 +749,7 @@ impl RuntimeSettingsFields {
.map_err(|_| WireValidationError::new("settingsOpsRetentionOverflow"))?, .map_err(|_| WireValidationError::new("settingsOpsRetentionOverflow"))?,
audit_retention_days: u32::try_from(self.audit_retention_days) audit_retention_days: u32::try_from(self.audit_retention_days)
.map_err(|_| WireValidationError::new("settingsAuditRetentionOverflow"))?, .map_err(|_| WireValidationError::new("settingsAuditRetentionOverflow"))?,
prompt_rewrite_rules: self.prompt_rewrite_rules,
account_error_protection: self.account_error_protection, account_error_protection: self.account_error_protection,
account_warmup_enabled: self.account_warmup_enabled, account_warmup_enabled: self.account_warmup_enabled,
account_warmup_cron: self.account_warmup_cron, account_warmup_cron: self.account_warmup_cron,
@@ -787,6 +793,7 @@ impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSett
usage_retention_days: u64::from(settings.usage_retention_days), usage_retention_days: u64::from(settings.usage_retention_days),
ops_event_retention_days: u64::from(settings.ops_event_retention_days), ops_event_retention_days: u64::from(settings.ops_event_retention_days),
audit_retention_days: u64::from(settings.audit_retention_days), audit_retention_days: u64::from(settings.audit_retention_days),
prompt_rewrite_rules: settings.prompt_rewrite_rules,
account_error_protection: settings.account_error_protection, account_error_protection: settings.account_error_protection,
account_warmup_enabled: settings.account_warmup_enabled, account_warmup_enabled: settings.account_warmup_enabled,
account_warmup_cron: settings.account_warmup_cron, account_warmup_cron: settings.account_warmup_cron,
@@ -801,6 +808,7 @@ impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSett
fn settings_validation_error(field: &'static str) -> WireValidationError { fn settings_validation_error(field: &'static str) -> WireValidationError {
WireValidationError::new(match field { WireValidationError::new(match field {
"prompt_rewrite_rules" => "promptRewriteRules",
"account_error_protection" => "accountErrorProtection", "account_error_protection" => "accountErrorProtection",
"account_warmup_enabled" => "accountWarmupEnabled", "account_warmup_enabled" => "accountWarmupEnabled",
"account_warmup_model" => "accountWarmupModel", "account_warmup_model" => "accountWarmupModel",
@@ -859,3 +867,25 @@ where
AdminEnvelope::ok(result), AdminEnvelope::ok(result),
)) ))
} }
async fn preview_prompt_rewrite<S>(
State(state): State<S>,
_auth: AdminAuth,
AdminJson(request): AdminJson<
gateway_core::settings::prompt_rewrite::PromptRewritePreviewRequest,
>,
) -> Result<impl IntoResponse, AdminError>
where
S: SessionState + Send + Sync,
{
let result = state
.admin_services()
.settings()
.preview_prompt_rewrite(request)
.await
.map_err(map_service_error)?;
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(result),
))
}
@@ -72,10 +72,6 @@ pub(crate) fn client_error_code(code: &str) -> &str {
} }
} }
pub(crate) fn is_retry_after_header(name: &str) -> bool {
name.eq_ignore_ascii_case("retry-after") || name.eq_ignore_ascii_case("retry-after-ms")
}
/// 为 HTTP 错误或流内失败保留原有字段,仅投影客户端需要的重试信号 /// 为 HTTP 错误或流内失败保留原有字段,仅投影客户端需要的重试信号
pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> { pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
const CODE_PATHS: [&str; 2] = ["/error/code", "/response/error/code"]; const CODE_PATHS: [&str; 2] = ["/error/code", "/response/error/code"];
@@ -91,12 +87,6 @@ pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
return None; return None;
} }
let mut projected = data.clone(); let mut projected = data.clone();
// 容量等待与换号已由网关执行;旧账号的等待提示不能再次阻塞客户端的新一轮路由
for path in ["/headers", "/error/headers", "/response/error/headers"] {
if let Some(Value::Object(headers)) = projected.pointer_mut(path) {
headers.retain(|name, _| !is_retry_after_header(name));
}
}
for path in CODE_PATHS { for path in CODE_PATHS {
if let Some(code) = projected.pointer_mut(path) if let Some(code) = projected.pointer_mut(path)
&& capacity_code(code) && capacity_code(code)
@@ -15,7 +15,7 @@ use serde_json::{Value, json};
pub use gateway_core::engine::execution::gateway_error_from_engine; pub use gateway_core::engine::execution::gateway_error_from_engine;
use crate::client_error::{ProtocolErrorBody, capacity_error_for_client, is_retry_after_header}; use crate::client_error::{ProtocolErrorBody, capacity_error_for_client};
pub use crate::client_error::{ pub use crate::client_error::{
gateway_error_contract, gateway_error_response, openai_error_response, gateway_error_contract, gateway_error_response, openai_error_response,
@@ -109,6 +109,24 @@ pub fn model_not_found_response() -> (StatusCode, Json<Value>) {
) )
} }
/// 将上游实际给出的等待头交给客户端错误事件
pub(crate) fn upstream_retry_headers(error: &EngineError) -> serde_json::Map<String, Value> {
let mut headers = Vec::new();
if let EngineError::Provider(provider) = error {
provider.extend_client_retry_headers(&mut headers, &[]);
}
headers
.into_iter()
.filter_map(|header| {
let value = HeaderValue::from_bytes(header.value()).ok()?;
Some((
header.name().to_ascii_lowercase(),
Value::String(value.to_str().ok()?.to_owned()),
))
})
.collect()
}
/// 在下游尚未提交时交付 Provider 的 HTTP 失败响应,并应用客户端容量恢复合同 /// 在下游尚未提交时交付 Provider 的 HTTP 失败响应,并应用客户端容量恢复合同
pub fn engine_error_response(error: &EngineError) -> Response { pub fn engine_error_response(error: &EngineError) -> Response {
let capacity_unavailable = matches!(error, EngineError::Provider(error) let capacity_unavailable = matches!(error, EngineError::Provider(error)
@@ -122,7 +140,6 @@ pub fn engine_error_response(error: &EngineError) -> Response {
let projected = serde_json::from_slice::<Value>(upstream.body()) let projected = serde_json::from_slice::<Value>(upstream.body())
.ok() .ok()
.and_then(|body| capacity_error_for_client(&body)); .and_then(|body| capacity_error_for_client(&body));
let suppress_retry_after = capacity_unavailable || projected.is_some();
let mut response = match projected { let mut response = match projected {
Some(body) => { Some(body) => {
let mut response = Response::new(Body::from(body.to_string())); let mut response = Response::new(Body::from(body.to_string()));
@@ -145,9 +162,6 @@ pub fn engine_error_response(error: &EngineError) -> Response {
response.headers_mut().insert(CONTENT_TYPE, content_type); response.headers_mut().insert(CONTENT_TYPE, content_type);
} }
for header in upstream.headers() { for header in upstream.headers() {
if suppress_retry_after && is_retry_after_header(header.name()) {
continue;
}
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else { let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
continue; continue;
}; };
@@ -830,7 +830,10 @@ impl StreamingExecutionBody {
} }
Ok(None) => return Err(invalid_execution_stream()), Ok(None) => return Err(invalid_execution_stream()),
Err(error) if self.committed => { Err(error) if self.committed => {
self.push_stream_error(gateway_error_from_engine(&error)); self.push_stream_error(
gateway_error_from_engine(&error),
crate::data_plane::error::upstream_retry_headers(&error),
);
continue; continue;
} }
Err(error) => return Err(MiddlewareError::Engine(error)), Err(error) => return Err(MiddlewareError::Engine(error)),
@@ -893,9 +896,13 @@ impl StreamingExecutionBody {
} }
} }
fn push_stream_error(&mut self, error: GatewayError) { fn push_stream_error(
&mut self,
error: GatewayError,
headers: serde_json::Map<String, serde_json::Value>,
) {
self.pending.push_back(MiddlewareFrame::new( self.pending.push_back(MiddlewareFrame::new(
self.encoder.error_frame(&error), self.encoder.error_frame(&error, headers),
MiddlewareFraming::SseEvent, MiddlewareFraming::SseEvent,
false, false,
)); ));
@@ -935,7 +942,7 @@ impl MiddlewareBody for StreamingExecutionBody {
"Gateway response stream could not be delivered.", "Gateway response stream could not be delivered.",
), ),
}; };
self.push_stream_error(error); self.push_stream_error(error, Default::default());
} }
Ok(self.pending.pop_front()) Ok(self.pending.pop_front())
}) })
@@ -972,7 +979,7 @@ impl MiddlewareBody for StreamingExecutionBody {
"The Chat response could not be finalized.", "The Chat response could not be finalized.",
), ),
}; };
self.push_stream_error(error); self.push_stream_error(error, Default::default());
} }
} }
} }
@@ -113,15 +113,9 @@ async fn stream_failure(
error_encoder: Option<fn(&Value) -> Bytes>, error_encoder: Option<fn(&Value) -> Bytes>,
append_done: bool, append_done: bool,
) -> Body { ) -> Body {
let status = response.status(); let (parts, body) = response.into_parts();
let retry_after = response let status = parts.status;
.headers() let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
.get(header::RETRY_AFTER)
.and_then(|value| value.to_str().ok())
.map(ToOwned::to_owned);
let bytes = to_bytes(response.into_body(), usize::MAX)
.await
.unwrap_or_default();
let json = serde_json::from_slice::<Value>(&bytes).ok(); let json = serde_json::from_slice::<Value>(&bytes).ok();
let raw_message = std::str::from_utf8(&bytes) let raw_message = std::str::from_utf8(&bytes)
.ok() .ok()
@@ -144,16 +138,20 @@ async fn stream_failure(
) )
}); });
// HTTP 头已提交,按官方 SSE 错误合同保留允许下发的重试建议 // HTTP 头已提交,按官方 SSE 错误合同保留允许下发的重试建议
if let Some(retry_after) = retry_after for name in gateway_protocol::http::RETRY_AFTER_HEADERS {
&& let Some(error) = data["response"]["error"].as_object_mut() if let Some(value) = parts
&& let Some(headers) = error .headers
.entry("headers") .get(name)
.or_insert_with(|| serde_json::json!({})) .and_then(|value| value.to_str().ok())
.as_object_mut() && let Some(error) = data["response"]["error"].as_object_mut()
{ && let Some(headers) = error
headers .entry("headers")
.entry("retry-after") .or_insert_with(|| serde_json::json!({}))
.or_insert(Value::String(retry_after)); .as_object_mut()
&& !headers.keys().any(|key| key.eq_ignore_ascii_case(name))
{
headers.insert(name.to_owned(), Value::String(value.to_owned()));
}
} }
let mut event = match error_encoder { let mut event = match error_encoder {
Some(encode) => encode(&data).to_vec(), Some(encode) => encode(&data).to_vec(),
@@ -6,7 +6,8 @@ use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL;
use gateway_protocol::{ use gateway_protocol::{
anthropic::MessagesAccumulator, anthropic::MessagesAccumulator,
openai::sse::{ openai::sse::{
DONE_SSE_FRAME, encode_sse_event_with_metadata, response_failed_sse_event_with_id, DONE_SSE_FRAME, encode_sse_event, encode_sse_event_with_metadata,
response_failed_sse_data_with_id,
}, },
}; };
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -159,7 +160,11 @@ impl GenerationEncoder {
} }
} }
pub(super) fn error_frame(&self, error: &GatewayError) -> Bytes { pub(super) fn error_frame(
&self,
error: &GatewayError,
headers: serde_json::Map<String, Value>,
) -> Bytes {
let (status, error_type, code) = gateway_error_contract(error.kind()); let (status, error_type, code) = gateway_error_contract(error.kind());
match self { match self {
Self::Chat(_) => { Self::Chat(_) => {
@@ -169,12 +174,21 @@ impl GenerationEncoder {
"message": error.client_message(), "message": error.client_message(),
}})) }}))
} }
Self::Responses(encoder) => Bytes::from(response_failed_sse_event_with_id( Self::Responses(encoder) => {
encoder.response_id(), let mut data = response_failed_sse_data_with_id(
error.client_error_type().unwrap_or(error_type), encoder.response_id(),
crate::client_error::client_error_code(error.client_error_code().unwrap_or(code)), error.client_error_type().unwrap_or(error_type),
error.client_message(), crate::client_error::client_error_code(
)), error.client_error_code().unwrap_or(code),
),
error.client_message(),
);
if !headers.is_empty() {
data["response"]["error"]["headers"] = json!(headers);
data["error"]["headers"] = Value::Object(headers);
}
Bytes::from(encode_sse_event("response.failed", &data.to_string()))
}
Self::GenAi { .. } => { Self::GenAi { .. } => {
crate::data_plane::genai::error_frame(status, error.client_message()) crate::data_plane::genai::error_frame(status, error.client_message())
} }
@@ -41,7 +41,7 @@ pub(crate) async fn models(
Query(query): Query<ModelsQuery>, Query(query): Query<ModelsQuery>,
headers: HeaderMap, headers: HeaderMap,
) -> Response { ) -> Response {
let anthropic = headers.contains_key("anthropic-version") || headers.contains_key("x-api-key"); let anthropic = headers.contains_key("anthropic-version");
let service = state.data_plane(); let service = state.data_plane();
let client = match authenticate_client(service, &headers, ClientKeyHeaders::Anthropic).await { let client = match authenticate_client(service, &headers, ClientKeyHeaders::Anthropic).await {
Ok(client) => client, Ok(client) => client,
@@ -104,7 +104,7 @@ pub(crate) async fn model_detail(
headers: HeaderMap, headers: HeaderMap,
Path(model_id): Path<String>, Path(model_id): Path<String>,
) -> Response { ) -> Response {
let anthropic = headers.contains_key("anthropic-version") || headers.contains_key("x-api-key"); let anthropic = headers.contains_key("anthropic-version");
let service = state.data_plane(); let service = state.data_plane();
let client = match authenticate_client(service, &headers, ClientKeyHeaders::Anthropic).await { let client = match authenticate_client(service, &headers, ClientKeyHeaders::Anthropic).await {
Ok(client) => client, Ok(client) => client,
@@ -575,7 +575,10 @@ impl WebSocketExecutionBody {
Ok(Some(delivery)) => delivery, Ok(Some(delivery)) => delivery,
Ok(None) => return Err(MiddlewareError::InvalidState), Ok(None) => return Err(MiddlewareError::InvalidState),
Err(error) if self.committed => { Err(error) if self.committed => {
self.push_gateway_error(gateway_error_from_engine(&error)); self.push_gateway_error(
gateway_error_from_engine(&error),
crate::data_plane::error::upstream_retry_headers(&error),
);
continue; continue;
} }
Err(error) => return Err(MiddlewareError::Engine(error)), Err(error) => return Err(MiddlewareError::Engine(error)),
@@ -635,7 +638,11 @@ impl WebSocketExecutionBody {
Ok(()) Ok(())
} }
fn push_gateway_error(&mut self, error: GatewayError) { fn push_gateway_error(
&mut self,
error: GatewayError,
headers: serde_json::Map<String, serde_json::Value>,
) {
let (status, default_type, default_code) = gateway_error_contract(error.kind()); let (status, default_type, default_code) = gateway_error_contract(error.kind());
self.pending.push_back(MiddlewareFrame::new( self.pending.push_back(MiddlewareFrame::new(
Bytes::from( Bytes::from(
@@ -646,7 +653,7 @@ impl WebSocketExecutionBody {
error.client_message(), error.client_message(),
None, None,
Some(&self.request_id), Some(&self.request_id),
serde_json::Map::new(), headers,
) )
.to_string(), .to_string(),
), ),
@@ -173,8 +173,13 @@ pub(super) fn initial_engine_error_event(
}; };
let upstream = provider.and_then(|error| error.client_visible_upstream_response()); let upstream = provider.and_then(|error| error.client_visible_upstream_response());
// 最终失败响应优先于会话快照,避免混入先前 attempt 或 opening 的关联头 // 最终失败响应优先于会话快照,避免混入先前 attempt 或 opening 的关联头
let mut headers = let mut headers = if let Some((provider, response)) = provider.zip(upstream) {
response_event_headers(upstream.map_or(response_headers, |response| response.headers())); let mut headers = response.headers().to_vec();
provider.extend_client_retry_headers(&mut headers, &[]);
response_event_headers(&headers)
} else {
response_event_headers(response_headers)
};
if upstream.is_none() { if upstream.is_none() {
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头 // 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
headers.remove("x-request-id"); headers.remove("x-request-id");
+7
View File
@@ -216,6 +216,7 @@ pub fn initialize(
}) })
}; };
let state = ApiState { let state = ApiState {
platform_icon_catalog: Arc::new(config.asset_directory.join("platform-icons.json")),
admin, admin,
data_plane: DataPlaneService::new(execution, lifecycle), data_plane: DataPlaneService::new(execution, lifecycle),
health: HealthStatus::new(probes, worker_health, diagnostics.clone()), health: HealthStatus::new(probes, worker_health, diagnostics.clone()),
@@ -337,6 +338,7 @@ pub enum ApiError {
#[derive(Clone)] #[derive(Clone)]
pub(crate) struct ApiState { pub(crate) struct ApiState {
platform_icon_catalog: Arc<PathBuf>,
admin: AdminServices, admin: AdminServices,
data_plane: DataPlaneService, data_plane: DataPlaneService,
health: HealthStatus, health: HealthStatus,
@@ -355,6 +357,11 @@ impl ApiState {
} }
impl SessionState for ApiState { impl SessionState for ApiState {
async fn platform_icon_names(&self) -> std::io::Result<std::collections::HashSet<String>> {
let bytes = tokio::fs::read(self.platform_icon_catalog.as_ref()).await?;
Ok(serde_json::from_slice(&bytes)?)
}
fn admin_services(&self) -> &AdminServices { fn admin_services(&self) -> &AdminServices {
&self.admin &self.admin
} }
@@ -4,5 +4,8 @@ use gateway_admin::AdminServices;
/// 控制面 HTTP adapter 消费同一组用例;权限由各入口服务端校验 /// 控制面 HTTP adapter 消费同一组用例;权限由各入口服务端校验
pub trait SessionState { pub trait SessionState {
fn platform_icon_names(
&self,
) -> impl Future<Output = std::io::Result<std::collections::HashSet<String>>> + Send;
fn admin_services(&self) -> &AdminServices; fn admin_services(&self) -> &AdminServices;
} }
@@ -411,6 +411,7 @@ fn account_page_item(
use gateway_core::account::resolve_account_status; use gateway_core::account::resolve_account_status;
AccountPageItem { AccountPageItem {
platform_icon: None,
protection_rules: Vec::new(), protection_rules: Vec::new(),
account: AccountRecord { account: AccountRecord {
quota_paused: false, quota_paused: false,
@@ -638,14 +639,22 @@ async fn connection_update_requires_admin_and_validates_before_calling_the_servi
"connection":{"baseUrl":"https://api.example.invalid/v1", "transport":"http"} "connection":{"baseUrl":"https://api.example.invalid/v1", "transport":"http"}
}); });
for (authenticated, transport, oauth, expected) in [ for (authenticated, transport, oauth, expected) in [
(false, "http", false, StatusCode::UNAUTHORIZED), (false, Some("http"), false, StatusCode::UNAUTHORIZED),
(true, "invalid", false, StatusCode::BAD_REQUEST), (true, Some("invalid"), false, StatusCode::BAD_REQUEST),
// 夹具没有凭据 Store,合法输入必须进入服务,不能按普通设置静默保存 // 夹具没有凭据 Store,合法输入必须进入服务,不能按普通设置静默保存
(true, "http", false, StatusCode::SERVICE_UNAVAILABLE), (true, Some("http"), false, StatusCode::SERVICE_UNAVAILABLE),
(true, "http", true, StatusCode::SERVICE_UNAVAILABLE), (true, Some("http"), true, StatusCode::SERVICE_UNAVAILABLE),
(true, None, false, StatusCode::SERVICE_UNAVAILABLE),
] { ] {
let mut input = input.clone(); let mut input = input.clone();
input["connection"]["transport"] = serde_json::json!(transport); if let Some(transport) = transport {
input["connection"]["transport"] = serde_json::json!(transport);
} else {
input["connection"]
.as_object_mut()
.unwrap()
.remove("transport");
}
if oauth { if oauth {
input["connection"] input["connection"]
.as_object_mut() .as_object_mut()
@@ -670,6 +679,67 @@ async fn connection_update_requires_admin_and_validates_before_calling_the_servi
} }
} }
#[tokio::test]
async fn account_icon_requires_a_known_preset_before_mutation() {
let fixture = AdminTestFixture::new().await;
fixture.auth.insert_session("valid-session");
for (name, expected) in [
("DeepSeek", StatusCode::SERVICE_UNAVAILABLE),
("", StatusCode::SERVICE_UNAVAILABLE),
("Unlisted", StatusCode::BAD_REQUEST),
("https://example.invalid/logo.svg", StatusCode::BAD_REQUEST),
] {
let settings = serde_json::json!({
"platformIcon": name, "enabled": true,
"concurrencyLimit": null, "weight": 1, "groupIds": []
});
for (route, payload) in [
(
"update",
serde_json::json!({
"accountId": "acct_api", "platformIcon": name, "enabled": true,
"concurrencyLimit": null, "weight": 1, "groupIds": []
}),
),
(
"import",
serde_json::json!({"provider": "openai", "data": {}, "settings": settings}),
),
(
"oauth/complete",
serde_json::json!({
"provider": "xai", "flowId": "flow-test", "callbackUrl": "code", "settings": settings
}),
),
] {
let request = Request::post(format!("/api/admin/accounts/{route}"))
.header("x-request-id", "req_account_icon")
.header(header::COOKIE, "cpr_session=valid-session")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(payload.to_string()))
.unwrap();
let response = admin::router::<AdminTestState>()
.with_state(fixture.state())
.oneshot(request)
.await
.unwrap();
let status = response.status();
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
if expected == StatusCode::BAD_REQUEST {
assert_eq!(status, expected, "{route}: {name}");
assert_eq!(body["message"], "platformIcon 字段不合法");
} else if route == "update" {
assert_eq!(status, expected, "{route}: {name}");
} else {
// 夹具 Provider 未实现导入和授权,合法图标应通过校验并到达 Provider
assert_eq!(status, StatusCode::BAD_REQUEST, "{route}: {name}: {body}");
assert_eq!(body["message"], "该服务商不支持此操作");
}
}
}
}
#[tokio::test] #[tokio::test]
async fn personal_info_requires_admin_and_a_valid_account_query() { async fn personal_info_requires_admin_and_a_valid_account_query() {
let fixture = AdminTestFixture::new().await; let fixture = AdminTestFixture::new().await;
@@ -126,7 +126,7 @@ mod query {
"provider": "xai", "provider": "xai",
"search": " operator ", "search": " operator ",
"status": "normal", "status": "normal",
"sortBy": "lastUsedAt", "sortBy": "name",
"sortDirection": "desc" "sortDirection": "desc"
})) }))
.expect("deserialize account query"); .expect("deserialize account query");
@@ -139,10 +139,7 @@ mod query {
)); ));
assert_eq!(query.search.as_deref(), Some("operator")); assert_eq!(query.search.as_deref(), Some("operator"));
assert_eq!(query.status, Some(AccountStatus::Normal)); assert_eq!(query.status, Some(AccountStatus::Normal));
assert_eq!( assert_eq!(query.sort.expect("sort").field, AccountSortField::Name);
query.sort.expect("sort").field,
AccountSortField::LastUsedAt
);
assert_eq!( assert_eq!(
query.sort.expect("copy sort").direction, query.sort.expect("copy sort").direction,
SortDirection::Desc SortDirection::Desc
@@ -727,6 +724,20 @@ mod actions {
); );
} }
#[test]
fn native_api_key_connection_accepts_address_and_key_without_transport() {
let request: UpdateAccountRequest = serde_json::from_value(json!({
"accountId":"acct_api", "enabled":true, "concurrencyLimit":null,
"weight":1, "groupIds":[],
"connection":{"baseUrl":"https://relay.example/antigravity/v1beta","apiKey":"fixture-key"}
})).unwrap();
request.validate().unwrap();
let connection = request.connection.unwrap();
assert!(connection.protocol.is_none());
assert!(connection.transport.is_none());
assert_eq!(connection.api_key.as_deref(), Some("fixture-key"));
}
#[test] #[test]
fn account_connection_update_rejects_invalid_fields_and_generic_credentials() { fn account_connection_update_rejects_invalid_fields_and_generic_credentials() {
let request = json!({ let request = json!({
@@ -564,6 +564,7 @@ mod provider {
last_error_message: None, last_error_message: None,
}; };
AccountPageItem { AccountPageItem {
platform_icon: None,
protection_rules: Vec::new(), protection_rules: Vec::new(),
capacity: gateway_admin::model::accounts::AccountCapacity { capacity: gateway_admin::model::accounts::AccountCapacity {
used_slots: None, used_slots: None,
@@ -311,6 +311,10 @@ impl ClientDistributionResolver for StaticClientDistribution {
pub(super) struct AdminTestState(AdminServices); pub(super) struct AdminTestState(AdminServices);
impl SessionState for AdminTestState { impl SessionState for AdminTestState {
async fn platform_icon_names(&self) -> std::io::Result<std::collections::HashSet<String>> {
Ok(["DeepSeek".to_owned()].into())
}
fn admin_services(&self) -> &AdminServices { fn admin_services(&self) -> &AdminServices {
&self.0 &self.0
} }
@@ -2016,6 +2020,7 @@ fn test_runtime_settings() -> RuntimeSettings {
usage_retention_days: 31, usage_retention_days: 31,
ops_event_retention_days: 30, ops_event_retention_days: 30,
audit_retention_days: 90, audit_retention_days: 90,
prompt_rewrite_rules: Vec::new(),
account_error_protection: Default::default(), account_error_protection: Default::default(),
account_warmup_enabled: false, account_warmup_enabled: false,
account_warmup_cron: "0 8 * * *".to_owned(), account_warmup_cron: "0 8 * * *".to_owned(),
@@ -748,11 +748,13 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
total_request_count: 4, total_request_count: 4,
items: vec![DiagnosticObservation { items: vec![DiagnosticObservation {
key: "acct_diag".to_owned(), key: "acct_diag".to_owned(),
account_provider_kind: Some("openai".to_owned()), providers: vec!["openai".to_owned()],
platform_icon: Some("Adobe".to_owned()),
account_authentication_kind: authentication_kind.map(str::to_owned), account_authentication_kind: authentication_kind.map(str::to_owned),
account_plan_type: plan_type.map(str::to_owned), account_plan_type: plan_type.map(str::to_owned),
account_plan_type_display: None, account_plan_type_display: None,
name: "diag@example.invalid".to_owned(), account_email: Some("diag@example.invalid".to_owned()),
name: "__none__".to_owned(),
request_count: 2, request_count: 2,
success_count: 2, success_count: 2,
failure_count: 0, failure_count: 0,
@@ -791,6 +793,8 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
value["data"]["items"][0]["accountUpstreamPeer"], value["data"]["items"][0]["accountUpstreamPeer"],
json!(peer.map(|(d, o)| d && o)) json!(peer.map(|(d, o)| d && o))
); );
assert_eq!(value["data"]["items"][0]["providers"], json!(["openai"]));
assert_eq!(value["data"]["items"][0]["platformIcon"], "Adobe");
assert_eq!(value["data"]["items"][0]["requestShare"], 0.5); assert_eq!(value["data"]["items"][0]["requestShare"], 0.5);
assert_eq!(value["data"]["items"][0]["retryCount"], 3); assert_eq!(value["data"]["items"][0]["retryCount"], 3);
assert_eq!(value["data"]["items"][0]["retryRate"], 0.5); assert_eq!(value["data"]["items"][0]["retryRate"], 0.5);
@@ -810,11 +814,13 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
( (
&value["data"]["items"][0]["key"], &value["data"]["items"][0]["key"],
&value["data"]["items"][0]["name"], &value["data"]["items"][0]["name"],
&value["data"]["items"][0]["accountEmail"],
&value["data"]["items"][0]["latencyP95Ms"], &value["data"]["items"][0]["latencyP95Ms"],
&value["data"]["dimension"], &value["data"]["dimension"],
), ),
( (
&serde_json::json!("acct_diag"), &serde_json::json!("acct_diag"),
&serde_json::json!("__none__"),
&serde_json::json!("diag@example.invalid"), &serde_json::json!("diag@example.invalid"),
&serde_json::json!(3800), &serde_json::json!(3800),
&serde_json::json!("account"), &serde_json::json!("account"),
@@ -981,8 +987,11 @@ async fn usage_route_projects_request_facts_and_billing() {
.lock() .lock()
.expect("usage records") .expect("usage records")
.push(UsageListRecord { .push(UsageListRecord {
platform_icon: None,
provider_account_upstream_peer: None, provider_account_upstream_peer: None,
has_upstream_error: false, has_upstream_error: false,
upstream_error_message: None,
retry_after_ms: None,
error_code: None, error_code: None,
error_message: None, error_message: None,
error_kind: None, error_kind: None,
@@ -1085,6 +1094,8 @@ async fn usage_route_projects_request_facts_and_billing() {
failed.upstream_status_code = Some(429); failed.upstream_status_code = Some(429);
failed.error_code = Some("server_error".to_owned()); failed.error_code = Some("server_error".to_owned());
failed.error_message = Some("The upstream service is temporarily unavailable.".to_owned()); failed.error_message = Some("The upstream service is temporarily unavailable.".to_owned());
failed.upstream_error_message = Some("Retry once capacity is available.".to_owned());
failed.retry_after_ms = Some(30_000);
records.push(failed); records.push(failed);
let mut closed = records[0].clone(); let mut closed = records[0].clone();
closed.id = "request_ws_closed".to_owned(); closed.id = "request_ws_closed".to_owned();
@@ -1127,6 +1138,11 @@ async fn usage_route_projects_request_facts_and_billing() {
assert!(value["data"]["items"][0]["errorCode"].is_null()); assert!(value["data"]["items"][0]["errorCode"].is_null());
assert!(value["data"]["items"][0]["errorMessage"].is_null()); assert!(value["data"]["items"][0]["errorMessage"].is_null());
assert_eq!(value["data"]["items"][3]["errorCode"], "server_error"); assert_eq!(value["data"]["items"][3]["errorCode"], "server_error");
assert_eq!(
value["data"]["items"][3]["upstreamErrorMessage"],
"Retry once capacity is available."
);
assert_eq!(value["data"]["items"][3]["retryAfterMs"], 30_000);
assert_eq!(value["data"]["items"][3]["clientStatusCode"], 503); assert_eq!(value["data"]["items"][3]["clientStatusCode"], 503);
assert_eq!(value["data"]["items"][3]["upstreamStatusCode"], 429); assert_eq!(value["data"]["items"][3]["upstreamStatusCode"], 429);
assert_eq!(value["data"]["items"][3]["errorOrigin"], "upstream"); assert_eq!(value["data"]["items"][3]["errorOrigin"], "upstream");
@@ -1962,6 +1978,7 @@ async fn dashboard_summary_identifies_trend_metrics_and_account_usage_values() {
.map(|(index, (requests, tokens, last_used_at))| { .map(|(index, (requests, tokens, last_used_at))| {
let account_id = format!("acct_metric_{index}"); let account_id = format!("acct_metric_{index}");
DashboardAccountUsage { DashboardAccountUsage {
platform_icon: None,
upstream: None, upstream: None,
account_id: account_id.clone(), account_id: account_id.clone(),
provider_kind: "openai".to_owned(), provider_kind: "openai".to_owned(),
@@ -2153,6 +2170,7 @@ async fn dashboard_relative_time_preserves_server_anchor_boundaries_and_deployme
provider_accounts: Default::default(), provider_accounts: Default::default(),
trend: Vec::new(), trend: Vec::new(),
account_usage: vec![DashboardAccountUsage { account_usage: vec![DashboardAccountUsage {
platform_icon: None,
upstream: None, upstream: None,
account_id: "acct_relative_time".to_owned(), account_id: "acct_relative_time".to_owned(),
provider_kind: "openai".to_owned(), provider_kind: "openai".to_owned(),
@@ -287,6 +287,7 @@ impl ProxyStore for MemoryProxies {
} }
Ok(ProxyAccountPage { Ok(ProxyAccountPage {
items: vec![ProxyAccountRef { items: vec![ProxyAccountRef {
platform_icon: None,
upstream: None, upstream: None,
id: "acct_linked".to_owned(), id: "acct_linked".to_owned(),
name: "工作账号".to_owned(), name: "工作账号".to_owned(),
@@ -569,7 +570,7 @@ async fn proxy_routes_save_reload_test_rename_and_delete_without_exposing_creden
assert_eq!( assert_eq!(
linked["data"]["items"], linked["data"]["items"],
json!([{ json!([{
"id":"acct_linked", "name":"工作账号", "email":"work@example.invalid", "id":"acct_linked", "name":"工作账号", "email":"work@example.invalid", "platformIcon":null,
"provider":"openai", "enabled":true, "authenticationKind":"oauth", "provider":"openai", "enabled":true, "authenticationKind":"oauth",
"planType":"plus", "planTypeDisplay":"Plus", "groups":[], "upstream":null "planType":"plus", "planTypeDisplay":"Plus", "groups":[], "upstream":null
}]) }])
@@ -106,6 +106,7 @@ fn update_body() -> Value {
"usageRetentionDays": 31, "usageRetentionDays": 31,
"opsEventRetentionDays": 31, "opsEventRetentionDays": 31,
"auditRetentionDays": 91, "auditRetentionDays": 91,
"promptRewriteRules": [],
"accountErrorProtection": gateway_core::account::AccountErrorProtection::default(), "accountErrorProtection": gateway_core::account::AccountErrorProtection::default(),
"accountWarmupEnabled": false, "accountWarmupEnabled": false,
"accountWarmupCron": "0 8 * * *", "accountWarmupCron": "0 8 * * *",
@@ -289,6 +290,67 @@ async fn error_protection_rules_round_trip_and_invalid_policy_does_not_replace_t
); );
} }
#[test]
fn prompt_rewrite_requires_names_and_prefixes_and_rejects_unknown_fields() {
let mut body = update_body();
for rule in [
json!({"name":"规则", "matchMode":"prefix", "pattern":"prefix", "replacement":"", "unknownField":["xai"]}),
json!({"name":"规则", "matchMode":"prefix", "pattern":"", "replacement":""}),
json!({"matchMode":"prefix", "pattern":"prefix", "replacement":""}),
json!({"name":"规则", "pattern":"prefix", "replacement":""}),
json!({"name":"规则", "matchMode":"unknown", "pattern":"prefix", "replacement":""}),
json!({"name":"", "matchMode":"prefix", "pattern":"prefix", "replacement":""}),
json!({"name":" ", "matchMode":"prefix", "pattern":"prefix", "replacement":""}),
] {
body["promptRewriteRules"] = json!([rule]);
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body.clone()).is_err());
}
}
#[tokio::test]
async fn prompt_rewrite_preview_uses_runtime_matching_and_rejects_invalid_rules() {
let fixture = AdminTestFixture::new().await;
fixture.auth.insert_session("valid-session");
let mut body = json!({
"rule": {"name":"DSH", "matchMode":"regex", "pattern":"(?i)you are (DSH)", "replacement":"Agent $1"},
"text":"You are DSH\nKeep this"
});
let response = app(fixture.state())
.oneshot(request(
Method::POST,
"/api/admin/settings/prompt-rewrite/preview",
Some(body.clone()),
))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response_json(response).await["data"],
json!({"matched":true,"output":"Agent DSH\nKeep this"})
);
body["rule"]["pattern"] = json!("[");
let response = app(fixture.state())
.oneshot(request(
Method::POST,
"/api/admin/settings/prompt-rewrite/preview",
Some(body.clone()),
))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let mut update = update_body();
update["promptRewriteRules"] = json!([body["rule"].clone()]);
let response = app(fixture.state())
.oneshot(request(
Method::POST,
"/api/admin/settings/update",
Some(update),
))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
#[test] #[test]
fn error_protection_requires_an_explicit_policy_in_settings_replacement() { fn error_protection_requires_an_explicit_policy_in_settings_replacement() {
let mut missing = update_body(); let mut missing = update_body();
@@ -1478,7 +1540,7 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
); );
assert_eq!( assert_eq!(
initial["openaiRequestSettings"]["requestCountry"], initial["openaiRequestSettings"]["requestCountry"],
json!({"mode":"follow_location"}) json!({"mode":"default"})
); );
let mut body = update_body(); let mut body = update_body();
body["configRevision"] = initial["configRevision"].clone(); body["configRevision"] = initial["configRevision"].clone();
@@ -101,8 +101,8 @@ async fn capacity_errors_offer_client_retry_without_changing_upstream_facts() {
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
if raw_response { if raw_response {
assert_eq!(response.headers()["x-request-id"], "req_capacity"); assert_eq!(response.headers()["x-request-id"], "req_capacity");
assert!(!response.headers().contains_key("retry-after")); assert_eq!(response.headers()["retry-after"], "7");
assert!(!response.headers().contains_key("retry-after-ms")); assert_eq!(response.headers()["retry-after-ms"], "7000");
} }
let body: Value = serde_json::from_slice( let body: Value = serde_json::from_slice(
&to_bytes(response.into_body(), 4096) &to_bytes(response.into_body(), 4096)
@@ -116,7 +116,6 @@ async fn capacity_errors_offer_client_retry_without_changing_upstream_facts() {
if raw_response { if raw_response {
let mut expected = original.clone(); let mut expected = original.clone();
expected["error"]["code"] = json!("server_error"); expected["error"]["code"] = json!("server_error");
expected["error"]["headers"] = json!({"x-request-id":"req_capacity"});
assert_eq!(body, expected); assert_eq!(body, expected);
} }
let EngineError::Provider(provider) = error else { let EngineError::Provider(provider) = error else {
@@ -34,7 +34,9 @@ async fn anthropic_models_use_explicit_headers_and_cursor_pagination() {
.clone() .clone()
.oneshot( .oneshot(
Request::get(path) Request::get(path)
.header(AUTHORIZATION, "Bearer sk_models_test")
.header("x-api-key", "sk_models_test") .header("x-api-key", "sk_models_test")
.header("anthropic-version", "2023-06-01")
.body(Body::empty()) .body(Body::empty())
.unwrap(), .unwrap(),
) )
@@ -90,6 +92,7 @@ async fn anthropic_model_detail_keeps_public_model_access() {
.oneshot( .oneshot(
Request::get(path) Request::get(path)
.header("x-api-key", "sk_models_test") .header("x-api-key", "sk_models_test")
.header("anthropic-version", "2023-06-01")
.body(Body::empty()) .body(Body::empty())
.unwrap(), .unwrap(),
) )
@@ -296,6 +299,22 @@ impl ExecutionService for ModelsExecution {
} }
} }
fn authenticated_model_requests(path: &str) -> [Request<Body>; 3] {
let api_key_request = Request::get(path)
.header("x-api-key", "sk_models_test")
.body(Body::empty())
.expect("API key request");
let mut dual_header_request = authorized_request(path);
dual_header_request
.headers_mut()
.insert("x-api-key", "sk_models_test".parse().expect("API key"));
[
authorized_request(path),
api_key_request,
dual_header_request,
]
}
fn authorized_request(path: &str) -> Request<Body> { fn authorized_request(path: &str) -> Request<Body> {
Request::get(path) Request::get(path)
.header(AUTHORIZATION, "Bearer sk_models_test") .header(AUTHORIZATION, "Bearer sk_models_test")
@@ -490,18 +509,20 @@ async fn native_catalog_failure_does_not_publish_a_synthetic_or_empty_success()
requested_versions: Mutex::default(), requested_versions: Mutex::default(),
middleware: None, middleware: None,
}); });
let response = api_router(execution) for request in authenticated_model_requests("/v1/models?client_version=0.154.0") {
.await let response = api_router(execution.clone())
.oneshot(authorized_request("/v1/models?client_version=0.154.0")) .await
.await .oneshot(request)
.expect("response"); .await
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); .expect("response");
let body = to_bytes(response.into_body(), usize::MAX) assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
.await let body = to_bytes(response.into_body(), usize::MAX)
.expect("body"); .await
let value: serde_json::Value = serde_json::from_slice(&body).expect("JSON"); .expect("body");
assert_eq!(value["error"]["code"], "model_catalog_unavailable"); let value: serde_json::Value = serde_json::from_slice(&body).expect("JSON");
assert!(value.get("models").is_none()); assert_eq!(value["error"]["code"], "model_catalog_unavailable");
assert!(value.get("models").is_none());
}
} }
#[tokio::test] #[tokio::test]
@@ -781,52 +802,64 @@ async fn models_should_preserve_unknown_context_windows() {
#[tokio::test] #[tokio::test]
async fn models_should_keep_the_codex_contract_when_profiles_are_empty() { async fn models_should_keep_the_codex_contract_when_profiles_are_empty() {
let response = api_router(ModelsExecution::new()) for request in authenticated_model_requests("/v1/models?client_version=0.145.0") {
.await let response = api_router(ModelsExecution::new())
.oneshot(authorized_request("/v1/models?client_version=0.145.0")) .await
.await .oneshot(request)
.expect("list empty Codex models response"); .await
let body = to_bytes(response.into_body(), usize::MAX) .expect("list empty Codex models response");
.await let body = to_bytes(response.into_body(), usize::MAX)
.expect("read empty Codex models body"); .await
let value: serde_json::Value = serde_json::from_slice(&body).expect("Codex models JSON"); .expect("read empty Codex models body");
let value: serde_json::Value = serde_json::from_slice(&body).expect("Codex models JSON");
assert_eq!(value, serde_json::json!({ "models": [] })); assert_eq!(value, serde_json::json!({ "models": [] }));
}
} }
#[tokio::test] #[tokio::test]
async fn models_with_provider_profiles_should_keep_the_openai_list_contract() { async fn models_with_provider_profiles_should_keep_the_openai_list_contract() {
let response = api_router(ModelsExecution::with_profiles()) for request in authenticated_model_requests("/v1/models") {
.await let response = api_router(ModelsExecution::with_profiles())
.oneshot(authorized_request("/v1/models")) .await
.await .oneshot(request)
.expect("list compatible models response"); .await
let body = to_bytes(response.into_body(), usize::MAX) .expect("list compatible models response");
.await let body = to_bytes(response.into_body(), usize::MAX)
.expect("read compatible models body"); .await
let value: serde_json::Value = serde_json::from_slice(&body).expect("models JSON"); .expect("read compatible models body");
let value: serde_json::Value = serde_json::from_slice(&body).expect("models JSON");
assert_eq!( assert_eq!(
value, value,
serde_json::json!({ serde_json::json!({
"object": "list", "object": "list",
"data": [ "data": [
{"id":"model-a","object":"model","created":1700000000_i64,"owned_by":"gateway"}, {"id":"model-a","object":"model","created":1700000000_i64,"owned_by":"gateway"},
{"id":"model-b","object":"model","created":1700000000_i64,"owned_by":"gateway"} {"id":"model-b","object":"model","created":1700000000_i64,"owned_by":"gateway"}
] ]
}) })
); );
}
} }
#[tokio::test] #[tokio::test]
async fn model_detail_should_keep_the_official_path_id_contract() { async fn model_detail_should_keep_the_official_path_id_contract() {
let response = api_router(ModelsExecution::new()) for request in authenticated_model_requests("/v1/models/responses-only") {
.await let response = api_router(ModelsExecution::new())
.oneshot(authorized_request("/v1/models/model-a")) .await
.await .oneshot(request)
.expect("model detail response"); .await
.expect("model detail response");
assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("model body");
let value: serde_json::Value = serde_json::from_slice(&body).expect("model JSON");
assert_eq!(value["id"], "responses-only");
assert_eq!(value["object"], "model");
}
} }
#[tokio::test] #[tokio::test]
@@ -91,6 +91,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu
last_error_message: None, last_error_message: None,
}; };
*fixture.account.lock().unwrap() = Some(AccountPageItem { *fixture.account.lock().unwrap() = Some(AccountPageItem {
platform_icon: None,
protection_rules: Vec::new(), protection_rules: Vec::new(),
capacity: AccountCapacity { capacity: AccountCapacity {
used_slots: None, used_slots: None,
@@ -1416,7 +1416,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
Some(b"application/json".to_vec()), Some(b"application/json".to_vec()),
Bytes::from(json!({"error": error}).to_string()), Bytes::from(json!({"error": error}).to_string()),
) )
.with_headers(headers(&[("retry-after", "7")])), .with_headers(headers(&[("retry-after", "7"), ("retry-after-ms", "7012")])),
) )
}; };
let immediate = FakeSession::streaming( let immediate = FakeSession::streaming(
@@ -1447,7 +1447,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
.find(|event| event.event.as_deref() == Some("response.failed")) .find(|event| event.event.as_deref() == Some("response.failed"))
.unwrap(); .unwrap();
let payload: Value = serde_json::from_str(&failed.data).unwrap(); let payload: Value = serde_json::from_str(&failed.data).unwrap();
error["headers"] = json!({"retry-after": "7"}); error["headers"] = json!({"retry-after": "7", "retry-after-ms":"7012"});
assert_eq!(payload["response"]["error"], error); assert_eq!(payload["response"]["error"], error);
assert!(bytes.ends_with(b"data: [DONE]\n\n")); assert!(bytes.ends_with(b"data: [DONE]\n\n"));
} }
@@ -2214,14 +2214,13 @@ async fn streaming_upstream_wire_failure_should_not_be_rewritten_as_a_gateway_er
#[tokio::test] #[tokio::test]
async fn streaming_upstream_error_event_should_be_translated_to_response_failed_for_sse() { async fn streaming_upstream_error_event_should_be_translated_to_response_failed_for_sse() {
for (error_type, code, client_code, kind, client_status, keeps_retry_after) in [ for (error_type, code, client_code, kind, client_status) in [
( (
"service_unavailable_error", "service_unavailable_error",
"server_is_overloaded", "server_is_overloaded",
"server_error", "server_error",
ProviderErrorKind::UpstreamCapacityUnavailable, ProviderErrorKind::UpstreamCapacityUnavailable,
503, 503,
false,
), ),
( (
"rate_limit_error", "rate_limit_error",
@@ -2229,7 +2228,6 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
"turn_rate_limit_exceeded", "turn_rate_limit_exceeded",
ProviderErrorKind::RateLimited, ProviderErrorKind::RateLimited,
429, 429,
true,
), ),
] { ] {
let trace = Arc::new(Trace::default()); let trace = Arc::new(Trace::default());
@@ -2306,16 +2304,17 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
.find(|event| event.event.as_deref() == Some("response.failed")) .find(|event| event.event.as_deref() == Some("response.failed"))
.expect("translated response.failed event"); .expect("translated response.failed event");
let failed: Value = serde_json::from_str(&failed.data).expect("response.failed JSON"); let failed: Value = serde_json::from_str(&failed.data).expect("response.failed JSON");
let mut expected = json!({ let expected = json!({
"type": "response.failed", "type": "response.failed",
"status": client_status, "status": client_status,
"headers": {"x-request-id": "req_test"}, "headers": {"Retry-After": "24", "retry-after-ms": "24000", "x-request-id": "req_test"},
"response": { "response": {
"id": "resp_test", "id": "resp_test",
"model": "public-model", "model": "public-model",
"status": "failed", "status": "failed",
"error": { "error": {
"type": error_type, "type": error_type,
"headers": {"retry-after": "24", "retry-after-ms": "24000"},
"code": client_code, "code": client_code,
"message": "Our servers are currently overloaded. Please try again later.", "message": "Our servers are currently overloaded. Please try again later.",
"param": null, "param": null,
@@ -2326,11 +2325,6 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
"sequence_number": 2, "sequence_number": 2,
"future_event_field": {"keep": true} "future_event_field": {"keep": true}
}); });
if keeps_retry_after {
expected["headers"]["Retry-After"] = json!("24");
expected["headers"]["retry-after-ms"] = json!("24000");
expected["response"]["error"]["headers"] = json!({"retry-after": "24"});
}
assert_eq!( assert_eq!(
( (
@@ -2346,18 +2340,38 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
} }
#[tokio::test] #[tokio::test]
async fn streaming_capacity_error_after_commit_offers_client_retry() { async fn streaming_errors_after_commit_preserve_upstream_retry_headers() {
for code in ["server_is_overloaded", "slow_down"] { for (kind, code, expected) in [
let trace = Arc::new(Trace::default()); (
let error = ProviderError::new(
ProviderErrorKind::UpstreamCapacityUnavailable, ProviderErrorKind::UpstreamCapacityUnavailable,
UpstreamSendState::Sent, "server_is_overloaded",
) "server_error",
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new( ),
"busy", (
Some(code.to_owned()), ProviderErrorKind::UpstreamCapacityUnavailable,
Some("service_unavailable_error".to_owned()), "slow_down",
)); "server_error",
),
(
ProviderErrorKind::QuotaExhausted,
"previous_response_not_found",
"previous_response_not_found",
),
] {
let trace = Arc::new(Trace::default());
let error = ProviderError::new(kind, UpstreamSendState::Sent)
.with_client_visible_upstream_response(
ClientVisibleUpstreamResponse::new(400, None, Bytes::new()).with_headers(vec![
ProviderResponseHeader::new("Retry-After", Bytes::from_static(b"309")),
ProviderResponseHeader::new("retry-after-ms", Bytes::from_static(b"309001")),
ProviderResponseHeader::new("x-unrelated", Bytes::from_static(b"omit")),
]),
)
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
"busy",
Some(code.to_owned()),
Some("service_unavailable_error".to_owned()),
));
let session = FakeSession::streaming( let session = FakeSession::streaming(
Arc::clone(&trace), Arc::clone(&trace),
vec![ vec![
@@ -2377,7 +2391,11 @@ async fn streaming_capacity_error_after_commit_offers_client_retry() {
.find(|event| event.event.as_deref() == Some("response.failed")) .find(|event| event.event.as_deref() == Some("response.failed"))
.expect("failed event"); .expect("failed event");
let failed: Value = serde_json::from_str(&failed.data).expect("JSON"); let failed: Value = serde_json::from_str(&failed.data).expect("JSON");
assert_eq!(failed["response"]["error"]["code"], "server_error"); assert_eq!(failed["response"]["error"]["code"], expected);
assert_eq!(
failed["response"]["error"]["headers"],
json!({"retry-after": "309", "retry-after-ms": "309001"})
);
assert_eq!(failed["response"]["error"]["message"], "busy"); assert_eq!(failed["response"]["error"]["message"], "busy");
assert_eq!(text.matches("event: response.failed").count(), 1); assert_eq!(text.matches("event: response.failed").count(), 1);
assert!(text.ends_with("data: [DONE]\n\n")); assert!(text.ends_with("data: [DONE]\n\n"));
@@ -1256,16 +1256,12 @@ fn capacity_failure_projection_preserves_wire_metadata_and_original_events() {
assert_eq!(sse_data["response"]["error"]["code"], "server_error"); assert_eq!(sse_data["response"]["error"]["code"], "server_error");
assert_eq!(sse_data["response"]["error"]["message"], "busy"); assert_eq!(sse_data["response"]["error"]["message"], "busy");
assert_eq!(sse_data["response"]["error"]["future"], 42); assert_eq!(sse_data["response"]["error"]["future"], 42);
assert_eq!( assert_eq!(sse_data["response"]["error"]["headers"], error["headers"]);
sse_data["response"]["error"]["headers"],
json!({"x-request-id":"req_capacity"})
);
let messages = ws.push_websocket(&event); let messages = ws.push_websocket(&event);
let ws_data: Value = serde_json::from_str(&messages[0]).expect("JSON"); let ws_data: Value = serde_json::from_str(&messages[0]).expect("JSON");
if event_type == "error" && status.is_some() { if event_type == "error" && status.is_some() {
let mut expected = original.clone(); let mut expected = original.clone();
expected["error"]["code"] = json!("server_error"); expected["error"]["code"] = json!("server_error");
expected["error"]["headers"] = json!({"x-request-id":"req_capacity"});
expected["status_code"] = json!(503); expected["status_code"] = json!(503);
assert_eq!(ws_data, expected); assert_eq!(ws_data, expected);
} else { } else {
@@ -340,8 +340,8 @@ async fn initial_capacity_failure_offers_client_retry_with_upstream_correlation(
assert_eq!(error["error"]["code"], "server_error"); assert_eq!(error["error"]["code"], "server_error");
assert_eq!(error["error"]["message"], "busy"); assert_eq!(error["error"]["message"], "busy");
assert_eq!(error["headers"]["x-request-id"], "req_capacity"); assert_eq!(error["headers"]["x-request-id"], "req_capacity");
assert!(error["headers"].get("retry-after").is_none()); assert_eq!(error["headers"]["retry-after"], "7");
assert!(error["headers"].get("retry-after-ms").is_none()); assert_eq!(error["headers"]["retry-after-ms"], "7000");
} }
} }
} }
@@ -720,7 +720,9 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
ClientVisibleUpstreamResponse::new( ClientVisibleUpstreamResponse::new(
400, 400,
Some(b"application/json".to_vec()), Some(b"application/json".to_vec()),
Bytes::from(json!({"error":detail}).to_string()), Bytes::from(
json!({"error":detail, "headers":{"Retry-After-Ms":"777"}}).to_string(),
),
) )
.with_headers(vec![header("x-request-id", b"req-quota-rejected")]), .with_headers(vec![header("x-request-id", b"req-quota-rejected")]),
); );
@@ -729,6 +731,7 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
assert_eq!(error["error"], detail); assert_eq!(error["error"], detail);
assert_eq!(error["headers"]["x-request-id"], "req-quota-rejected"); assert_eq!(error["headers"]["x-request-id"], "req-quota-rejected");
assert!(error["headers"].get("retry-after").is_none()); assert!(error["headers"].get("retry-after").is_none());
assert_eq!(error["headers"]["retry-after-ms"], "777");
} }
#[tokio::test] #[tokio::test]
@@ -101,8 +101,11 @@ pub(super) async fn fixture() -> AdminTestFixture {
fn usage_record() -> UsageListRecord { fn usage_record() -> UsageListRecord {
UsageListRecord { UsageListRecord {
platform_icon: None,
provider_account_upstream_peer: None, provider_account_upstream_peer: None,
has_upstream_error: false, has_upstream_error: false,
upstream_error_message: Some("private-sentinel-upstream".into()),
retry_after_ms: Some(30_000),
error_code: None, error_code: None,
error_message: None, error_message: None,
error_kind: None, error_kind: None,
+1
View File
@@ -24,6 +24,7 @@ http = "1.5.0"
http-body-util = "0.1.5" http-body-util = "0.1.5"
futures-timer = "3.0.3" futures-timer = "3.0.3"
gateway-protocol = { path = "../gateway-protocol" } gateway-protocol = { path = "../gateway-protocol" }
regex-automata = "0.4.19"
serde = { version = "1.0.228", features = ["derive", "rc"] } serde = { version = "1.0.228", features = ["derive", "rc"] }
serde_json = { version = "1.0.150", features = ["arbitrary_precision", "preserve_order"] } serde_json = { version = "1.0.150", features = ["arbitrary_precision", "preserve_order"] }
sha2 = "0.11.0" sha2 = "0.11.0"
@@ -1201,6 +1201,7 @@ where
.with_response_control(self.response_control.clone()) .with_response_control(self.response_control.clone())
.with_request_profile(self.request_profiles.get(candidate.provider()).cloned()) .with_request_profile(self.request_profiles.get(candidate.provider()).cloned())
.with_fast_mode(self.plan.fast_mode()) .with_fast_mode(self.plan.fast_mode())
.with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider()))
.with_pricing(self.plan.pricing()) .with_pricing(self.plan.pricing())
.with_request_location(self.plan.request_location().cloned()) .with_request_location(self.plan.request_location().cloned())
.with_openai_websocket_pool(*self.plan.openai_websocket_pool()) .with_openai_websocket_pool(*self.plan.openai_websocket_pool())
@@ -1479,7 +1480,7 @@ where
&& let Some(original) = self.last_retryable_failure.take() && let Some(original) = self.last_retryable_failure.take()
{ {
// 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求 // 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求
error = original.with_client_recovery_from(error); error = original.with_client_recovery_from(error, &self.last_retryable_failure_events);
self.last_retryable_failure_events.clear(); self.last_retryable_failure_events.clear();
} }
let kind = error.kind(); let kind = error.kind();
@@ -1547,11 +1547,8 @@ impl DefaultExecutionService {
) -> AccountProbeError { ) -> AccountProbeError {
let (source, send_state, upstream_response) = match error { let (source, send_state, upstream_response) = match error {
EngineError::Provider(provider_error) => { EngineError::Provider(provider_error) => {
let upstream_response = provider_error let upstream_response = AccountProbeUpstreamResponse::from_provider(provider_error);
.client_visible_upstream_response()
.map(AccountProbeUpstreamResponse::from_client_response);
let has_upstream_facts = provider_error.send_state() != UpstreamSendState::NotSent let has_upstream_facts = provider_error.send_state() != UpstreamSendState::NotSent
|| provider_error.upstream_status().is_some()
|| provider_error.upstream_code().is_some() || provider_error.upstream_code().is_some()
|| provider_error.client_visible_upstream_error().is_some() || provider_error.client_visible_upstream_error().is_some()
|| upstream_response.is_some(); || upstream_response.is_some();
@@ -16,6 +16,7 @@ pub mod nested;
pub mod observation; pub mod observation;
pub mod policy; pub mod policy;
pub mod probe; pub mod probe;
mod prompt_rewrite;
pub mod provider; pub mod provider;
pub mod response_control; pub mod response_control;
pub mod upstream_adapter; pub mod upstream_adapter;
@@ -324,6 +325,7 @@ pub struct RequestAttemptContext {
request_body_limit: Option<usize>, request_body_limit: Option<usize>,
lease_metadata: Option<Arc<crate::provider_ports::ProviderLeaseMetadata>>, lease_metadata: Option<Arc<crate::provider_ports::ProviderLeaseMetadata>>,
response_control: Option<response_control::ResponseControl>, response_control: Option<response_control::ResponseControl>,
prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
pricing: Arc<crate::metering::PricingOverrides>, pricing: Arc<crate::metering::PricingOverrides>,
request_profile: Option<crate::account::OpaqueProviderData>, request_profile: Option<crate::account::OpaqueProviderData>,
fast_mode: FastMode, fast_mode: FastMode,
@@ -396,6 +398,15 @@ impl RequestAttemptContext {
self self
} }
#[must_use]
pub fn with_prompt_rewrite_rules(
mut self,
rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
) -> Self {
self.prompt_rewrite_rules = rules;
self
}
#[must_use] #[must_use]
pub fn with_pricing(mut self, pricing: Arc<crate::metering::PricingOverrides>) -> Self { pub fn with_pricing(mut self, pricing: Arc<crate::metering::PricingOverrides>) -> Self {
self.pricing = pricing; self.pricing = pricing;
@@ -463,6 +474,7 @@ impl RequestAttemptContext {
request_id, request_id,
client_api_key_ref, client_api_key_ref,
request_profile: None, request_profile: None,
prompt_rewrite_rules: None,
pricing: Arc::default(), pricing: Arc::default(),
fast_mode: FastMode::Default, fast_mode: FastMode::Default,
openai_websocket_pool: Default::default(), openai_websocket_pool: Default::default(),
@@ -832,6 +844,21 @@ impl AttemptContext {
self.request.extension_scope() self.request.extension_scope()
} }
/// 计数由 Provider 解开入站封套后在现有正文上应用同一份规则
pub fn rewrite_count_prompt(
&self,
protocol: &str,
body: &mut serde_json::Map<String, serde_json::Value>,
) {
if let Some(rules) = &self.request.prompt_rewrite_rules
&& let Some(edit) = gateway_protocol::prompt_rewrite::plan(protocol, body, |text| {
rules.replace_prefix(text)
})
{
edit.apply(body);
}
}
/// 在已选账号并持有其 lease 后,以 owned terminal 执行本次 retry 的中间件链 /// 在已选账号并持有其 lease 后,以 owned terminal 执行本次 retry 的中间件链
/// ///
/// terminal 返回的 stream 仍须保持 cold;中间件不能取得 credential、发送状态、 /// terminal 返回的 stream 仍须保持 cold;中间件不能取得 credential、发送状态、
@@ -860,6 +887,12 @@ impl AttemptContext {
} else { } else {
terminal terminal
}; };
let terminal = match (&operation, &self.request.prompt_rewrite_rules) {
(crate::operation::Operation::Generate(_), Some(rules)) => {
prompt_rewrite::wrap(terminal, rules)
}
_ => terminal,
};
// 保护观察真正的 Provider terminal,先于 attempt 中间件的响应改写 // 保护观察真正的 Provider terminal,先于 attempt 中间件的响应改写
let terminal: provider::ProviderMiddlewareTerminal = let terminal: provider::ProviderMiddlewareTerminal =
if let Some(protection) = self.request.account_error_protection.clone() { if let Some(protection) = self.request.account_error_protection.clone() {
+13 -13
View File
@@ -5,9 +5,7 @@ use std::fmt;
use bytes::Bytes; use bytes::Bytes;
use futures::future::BoxFuture; use futures::future::BoxFuture;
use crate::error::{ use crate::error::{GatewayError, GatewayErrorKind, ProviderError, ProxyConnectionHint};
ClientVisibleUpstreamResponse, GatewayError, GatewayErrorKind, ProxyConnectionHint,
};
use crate::identity::ProviderKind; use crate::identity::ProviderKind;
use crate::routing::UpstreamModelId; use crate::routing::UpstreamModelId;
use crate::{ use crate::{
@@ -60,16 +58,18 @@ pub struct AccountProbeResult {
pub struct AccountProbeUpstreamResponse { pub struct AccountProbeUpstreamResponse {
status: u16, status: u16,
content_type: Option<Vec<u8>>, content_type: Option<Vec<u8>>,
body: Bytes, body: Option<Bytes>,
} }
impl AccountProbeUpstreamResponse { impl AccountProbeUpstreamResponse {
pub(crate) fn from_client_response(response: &ClientVisibleUpstreamResponse) -> Self { pub(crate) fn from_provider(error: &ProviderError) -> Option<Self> {
Self { let response = error.client_visible_upstream_response();
status: response.status(), // 即使没有可展示的响应正文,Provider 收到的状态码仍可用于诊断
content_type: response.content_type().map(<[u8]>::to_vec), Some(Self {
body: response.body().clone(), status: response.map(|r| r.status()).or(error.upstream_status())?,
} content_type: response.and_then(|r| r.content_type()).map(<[u8]>::to_vec),
body: response.map(|r| r.body().clone()),
})
} }
#[must_use] #[must_use]
@@ -83,8 +83,8 @@ impl AccountProbeUpstreamResponse {
} }
#[must_use] #[must_use]
pub const fn body(&self) -> &Bytes { pub const fn body(&self) -> Option<&Bytes> {
&self.body self.body.as_ref()
} }
} }
@@ -97,7 +97,7 @@ impl fmt::Debug for AccountProbeUpstreamResponse {
"content_type", "content_type",
&self.content_type.as_ref().map(|_| "<present>"), &self.content_type.as_ref().map(|_| "<present>"),
) )
.field("body", &"<redacted>") .field("body", &self.body.as_ref().map(|_| "<redacted>"))
.finish() .finish()
} }
} }
@@ -0,0 +1,25 @@
//! 在 attempt 中间件提交后应用所选平台的生成规则
use super::provider::ProviderMiddlewareTerminal;
use crate::{operation::Operation, settings::prompt_rewrite::ProviderPromptRules};
use std::sync::Arc;
pub(super) fn wrap(
terminal: ProviderMiddlewareTerminal,
rules: &Arc<ProviderPromptRules>,
) -> ProviderMiddlewareTerminal {
let rules = Arc::clone(rules);
Box::new(move |mut operation, headers| {
if let Operation::Generate(request) = &mut operation {
let payload = request.protocol_payload();
if let Some(edit) =
gateway_protocol::prompt_rewrite::plan(payload.protocol(), payload.body(), |text| {
rules.replace_prefix(text)
})
{
request.apply_prompt_edit(edit);
}
}
terminal(operation, headers)
})
}
+53 -1
View File
@@ -1093,8 +1093,60 @@ impl ProviderError {
self.client_visible_upstream_response.as_deref() self.client_visible_upstream_response.as_deref()
} }
/// 将原失败携带的等待头补入客户端响应,保留响应中已有的值
pub fn extend_client_retry_headers(
&self,
headers: &mut Vec<ProviderResponseHeader>,
events: &[ProviderEvent],
) {
let original = self.client_visible_upstream_response();
let body = std::cell::LazyCell::new(|| {
original.and_then(|response| serde_json::from_slice(response.body()).ok())
});
let event = events
.iter()
.rev()
.find_map(ProviderEvent::wire_event)
.map(|wire| wire.data());
for name in gateway_protocol::http::RETRY_AFTER_HEADERS {
if headers
.iter()
.any(|header| header.name().eq_ignore_ascii_case(name))
{
continue;
}
if let Some(header) = original.and_then(|response| {
response
.headers()
.iter()
.rev()
.find(|header| header.name().eq_ignore_ascii_case(name))
}) {
headers.push(header.clone());
continue;
}
let read = |value| gateway_protocol::openai::events::error_event_header(value, name);
if let Some(value) = event
.and_then(read)
.or_else(|| body.as_ref().and_then(read))
{
headers.push(ProviderResponseHeader::new(
name,
Bytes::copy_from_slice(value.as_bytes()),
));
}
}
}
/// 绑定迁移完成后仅替换客户端恢复投影,保留原始失败的诊断与计费事实 /// 绑定迁移完成后仅替换客户端恢复投影,保留原始失败的诊断与计费事实
pub(crate) fn with_client_recovery_from(mut self, recovery: Self) -> Self { pub(crate) fn with_client_recovery_from(
mut self,
mut recovery: Self,
events: &[ProviderEvent],
) -> Self {
if let Some(response) = recovery.client_visible_upstream_response.as_deref_mut() {
self.extend_client_retry_headers(&mut response.headers, events);
}
if let Some(reason) = recovery.continuation_unavailable_reason() { if let Some(reason) = recovery.continuation_unavailable_reason() {
self = self.with_continuation_unavailable_reason(reason); self = self.with_continuation_unavailable_reason(reason);
} }
@@ -462,6 +462,23 @@ impl ClientTurn {
} }
impl GenerateRequest { impl GenerateRequest {
/// 只在命中后对共享请求执行写时复制,重试持有的原请求仍可独立使用
pub(crate) fn apply_prompt_edit(&mut self, edit: gateway_protocol::prompt_rewrite::PromptEdit) {
let wire = match self.protocol_payload().raw_json_body() {
Some(body) => {
let Some(updated) = edit.wire(body) else {
return;
};
Some(Bytes::from(updated))
}
None => None,
};
let payload = Arc::make_mut(&mut self.payload);
edit.apply(&mut payload.protocol_payload.body);
payload.protocol_payload.raw_json_body = wire;
// 只编辑字符串内容,能力、角色与工具结构仍使用已有的 wire_facts
}
/// 返回可信入口协议,直接转换只能更新当前 wire,不能改写请求来源 /// 返回可信入口协议,直接转换只能更新当前 wire,不能改写请求来源
#[must_use] #[must_use]
pub fn source_protocol(&self) -> &str { pub fn source_protocol(&self) -> &str {
@@ -714,6 +714,7 @@ impl ProviderCandidate {
/// 一次请求冻结的 Provider 尝试顺序 /// 一次请求冻结的 Provider 尝试顺序
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RoutingPlan { pub struct RoutingPlan {
prompt_rewrite: Arc<crate::settings::prompt_rewrite::CompiledPromptRewrite>,
account_error_protection: Arc<crate::account::CompiledAccountErrorProtection>, account_error_protection: Arc<crate::account::CompiledAccountErrorProtection>,
account_error_protection_revision: u64, account_error_protection_revision: u64,
request_body_limit: usize, request_body_limit: usize,
@@ -732,6 +733,14 @@ pub struct RoutingPlan {
} }
impl RoutingPlan { impl RoutingPlan {
#[must_use]
pub fn prompt_rewrite_rules(
&self,
provider: &ProviderKind,
) -> Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>> {
self.prompt_rewrite.for_provider(provider)
}
#[must_use] #[must_use]
pub const fn account_error_protection_revision(&self) -> u64 { pub const fn account_error_protection_revision(&self) -> u64 {
self.account_error_protection_revision self.account_error_protection_revision
@@ -2060,6 +2060,7 @@ impl RuntimeSnapshot {
self.settings.values.max_retry_after_seconds, self.settings.values.max_retry_after_seconds,
)), )),
config_revision: self.revision, config_revision: self.revision,
prompt_rewrite: Arc::clone(&self.settings.prompt_rewrite),
pricing: Arc::clone(&self.settings.values.pricing), pricing: Arc::clone(&self.settings.values.pricing),
openai_websocket_pool: *self.settings.values.openai_websocket_pool(), openai_websocket_pool: *self.settings.values.openai_websocket_pool(),
openai_request_settings: self.settings.values.openai_request_settings().clone(), openai_request_settings: self.settings.values.openai_request_settings().clone(),
@@ -2153,6 +2154,7 @@ impl RuntimeSnapshot {
self.settings.values.max_retry_after_seconds, self.settings.values.max_retry_after_seconds,
)), )),
config_revision: self.revision, config_revision: self.revision,
prompt_rewrite: Arc::clone(&self.settings.prompt_rewrite),
pricing: Arc::clone(&self.settings.values.pricing), pricing: Arc::clone(&self.settings.values.pricing),
openai_websocket_pool: *self.settings.values.openai_websocket_pool(), openai_websocket_pool: *self.settings.values.openai_websocket_pool(),
openai_request_settings: self.settings.values.openai_request_settings().clone(), openai_request_settings: self.settings.values.openai_request_settings().clone(),
@@ -13,6 +13,7 @@ use crate::{
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub(crate) struct CompiledSettings { pub(crate) struct CompiledSettings {
pub(crate) values: SettingsValues, pub(crate) values: SettingsValues,
pub(crate) prompt_rewrite: std::sync::Arc<super::prompt_rewrite::CompiledPromptRewrite>,
pub(crate) account_error_protection: pub(crate) account_error_protection:
std::sync::Arc<crate::account::CompiledAccountErrorProtection>, std::sync::Arc<crate::account::CompiledAccountErrorProtection>,
pub(crate) privacy: Option<std::sync::Arc<dyn super::privacy::CompiledPrivacyPolicy>>, pub(crate) privacy: Option<std::sync::Arc<dyn super::privacy::CompiledPrivacyPolicy>>,
@@ -40,6 +41,18 @@ impl CompiledSettings {
.account_error_protection .account_error_protection
.validate() .validate()
.map_err(|_| InvalidSettings)?; .map_err(|_| InvalidSettings)?;
let prompt_rewrite = previous
.filter(|prior| prior.values.prompt_rewrite_rules == settings.prompt_rewrite_rules)
.map_or_else(
|| {
super::prompt_rewrite::CompiledPromptRewrite::new(std::sync::Arc::clone(
&settings.prompt_rewrite_rules,
))
.map(std::sync::Arc::new)
.map_err(|_| InvalidSettings)
},
|prior| Ok(prior.prompt_rewrite.clone()),
)?;
let account_error_protection = previous let account_error_protection = previous
.filter(|previous| { .filter(|previous| {
previous.values.account_error_protection == settings.account_error_protection previous.values.account_error_protection == settings.account_error_protection
@@ -130,6 +143,7 @@ impl CompiledSettings {
} }
} }
Ok(Self { Ok(Self {
prompt_rewrite,
account_error_protection, account_error_protection,
account_selection_policy, account_selection_policy,
client_queue_policy, client_queue_policy,
@@ -3,6 +3,7 @@
pub(crate) mod compiled; pub(crate) mod compiled;
mod openai; mod openai;
pub mod privacy; pub mod privacy;
pub mod prompt_rewrite;
pub mod request_profiles; pub mod request_profiles;
mod values; mod values;
mod websocket; mod websocket;
@@ -40,7 +40,7 @@ impl Default for OpenAiRequestSettings {
Self { Self {
request_country: Default::default(), request_country: Default::default(),
oauth_guardian_review_model: true, oauth_guardian_review_model: true,
residency: Some("us".to_owned()), residency: None,
account_routing_override: None, account_routing_override: None,
} }
} }
@@ -58,7 +58,7 @@ pub enum OpenAiRequestCountry {
impl Default for OpenAiRequestCountry { impl Default for OpenAiRequestCountry {
fn default() -> Self { fn default() -> Self {
Self::FollowLocation {} Self::Default {}
} }
} }
@@ -0,0 +1,253 @@
//! 按目标上游索引并共享已编译规则,按配置顺序匹配系统提示词开头
use crate::identity::ProviderKind;
use regex_automata::{
Anchored, Input,
meta::{BuildError, Regex},
};
use serde::{Deserialize, Serialize};
use std::{
borrow::Cow,
collections::{BTreeMap, BTreeSet},
fmt,
sync::{Arc, OnceLock},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PromptMatchMode {
Prefix,
Regex,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PromptRewriteRule {
#[serde(deserialize_with = "nonempty_name")]
name: String,
#[serde(default)]
providers: BTreeSet<ProviderKind>,
match_mode: PromptMatchMode,
pattern: PromptPattern,
replacement: String,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(transparent)]
struct PromptPattern {
#[serde(deserialize_with = "nonempty_pattern")]
text: String,
// API、管理用例和持久化边界校验同一份不可变规则时,共用编译结果
#[serde(skip)]
regex: OnceLock<Result<Arc<Regex>, Box<BuildError>>>,
}
impl PromptPattern {
fn regex(&self) -> Result<&Arc<Regex>, Box<BuildError>> {
self.regex
.get_or_init(|| Regex::new(&self.text).map(Arc::new).map_err(Box::new))
.as_ref()
.map_err(Clone::clone)
}
}
impl PartialEq for PromptPattern {
fn eq(&self, other: &Self) -> bool {
self.text == other.text
}
}
impl Eq for PromptPattern {}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PromptRewritePreviewRequest {
pub rule: PromptRewriteRule,
pub text: String,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct PromptRewritePreviewResult {
pub matched: bool,
pub output: String,
}
impl PromptRewriteRule {
fn compile(&self) -> Result<CompiledRule, Box<BuildError>> {
Ok(CompiledRule {
matcher: match self.match_mode {
PromptMatchMode::Prefix => Matcher::Prefix(self.pattern.text.clone()),
PromptMatchMode::Regex if self.replacement.contains('$') => {
Matcher::RegexCaptures(Arc::clone(self.pattern.regex()?))
}
PromptMatchMode::Regex => Matcher::Regex(Arc::clone(self.pattern.regex()?)),
},
replacement: self.replacement.clone(),
})
}
pub fn validate(&self) -> Result<(), Box<BuildError>> {
if self.match_mode == PromptMatchMode::Regex {
self.pattern.regex()?;
}
Ok(())
}
pub fn preview(&self, text: &str) -> Result<PromptRewritePreviewResult, Box<BuildError>> {
let compiled = self.compile()?;
let result = compiled.replace_prefix(text);
Ok(PromptRewritePreviewResult {
matched: result.is_some(),
output: result.unwrap_or(Cow::Borrowed(text)).into_owned(),
})
}
}
enum Matcher {
Prefix(String),
Regex(Arc<Regex>),
RegexCaptures(Arc<Regex>),
}
struct CompiledRule {
matcher: Matcher,
replacement: String,
}
// 编译后的表达式和替换内容同样可能包含敏感提示词,不输出到诊断日志
impl fmt::Debug for CompiledRule {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CompiledRule").finish_non_exhaustive()
}
}
impl CompiledRule {
fn replace_prefix<'a>(&self, text: &'a str) -> Option<Cow<'a, str>> {
let (end, replacement) = match &self.matcher {
Matcher::Prefix(pattern) => {
text.strip_prefix(pattern)?;
(pattern.len(), Cow::Borrowed(self.replacement.as_str()))
}
Matcher::RegexCaptures(regex) => {
// 使用引擎的起始位置约束,不拼接表达式,避免分组与注释改变边界
let mut captures = regex.create_captures();
regex.captures(Input::new(text).anchored(Anchored::Yes), &mut captures);
let matched = captures.get_match()?;
let mut expanded = String::new();
captures.interpolate_string_into(text, &self.replacement, &mut expanded);
(matched.end(), Cow::Owned(expanded))
}
Matcher::Regex(regex) => (
regex.find(Input::new(text).anchored(Anchored::Yes))?.end(),
Cow::Borrowed(self.replacement.as_str()),
),
};
if text[..end] == *replacement {
return Some(Cow::Borrowed(text));
}
let mut updated = match replacement {
Cow::Owned(expanded) => expanded,
Cow::Borrowed(literal) => {
let mut updated = String::with_capacity(literal.len() + (text.len() - end));
updated.push_str(literal);
updated
}
};
updated.push_str(&text[end..]);
Some(Cow::Owned(updated))
}
}
impl fmt::Debug for PromptRewriteRule {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PromptRewriteRule")
.field("providers", &self.providers)
.finish_non_exhaustive()
}
}
fn nonempty_name<'de, D: serde::Deserializer<'de>>(de: D) -> Result<String, D::Error> {
let name = String::deserialize(de)?;
if name.trim().is_empty() {
return Err(serde::de::Error::custom("规则名称不能为空"));
}
Ok(name)
}
fn nonempty_pattern<'de, D: serde::Deserializer<'de>>(de: D) -> Result<String, D::Error> {
let pattern = String::deserialize(de)?;
if pattern.is_empty() {
return Err(serde::de::Error::custom("匹配文本不能为空"));
}
Ok(pattern)
}
#[derive(Debug)]
pub struct ProviderPromptRules {
rules: Arc<[CompiledRule]>,
global: Arc<BTreeSet<usize>>,
scoped: BTreeSet<usize>,
}
impl ProviderPromptRules {
pub fn replace_prefix(&self, text: &str) -> Option<String> {
// 命中但内容未变化也必须终止,不能落到后续规则
match self
.global
.union(&self.scoped)
.map(|&index| &self.rules[index])
.find_map(|rule| rule.replace_prefix(text))?
{
Cow::Borrowed(_) => None,
Cow::Owned(updated) => Some(updated),
}
}
}
#[derive(Debug, Default)]
pub struct CompiledPromptRewrite {
all: Option<Arc<ProviderPromptRules>>,
by_provider: BTreeMap<ProviderKind, Arc<ProviderPromptRules>>,
}
impl CompiledPromptRewrite {
pub fn new(rules: Arc<[PromptRewriteRule]>) -> Result<Self, Box<BuildError>> {
let mut global = BTreeSet::new();
let mut scoped = BTreeMap::<_, BTreeSet<_>>::new();
for (index, rule) in rules.iter().enumerate() {
if rule.providers.is_empty() {
global.insert(index);
} else {
for provider in &rule.providers {
scoped.entry(provider.clone()).or_default().insert(index);
}
}
}
let rules: Arc<[CompiledRule]> = rules
.iter()
.map(PromptRewriteRule::compile)
.collect::<Result<_, _>>()?;
let global = Arc::new(global);
let selection = |scoped| {
Arc::new(ProviderPromptRules {
rules: Arc::clone(&rules),
global: Arc::clone(&global),
scoped,
})
};
Ok(Self {
all: (!global.is_empty()).then(|| selection(BTreeSet::new())),
by_provider: scoped
.into_iter()
.map(|(id, indices)| (id, selection(indices)))
.collect(),
})
}
pub fn for_provider(&self, provider: &ProviderKind) -> Option<Arc<ProviderPromptRules>> {
self.by_provider
.get(provider)
.or(self.all.as_ref())
.cloned()
}
}
@@ -8,6 +8,8 @@ use crate::identity::ProviderKind;
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct SettingsValues { pub struct SettingsValues {
#[serde(default)]
pub(crate) prompt_rewrite_rules: Arc<[super::prompt_rewrite::PromptRewriteRule]>,
#[serde(default)] #[serde(default)]
pub(crate) account_error_protection: crate::account::AccountErrorProtection, pub(crate) account_error_protection: crate::account::AccountErrorProtection,
#[serde(skip, default = "initial_protection_revision")] #[serde(skip, default = "initial_protection_revision")]
@@ -45,6 +47,15 @@ fn initial_protection_revision() -> u64 {
} }
impl SettingsValues { impl SettingsValues {
#[must_use]
pub fn with_prompt_rewrite_rules(
mut self,
rules: Vec<super::prompt_rewrite::PromptRewriteRule>,
) -> Self {
self.prompt_rewrite_rules = rules.into();
self
}
#[must_use] #[must_use]
pub const fn with_account_error_protection_revision(mut self, revision: u64) -> Self { pub const fn with_account_error_protection_revision(mut self, revision: u64) -> Self {
self.account_error_protection_revision = revision; self.account_error_protection_revision = revision;
@@ -222,6 +233,7 @@ impl SettingsValues {
min_codex_cli_version: Option<String>, min_codex_cli_version: Option<String>,
) -> Self { ) -> Self {
Self { Self {
prompt_rewrite_rules: Default::default(),
account_error_protection: Default::default(), account_error_protection: Default::default(),
account_error_protection_revision: 1, account_error_protection_revision: 1,
request_profiles: Arc::default(), request_profiles: Arc::default(),
@@ -2525,11 +2525,33 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
.with_continuation_recovery_disposition( .with_continuation_recovery_disposition(
ContinuationRecoveryDisposition::ClientReplayRequired, ContinuationRecoveryDisposition::ClientReplayRequired,
); );
let original = if committed_prelude {
let event = json!({"type":"response.failed", "response":{"error":{
"headers":{"Retry-After":seconds.to_string(), "Retry-After-Ms":"317001", "x-private":"omit"}
}}});
original.with_atomic_client_events(vec![ProviderEvent::wire(
ProtocolWireEvent::json("openai", Some("response.failed".to_owned()), event)
.unwrap(),
)])
} else {
original.with_client_visible_upstream_response(
ClientVisibleUpstreamResponse::new(503, None, Bytes::from(original_body.clone()))
.with_headers(vec![gateway_core::event::ProviderResponseHeader::new(
"Retry-After-Ms",
Bytes::from_static(b"309001"),
)]),
)
};
let recovery = if replacement { let recovery = if replacement {
ProviderError::new( ProviderError::new(
ProviderErrorKind::ContinuationRecoveryRequired, ProviderErrorKind::ContinuationRecoveryRequired,
UpstreamSendState::NotSent, UpstreamSendState::NotSent,
) )
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
400,
None,
Bytes::from_static(b"{}"),
))
.with_continuation_unavailable_reason("account_rotated") .with_continuation_unavailable_reason("account_rotated")
.with_continuation_recovery_disposition( .with_continuation_recovery_disposition(
ContinuationRecoveryDisposition::ClientReplayRequired, ContinuationRecoveryDisposition::ClientReplayRequired,
@@ -2602,6 +2624,29 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
error.continuation_unavailable_reason(), error.continuation_unavailable_reason(),
(replacement && expected_attempts == 2).then_some("account_rotated") (replacement && expected_attempts == 2).then_some("account_rotated")
); );
if replacement && expected_attempts == 2 {
let response = error.client_visible_upstream_response().unwrap();
assert_eq!(response.status(), 400);
let headers: Vec<_> = response
.headers()
.iter()
.map(|header| (header.name().to_ascii_lowercase(), header.value().as_ref()))
.collect();
assert_eq!(
headers,
vec![
("retry-after".to_owned(), seconds.to_string().as_bytes()),
(
"retry-after-ms".to_owned(),
if committed_prelude {
b"317001"
} else {
b"309001"
}
),
]
);
}
let contexts = provider.contexts.lock().unwrap(); let contexts = provider.contexts.lock().unwrap();
assert_eq!(contexts.len(), expected_attempts); assert_eq!(contexts.len(), expected_attempts);
if contexts.len() == 2 { if contexts.len() == 2 {
@@ -3509,8 +3509,10 @@ fn account_probe_should_not_write_to_the_persistent_execution_store() {
#[test] #[test]
fn probe_failures_should_be_observable_without_a_model_request_row() { fn probe_failures_should_be_observable_without_a_model_request_row() {
let store = Arc::new(TrackingExecutionStore::default()); let store = Arc::new(TrackingExecutionStore::default());
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>]) let providers = ProviderRegistry::new([
.expect("provider registry"); Arc::new(FailingProvider { include_body: true }) as Arc<dyn Provider>
])
.expect("provider registry");
let service = DefaultExecutionService::new( let service = DefaultExecutionService::new(
RuntimeSnapshotHandle::new(probe_snapshot()), RuntimeSnapshotHandle::new(probe_snapshot()),
store.clone(), store.clone(),
@@ -3547,7 +3549,9 @@ fn probe_failures_should_be_observable_without_a_model_request_row() {
); );
assert_eq!( assert_eq!(
upstream.body(), upstream.body(),
&Bytes::from_static(br#"{"error":{"message":"source upstream failure"}}"#), Some(&Bytes::from_static(
br#"{"error":{"message":"source upstream failure"}}"#
)),
); );
assert!(!format!("{error:?}").contains("source upstream failure")); assert!(!format!("{error:?}").contains("source upstream failure"));
assert!(!store.touched.load(Ordering::SeqCst)); assert!(!store.touched.load(Ordering::SeqCst));
@@ -3687,8 +3691,10 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
fail_probe_observation: AtomicBool::new(true), fail_probe_observation: AtomicBool::new(true),
..TrackingExecutionStore::default() ..TrackingExecutionStore::default()
}); });
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>]) let providers = ProviderRegistry::new([Arc::new(FailingProvider {
.expect("provider registry"); include_body: false,
}) as Arc<dyn Provider>])
.expect("provider registry");
let service = DefaultExecutionService::new( let service = DefaultExecutionService::new(
RuntimeSnapshotHandle::new(probe_snapshot()), RuntimeSnapshotHandle::new(probe_snapshot()),
store.clone(), store.clone(),
@@ -3715,9 +3721,15 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
assert_eq!(error.kind(), GatewayErrorKind::UpstreamUnavailable); assert_eq!(error.kind(), GatewayErrorKind::UpstreamUnavailable);
assert!(!store.touched.load(Ordering::SeqCst)); assert!(!store.touched.load(Ordering::SeqCst));
assert!(store.probe_failures().is_empty()); assert!(store.probe_failures().is_empty());
let upstream = error.upstream_response().unwrap();
assert_eq!(upstream.status(), 403);
assert!(upstream.body().is_none());
assert!(upstream.content_type().is_none());
} }
struct FailingProvider; struct FailingProvider {
include_body: bool,
}
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
enum CatalogProvider { enum CatalogProvider {
@@ -4055,6 +4067,13 @@ impl Provider for FailingProvider {
_request: ProviderRequest, _request: ProviderRequest,
_context: AttemptContext, _context: AttemptContext,
) -> Result<ProviderStream, ProviderError> { ) -> Result<ProviderStream, ProviderError> {
if !self.include_body {
return Err(ProviderError::new(
ProviderErrorKind::PermissionDenied,
UpstreamSendState::Sent,
)
.with_status(403));
}
Err( Err(
ProviderError::new(ProviderErrorKind::Transport, UpstreamSendState::NotSent) ProviderError::new(ProviderErrorKind::Transport, UpstreamSendState::NotSent)
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new( .with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
@@ -16,6 +16,7 @@ mod policy;
mod provider_ports; mod provider_ports;
mod routing; mod routing;
mod runtime; mod runtime;
mod settings;
mod task; mod task;
mod upstream; mod upstream;
@@ -437,3 +437,30 @@ fn chat_source_survives_the_one_authorized_wire_translation() {
.is_err() .is_err()
); );
} }
#[test]
fn unmatched_prompt_prefixes_do_not_allocate_for_large_histories() {
use gateway_core::{identity::ProviderKind, settings::prompt_rewrite::CompiledPromptRewrite};
use gateway_protocol::prompt_rewrite::plan;
let body = serde_json::json!({"instructions": "Custom instructions", "input": "x".repeat(1024 * 1024)});
let body = body.as_object().unwrap();
let rules = CompiledPromptRewrite::new(
serde_json::from_value(json!([{
"name":"客户端身份", "matchMode":"prefix", "pattern":"Unknown", "replacement":"Changed"
}]))
.unwrap(),
)
.unwrap()
.for_provider(&ProviderKind::new("openai").unwrap())
.unwrap();
let stats = allocation_counter::measure(|| {
for _ in 0..1000 {
assert!(
plan("openai", std::hint::black_box(body), |text| rules
.replace_prefix(text))
.is_none()
);
}
});
assert_eq!(stats.count_total, 0);
}
@@ -1817,6 +1817,77 @@ fn withdrawn_provider_keeps_accounts_without_becoming_a_route_or_expanding_group
} }
} }
#[test]
fn prompt_rules_are_selected_once_by_upstream_and_keep_global_order() {
let snapshot = super::snapshot();
let plan_for = |rules| {
let configured = snapshot
.with_settings(&snapshot.settings().clone().with_prompt_rewrite_rules(rules))
.unwrap();
configured
.plan(
&PublicModelId::new("gpt-5.4").unwrap(),
&super::operation(),
configured.all_account_scope(),
&Default::default(),
)
.unwrap()
};
let openai = ProviderKind::new("openai").unwrap();
let agy = ProviderKind::new("antigravity").unwrap();
let xai = ProviderKind::new("xai").unwrap();
let scoped = |targets, prefix| {
serde_json::from_value(
serde_json::json!({"name": "客户端身份", "providers": targets, "matchMode":"prefix", "pattern": prefix, "replacement": ""}),
)
.unwrap()
};
let only_agy = plan_for(vec![scoped(vec!["antigravity"], "example"); 20]);
assert!(only_agy.prompt_rewrite_rules(&openai).is_none());
let selected = only_agy.prompt_rewrite_rules(&agy).unwrap();
assert_eq!(
selected.replace_prefix("example suffix").as_deref(),
Some(" suffix")
);
assert!(Arc::ptr_eq(
&selected,
&only_agy.prompt_rewrite_rules(&agy).unwrap()
));
let mixed = plan_for(vec![
scoped(vec![], "shared first"),
scoped(vec!["xai", "antigravity"], "shared"),
scoped(vec![], "sh"),
]);
for provider in [&agy, &xai] {
let rules = mixed.prompt_rewrite_rules(provider).unwrap();
assert_eq!(rules.replace_prefix("shared first!").as_deref(), Some("!"));
assert_eq!(
rules.replace_prefix("shared second").as_deref(),
Some(" second")
);
}
let global = mixed.prompt_rewrite_rules(&openai).unwrap();
assert_eq!(
global.replace_prefix("shared second").as_deref(),
Some("ared second")
);
}
#[test]
fn prompt_rewrite_invalid_regex_cannot_replace_a_working_snapshot() {
let snapshot = super::snapshot();
let rules = serde_json::from_value(serde_json::json!([{
"name":"DSH", "matchMode":"regex", "pattern":"[", "replacement":""
}]))
.unwrap();
assert!(
snapshot
.with_settings(&snapshot.settings().clone().with_prompt_rewrite_rules(rules))
.is_err()
);
}
#[test] #[test]
fn routing_plans_share_frozen_pricing_after_a_new_snapshot_is_published() { fn routing_plans_share_frozen_pricing_after_a_new_snapshot_is_published() {
use gateway_core::{metering::PricingOverrides, runtime::RuntimeSnapshotHandle}; use gateway_core::{metering::PricingOverrides, runtime::RuntimeSnapshotHandle};
@@ -2546,7 +2617,7 @@ fn global_request_location_should_be_frozen_when_snapshot_is_published() {
assert_eq!( assert_eq!(
plan(&handle.acquire().unwrap()).openai_request_settings(), plan(&handle.acquire().unwrap()).openai_request_settings(),
&gateway_core::settings::OpenAiRequestSettings { &gateway_core::settings::OpenAiRequestSettings {
residency: None, request_country: OpenAiRequestCountry::FollowLocation {},
..Default::default() ..Default::default()
} }
); );
@@ -0,0 +1,3 @@
//! 运行设置的行为测试
mod prompt_rewrite;
@@ -0,0 +1,129 @@
//! 预览与转发共享匹配语义,配置编译错误不进入运行快照
use gateway_core::{
identity::ProviderKind,
settings::prompt_rewrite::{CompiledPromptRewrite, PromptRewriteRule},
};
use serde_json::json;
fn rule(mode: &str, pattern: &str, replacement: &str) -> PromptRewriteRule {
serde_json::from_value(json!({
"name": "测试规则", "matchMode": mode, "pattern": pattern,
"replacement": replacement, "providers": []
}))
.unwrap()
}
#[test]
fn prompt_rewrite_preview_and_runtime_share_captures_flags_and_prefix_semantics() {
for (mode, pattern, replacement, input, expected, matched) in [
(
"regex",
r"(?is)you are (?<agent>\w+).*?END",
"Agent: ${agent} / $1 / $$",
"You are DSH\nbody\nEND\n用户内容",
"Agent: DSH / DSH / $\n用户内容",
true,
),
(
"regex",
r"(?m)^DSH|Other",
"New",
"Before\nDSH",
"Before\nDSH",
false,
),
(
"regex",
r"DSH|Other",
"New",
"Before Other",
"Before Other",
false,
),
(
"regex",
r"^",
"Start: ",
"用户内容",
"Start: 用户内容",
true,
),
(
"regex",
r"(?x)(DSH) # identity",
"$1 revised",
"DSH suffix",
"DSH revised suffix",
true,
),
("regex", r"(DSH)", "$1", "DSH suffix", "DSH suffix", true),
("prefix", "DSH.*", "$1", "DSH.* suffix", "$1 suffix", true),
(
"regex",
r"(?s)DSH.*?END\n",
"",
"DSH\nidentity\nEND\n用户内容",
"用户内容",
true,
),
] {
let rule = rule(mode, pattern, replacement);
let preview = rule.preview(input).unwrap();
assert_eq!(preview.matched, matched, "{pattern}");
assert_eq!(preview.output, expected, "{pattern}");
let compiled = CompiledPromptRewrite::new(vec![rule].into()).unwrap();
let runtime = compiled
.for_provider(&ProviderKind::new("antigravity").unwrap())
.unwrap();
let updated = runtime.replace_prefix(input);
assert_eq!(updated.as_deref().unwrap_or(input), expected, "{pattern}");
assert_eq!(updated.is_some(), expected != input);
}
}
#[test]
fn prompt_rewrite_noop_first_match_stops_following_rules() {
let compiled = CompiledPromptRewrite::new(
vec![
rule("regex", "(DSH)", "$1"),
rule("prefix", "DSH", "Changed"),
]
.into(),
)
.unwrap();
let rules = compiled
.for_provider(&ProviderKind::new("openai").unwrap())
.unwrap();
assert_eq!(rules.replace_prefix("DSH suffix"), None);
}
#[test]
fn prompt_rewrite_rejects_invalid_unsupported_and_oversized_regexes() {
for pattern in ["[", "DSH)|Other(?:", r"(?=DSH)", r"(DSH)\1", "a{100000000}"] {
let rule = rule("regex", pattern, "");
assert!(rule.validate().is_err());
assert!(rule.preview("DSH").is_err());
assert!(CompiledPromptRewrite::new(vec![rule.clone()].into()).is_err());
}
}
#[test]
fn repeated_validation_of_unchanged_rules_does_not_allocate() {
for mode in ["prefix", "regex"] {
let rule = rule(mode, "(DSH)", "$1 revised");
rule.validate().unwrap();
let allocations = allocation_counter::measure(|| rule.validate().unwrap());
assert_eq!(allocations.count_total, 0, "{mode}");
}
}
#[test]
fn prompt_rewrite_debug_hides_patterns_and_replacements() {
let rule = rule("regex", "private-pattern", "private-replacement");
let compiled = CompiledPromptRewrite::new(vec![rule.clone()].into()).unwrap();
for diagnostic in [format!("{rule:?}"), format!("{compiled:?}")] {
assert!(!diagnostic.contains("private-pattern"));
assert!(!diagnostic.contains("private-replacement"));
}
}
@@ -24,7 +24,7 @@ gateway-plugin-sdk = { path = "../sdk", features = ["io"] }
gateway-protocol = { path = "../../gateway-protocol" } gateway-protocol = { path = "../../gateway-protocol" }
hex = "0.4.3" hex = "0.4.3"
image = { version = "0.25.8", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] } image = { version = "0.25.8", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }
jsonschema = { version = "0.61.2", default-features = false } jsonschema = { version = "0.63.2", default-features = false }
roxmltree = "0.21.1" roxmltree = "0.21.1"
semver = "1.0.27" semver = "1.0.27"
secrecy = "0.10.3" secrecy = "0.10.3"
@@ -3,7 +3,7 @@
use std::{ use std::{
collections::BTreeMap, collections::BTreeMap,
sync::{ sync::{
Arc, Mutex, Arc, Mutex, MutexGuard,
atomic::{AtomicBool, Ordering}, atomic::{AtomicBool, Ordering},
}, },
time::{Duration, Instant}, time::{Duration, Instant},
@@ -31,7 +31,8 @@ pub(crate) struct Shared {
pub stopped: watch::Sender<bool>, pub stopped: watch::Sender<bool>,
callback_slots: Arc<Semaphore>, callback_slots: Arc<Semaphore>,
pub(super) execution: ExecutionCapacity, pub(super) execution: ExecutionCapacity,
cancellations_changed: Notify, maximum_queue_timeout: Duration,
pub(super) cancellations_changed: Notify,
} }
struct State { struct State {
@@ -46,7 +47,7 @@ struct PendingCall {
handler: Arc<dyn CallbackHandler>, handler: Arc<dyn CallbackHandler>,
revoked: bool, revoked: bool,
transmitted: bool, transmitted: bool,
cancellation: Option<RpcError>, cancellation: Option<PendingCancellation>,
context: CallContext, context: CallContext,
result: Option<oneshot::Sender<Result<RpcReply, RpcError>>>, result: Option<oneshot::Sender<Result<RpcReply, RpcError>>>,
stream: Option<StreamIngress>, stream: Option<StreamIngress>,
@@ -54,6 +55,12 @@ struct PendingCall {
callbacks: BTreeMap<u64, CallbackTask>, callbacks: BTreeMap<u64, CallbackTask>,
} }
struct PendingCancellation {
error: RpcError,
deadline: tokio::time::Instant,
transmitted: bool,
}
// 调度状态只属于父任务;回调完成与恢复授权分别推进 // 调度状态只属于父任务;回调完成与恢复授权分别推进
enum Scheduling { enum Scheduling {
Running { Running {
@@ -154,6 +161,7 @@ impl Shared {
limits.maximum_queue_timeout, limits.maximum_queue_timeout,
), ),
cancellations_changed: Notify::new(), cancellations_changed: Notify::new(),
maximum_queue_timeout: limits.maximum_queue_timeout,
} }
} }
@@ -252,9 +260,12 @@ impl Shared {
} }
pub fn fail(&self, error: RpcError) { pub fn fail(&self, error: RpcError) {
self.fail_with_state(error, self.state());
}
fn fail_with_state(&self, error: RpcError, mut state: MutexGuard<'_, State>) {
let uptime = self.started_at.elapsed(); let uptime = self.started_at.elapsed();
let (calls, failure_observer) = { let (calls, failure_observer) = {
let mut state = self.state();
if state.failure.is_some() { if state.failure.is_some() {
return; return;
} }
@@ -268,6 +279,7 @@ impl Shared {
} }
(std::mem::take(&mut state.calls), observer) (std::mem::take(&mut state.calls), observer)
}; };
drop(state);
self.execution.close(); self.execution.close();
for call in calls.into_values() { for call in calls.into_values() {
call.finish(Err(error.clone())); call.finish(Err(error.clone()));
@@ -406,8 +418,8 @@ impl Shared {
true true
} }
/// 先撤销调用权限,再等待对端确认;只有无响应对端才终止整个 incarnation /// 先撤销调用权限,再有界等待取消帧发送与对端确认
pub fn cancel(self: &Arc<Self>, id: u64, error: RpcError) { pub fn cancel(&self, id: u64, error: RpcError) {
let mut state = self.state(); let mut state = self.state();
let Some(call) = state.calls.get_mut(&id) else { let Some(call) = state.calls.get_mut(&id) else {
return; return;
@@ -436,7 +448,11 @@ impl Shared {
} }
return; return;
} }
call.cancellation = Some(error.clone()); call.cancellation = Some(PendingCancellation {
error: error.clone(),
deadline: tokio::time::Instant::now() + self.maximum_queue_timeout,
transmitted: false,
});
// 同步撤销不能跨越取消确认:收到确认的并发任务可能立即复用实例 // 同步撤销不能跨越取消确认:收到确认的并发任务可能立即复用实例
// CallbackHandler::finish 合同要求非阻塞;真正的等待与结果交付放在锁外 // CallbackHandler::finish 合同要求非阻塞;真正的等待与结果交付放在锁外
call.revoke(); call.revoke();
@@ -455,16 +471,63 @@ impl Shared {
stream.finish(Err(error.clone())); stream.finish(Err(error.clone()));
} }
if let Some(result) = result { if let Some(result) = result {
let _ = result.send(Err(error.clone())); let _ = result.send(Err(error));
} }
self.send_control(Frame::control(Message::Cancel { id })); self.send_control(Frame::control(Message::Cancel { id }));
let shared = Arc::clone(self); self.cancellations_changed.notify_waiters();
tokio::spawn(async move { }
tokio::time::sleep(Duration::from_millis(250)).await;
if shared.is_cancelling(id) { pub(super) fn cancellation_transmitted(&self, id: u64) {
shared.fail(error); let mut state = self.state();
} let Some(cancellation) = state
}); .calls
.get_mut(&id)
.and_then(|call| call.cancellation.as_mut())
else {
// 对端确认可能先于写泵恢复执行,已退休调用不再建立期限
return;
};
cancellation.transmitted = true;
// 写入管道不代表对端已处理,确认还需经过插件输入与输出队列
cancellation.deadline = tokio::time::Instant::now() + self.maximum_queue_timeout;
drop(state);
self.cancellations_changed.notify_waiters();
}
pub(super) fn cancellation_deadline(&self) -> Option<tokio::time::Instant> {
self.state()
.calls
.values()
.filter_map(|call| call.cancellation.as_ref().map(|pending| pending.deadline))
.min()
}
pub(super) fn expire_cancellation(&self) -> bool {
let state = self.state();
let now = tokio::time::Instant::now();
let Some((call, cancellation)) = state.calls.values().find_map(|call| {
call.cancellation
.as_ref()
.filter(|pending| pending.deadline <= now)
.map(|pending| (call, pending))
}) else {
return false;
};
tracing::warn!(
event = "plugin.rpc.cancellation_timeout",
instance_id = call.context.instance_id,
call_id = call.context.call_id,
phase = if cancellation.transmitted {
"confirmation"
} else {
"send_queue"
},
"插件取消未在期限内完成,终止会话"
);
let error = cancellation.error.clone();
// 期限复核与失败提交共用调用表锁,确认到达后不能被旧检查结果关闭
self.fail_with_state(error, state);
true
} }
pub fn acknowledge_cancellation(&self, id: u64) -> Result<(), RpcError> { pub fn acknowledge_cancellation(&self, id: u64) -> Result<(), RpcError> {
@@ -14,6 +14,7 @@ pub struct RpcLimits {
pub maximum_calls: usize, pub maximum_calls: usize,
pub maximum_executing_calls: usize, pub maximum_executing_calls: usize,
pub maximum_queued_calls: usize, pub maximum_queued_calls: usize,
/// 初次准入、恢复、取消发送排队及确认等待各自使用此期限
pub maximum_queue_timeout: Duration, pub maximum_queue_timeout: Duration,
pub maximum_callbacks: usize, pub maximum_callbacks: usize,
pub handshake_timeout: Duration, pub handshake_timeout: Duration,
@@ -70,6 +70,10 @@ async fn write_loop<W: AsyncWrite + Unpin>(
))); )));
return; return;
} }
if let Message::Cancel { id } = frame.message() {
// 确认预算从控制帧完整写出后开始,不包含其他帧造成的发送排队
shared.cancellation_transmitted(*id);
}
} }
} }
@@ -84,10 +88,32 @@ async fn read_loop<R: AsyncRead + Unpin>(
if *stopped.borrow() { if *stopped.borrow() {
return; return;
} }
let frame = tokio::select! { let frame = read_frame(&mut reader);
biased; tokio::pin!(frame);
_ = stopped.changed() => return, let frame = loop {
frame = read_frame(&mut reader) => frame, let changed = shared.cancellations_changed.notified();
tokio::pin!(changed);
changed.as_mut().enable();
let deadline = shared.cancellation_deadline();
let expired = async {
match deadline {
Some(deadline) => tokio::time::sleep_until(deadline).await,
None => std::future::pending().await,
}
};
tokio::select! {
biased;
_ = stopped.changed() => return,
// 读取与取消超时只有一个裁决者,已就绪的确认优先于超时
frame = &mut frame => break frame,
// 保留同一个读帧 future,期限变更不能丢弃已读取的半帧
_ = &mut changed => {},
() = expired => {
if shared.expire_cancellation() {
return;
}
}
}
}; };
let frame = match frame { let frame = match frame {
Ok(frame) => frame, Ok(frame) => frame,
@@ -36,26 +36,22 @@ async fn http_waiting_next_releases_execution_for_reject_plugin() {
#[tokio::test] #[tokio::test]
async fn http_in_flight_limit_never_delegates_and_recovers_after_cancellation() { async fn http_in_flight_limit_never_delegates_and_recovers_after_cancellation() {
for policy in [PluginFailurePolicy::Delegate, PluginFailurePolicy::Reject] { for policy in [PluginFailurePolicy::Delegate, PluginFailurePolicy::Reject] {
assert_capacity( assert_capacity(policy, RpcLimits::default(), true).await;
policy,
RpcLimits {
maximum_calls: 64,
..Default::default()
},
true,
)
.await;
} }
} }
async fn assert_capacity(policy: PluginFailurePolicy, limits: RpcLimits, saturated: bool) { async fn assert_capacity(policy: PluginFailurePolicy, limits: RpcLimits, saturated: bool) {
const CONCURRENT_CALLS: usize = 64; let concurrent_calls = if saturated {
limits.maximum_calls
} else {
limits.maximum_executing_calls
};
let (cache, runtime, generation, plan) = let (cache, runtime, generation, plan) =
http_plugin_with_policy("passthrough", limits, policy).await; http_plugin_with_policy("passthrough", limits, policy).await;
let release = Arc::new(tokio::sync::Semaphore::new(0)); let release = Arc::new(tokio::sync::Semaphore::new(0));
let (started, mut entered) = tokio::sync::mpsc::unbounded_channel(); let (started, mut entered) = tokio::sync::mpsc::unbounded_channel();
let mut slow_calls = tokio::task::JoinSet::new(); let mut slow_calls = tokio::task::JoinSet::new();
for index in 0..CONCURRENT_CALLS { for index in 0..concurrent_calls {
let plan = plan.clone(); let plan = plan.clone();
let release = release.clone(); let release = release.clone();
let started = started.clone(); let started = started.clone();
@@ -120,7 +116,7 @@ async fn assert_capacity(policy: PluginFailurePolicy, limits: RpcLimits, saturat
assert!(matches!(result, Err(error) if error.is_cancelled())); assert!(matches!(result, Err(error) if error.is_cancelled()));
} }
} }
release.add_permits(CONCURRENT_CALLS); release.add_permits(concurrent_calls);
while let Some(result) = slow_calls.join_next().await { while let Some(result) = slow_calls.join_next().await {
let response = result.unwrap().unwrap(); let response = result.unwrap().unwrap();
assert_eq!(response.headers()["x-http-plugin"], "active"); assert_eq!(response.headers()["x-http-plugin"], "active");
@@ -812,9 +812,153 @@ async fn explicit_policy_denial_keeps_its_error_kind_and_status() {
session.shutdown(Duration::from_secs(1)).await; session.shutdown(Duration::from_secs(1)).await;
} }
#[tokio::test]
async fn queued_cancellation_survives_backpressure_but_a_stalled_writer_is_bounded() {
for recover in [true, false] {
let (cache, prepared, handshake, processes) = prepared_session();
let session = RpcSession::start(
prepared,
handshake,
RpcLimits {
maximum_queue_timeout: Duration::from_secs(2),
..Default::default()
},
&processes,
Arc::new(Callbacks::default()),
)
.await
.unwrap();
let entered = cache.path().join("frame-entered");
let release = cache.path().join("frame-release");
let mut hanging = Box::pin(session.call(
"hang",
session.context(Stage::Request, Duration::from_secs(10)),
json!({}),
vec![],
));
assert!(futures::poll!(&mut hanging).is_pending());
session
.call(
"pause_next_frame",
session.context(Stage::Request, Duration::from_secs(10)),
json!({"entered": entered, "release": release}),
vec![],
)
.await
.unwrap();
let mut blocked = Box::pin(session.call(
"echo",
session.context(Stage::Request, Duration::from_secs(10)),
json!({}),
vec![42; 4 * 1024 * 1024],
));
assert!(futures::poll!(&mut blocked).is_pending());
tokio::time::timeout(Duration::from_secs(5), async {
while !entered.exists() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.unwrap();
drop(hanging);
// Cancel 尚未写出,不能将共享写泵的排队时间视为对端拒绝确认
tokio::time::sleep(Duration::from_millis(350)).await;
assert!(session.is_ready(), "queued cancellation closed the session");
if recover {
std::fs::write(release, b"ready").unwrap();
let reply = tokio::time::timeout(Duration::from_secs(5), blocked)
.await
.unwrap()
.unwrap();
assert_eq!(reply.payload, vec![42; 4 * 1024 * 1024]);
assert!(
session
.call(
"echo",
session.context(Stage::Request, Duration::from_secs(2)),
json!("after-cancel"),
vec![],
)
.await
.is_ok()
);
} else {
assert!(matches!(
tokio::time::timeout(Duration::from_secs(3), blocked)
.await
.unwrap(),
Err(RpcError::Cancelled)
));
assert!(!session.is_ready());
}
session.shutdown(Duration::from_secs(1)).await;
}
}
#[tokio::test]
async fn cancellation_confirmation_survives_peer_backpressure() {
let (cache, session) = session(Arc::new(Callbacks::default())).await;
let entered = cache.path().join("cancel-entered");
let release = cache.path().join("cancel-release");
let mut hanging = Box::pin(session.call(
"hang",
session.context(Stage::Request, Duration::from_secs(10)),
json!({}),
vec![],
));
assert!(futures::poll!(&mut hanging).is_pending());
session
.call(
"pause_next_frame",
session.context(Stage::Request, Duration::from_secs(10)),
json!({"entered": entered, "release": release}),
vec![],
)
.await
.unwrap();
drop(hanging);
tokio::time::timeout(Duration::from_secs(5), async {
while !entered.exists() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.unwrap();
// 小控制帧已写入管道,但对端仍可能在处理此前排队的调用与确认
tokio::time::sleep(Duration::from_millis(350)).await;
assert!(
session.is_ready(),
"pending confirmation closed the session"
);
std::fs::write(release, b"ready").unwrap();
let reply = session
.call(
"echo",
session.context(Stage::Request, Duration::from_secs(2)),
json!("after-cancel"),
vec![],
)
.await
.unwrap();
assert_eq!(reply.result, json!("after-cancel"));
session.shutdown(Duration::from_secs(1)).await;
}
#[tokio::test] #[tokio::test]
async fn ignored_cancellation_closes_the_incarnation_and_settles_other_calls() { async fn ignored_cancellation_closes_the_incarnation_and_settles_other_calls() {
let (_cache, session) = session(Arc::new(Callbacks::default())).await; let (_cache, prepared, handshake, processes) = prepared_session();
let session = RpcSession::start(
prepared,
handshake,
RpcLimits {
maximum_queue_timeout: Duration::from_millis(350),
..Default::default()
},
&processes,
Arc::new(Callbacks::default()),
)
.await
.unwrap();
let first = session.call( let first = session.call(
"hang_uncancellable", "hang_uncancellable",
session.context(Stage::Request, Duration::from_millis(100)), session.context(Stage::Request, Duration::from_millis(100)),
@@ -823,13 +967,18 @@ async fn ignored_cancellation_closes_the_incarnation_and_settles_other_calls() {
); );
let second = session.call( let second = session.call(
"hang", "hang",
session.context(Stage::Request, Duration::from_secs(2)), session.context(Stage::Request, Duration::from_secs(10)),
json!({}), json!({}),
vec![], vec![],
); );
let (first, second) = tokio::join!(first, second); let (first, second) = tokio::time::timeout(Duration::from_secs(3), async {
tokio::join!(first, second)
})
.await
.expect("unacknowledged cancellation must close the session before other calls expire");
assert!(matches!(first, Err(RpcError::Timeout))); assert!(matches!(first, Err(RpcError::Timeout)));
assert!(matches!(second, Err(RpcError::Timeout))); assert!(matches!(second, Err(RpcError::Timeout)));
assert!(!session.is_ready());
session.shutdown(Duration::from_secs(1)).await; session.shutdown(Duration::from_secs(1)).await;
} }
@@ -15,7 +15,7 @@ use gateway_plugin_sdk::{
client::{read_frame, write_frame}, client::{read_frame, write_frame},
}; };
use serde_json::{Value, json}; use serde_json::{Value, json};
use tokio::io::AsyncWriteExt as _; use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
use tokio::sync::{Mutex, Notify, mpsc, oneshot}; use tokio::sync::{Mutex, Notify, mpsc, oneshot};
use gateway_plugin_sdk::call::{ use gateway_plugin_sdk::call::{
@@ -1577,7 +1577,20 @@ async fn main() {
let mut tasks = BTreeMap::new(); let mut tasks = BTreeMap::new();
let mut uncancellable = std::collections::BTreeSet::new(); let mut uncancellable = std::collections::BTreeSet::new();
let mut last_call = 0; let mut last_call = 0;
while let Ok(frame) = read_frame(&mut input).await { let mut paused_read: Option<(String, String)> = None;
loop {
let frame = if let Some((entered, release)) = paused_read.take() {
// 先确认下一帧已经开始写入,再暂停消费,稳定制造共享写泵的背压
let prefix = input.read_u32().await.unwrap().to_be_bytes();
std::fs::write(entered, b"reading").unwrap();
while !std::path::Path::new(&release).exists() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
read_frame(&mut prefix.as_slice().chain(&mut input)).await
} else {
read_frame(&mut input).await
};
let Ok(frame) = frame else { break };
match frame.message { match frame.message {
Message::Call { Message::Call {
id, id,
@@ -1587,6 +1600,21 @@ async fn main() {
} => { } => {
assert!(id > last_call && !id.is_multiple_of(2) && context.call_id == id); assert!(id > last_call && !id.is_multiple_of(2) && context.call_id == id);
last_call = id; last_call = id;
if method == "pause_next_frame" {
paused_read = Some((
params["entered"].as_str().unwrap().to_owned(),
params["release"].as_str().unwrap().to_owned(),
));
peer.send(
Message::Result {
id,
result: json!({}),
},
vec![],
)
.await;
continue;
}
peer.append_observation_marker( peer.append_observation_marker(
"call_context_marker", "call_context_marker",
&json!({"method":method, "context":context}), &json!({"method":method, "context":context}),
@@ -84,6 +84,9 @@ SDK 和宿主的 `maximum_callbacks` 默认 320、最大 512,统一限制全
取消或丢弃回调 future 会释放该回调;宿主不保证已发出的业务操作可以撤销,不自动重试或补偿。 取消或丢弃回调 future 会释放该回调;宿主不保证已发出的业务操作可以撤销,不自动重试或补偿。
已返回响应头的流继续占用总在途预算,不占首结果执行名额,由正文或连接的 owner 管理真实寿命 已返回响应头的流继续占用总在途预算,不占首结果执行名额,由正文或连接的 owner 管理真实寿命
取消控制帧的发送排队与确认等待分别使用宿主排队期限,默认各 30 秒;确认期限从控制帧完整写出后开始计算。
发送排队或确认超时会终止该插件会话并回收在途调用,运行日志区分这两个阶段
实际容量由宿主预算与 SDK 会话配置共同限制,较小的插件侧上限会提前拒绝新调用。 实际容量由宿主预算与 SDK 会话配置共同限制,较小的插件侧上限会提前拒绝新调用。
达到容量或等待上限时,中间件返回过载错误;HTTP 响应为 503(`middleware_capacity_unavailable`), 达到容量或等待上限时,中间件返回过载错误;HTTP 响应为 503(`middleware_capacity_unavailable`),
不跳过插件或重放请求。调整 SDK 会话配置需重新构建插件包,容量应结合插件耗时、正文和响应流的资源占用评估 不跳过插件或重放请求。调整 SDK 会话配置需重新构建插件包,容量应结合插件耗时、正文和响应流的资源占用评估
@@ -349,7 +349,7 @@ HTTP 总入口统一包裹原生路由,`dispatch_http` 复用同一路由与
`Load` 返回完整运行设置与 `config_revision`。`ReplaceRuntimeSettings::from(settings)` 保留该版本并构造更新命令; `Load` 返回完整运行设置与 `config_revision`。`ReplaceRuntimeSettings::from(settings)` 保留该版本并构造更新命令;
`Replace` 接收 `(MutationContext, ReplaceRuntimeSettings)`,通过已有校验、事务、审计和快照发布保存设置。 `Replace` 接收 `(MutationContext, ReplaceRuntimeSettings)`,通过已有校验、事务、审计和快照发布保存设置。
每次写入都必须提供 `openai_request_settings`、`openai_websocket_pool` 和 `reset_credit_on_low_weekly_quota`。 每次写入都必须提供 `openai_request_settings`、`openai_websocket_pool`、`reset_credit_on_low_weekly_quota` 和 `prompt_rewrite_rules`。清空提示词改写规则时提交空数组,范围与顺序见[提示词改写](../../../../../docs/api.md#提示词改写)。
版本过期返回 `ServiceError { kind: "conflict", message }`。读取结果的普通改写不会持久化,也不会回滚已经提交的事务 版本过期返回 `ServiceError { kind: "conflict", message }`。读取结果的普通改写不会持久化,也不会回滚已经提交的事务
`accounts::GetResetCreditAutomation` 接收账号 ID,返回 `ResetCreditAutomationStatus`:开关、全局提前分钟数、 `accounts::GetResetCreditAutomation` 接收账号 ID,返回 `ResetCreditAutomationStatus`:开关、全局提前分钟数、
@@ -493,6 +493,7 @@ let plugin = PluginBuilder::from_json(manifest_json)?
attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。 attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。
request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。 request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。
OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。 OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。
xAI 明确换号时会在合并后清理 `traceparent`、`tracestate`、`sentry-trace`、`baggage`,避免将上一账号的追踪上下文带入新账号。
CPR 中间件添加的 HTTP 扩展头在发往 Antigravity 时经过该 Provider 的过滤:账号身份、客户端画像和 HTTP 传输字段由网关生成,明确换号时清理已识别的追踪头,其余头保留多值字节,具体范围见 [AGY 请求合同](../../../../../docs/api.md#antigravity-客户端原生生成)。 CPR 中间件添加的 HTTP 扩展头在发往 Antigravity 时经过该 Provider 的过滤:账号身份、客户端画像和 HTTP 传输字段由网关生成,明确换号时清理已识别的追踪头,其余头保留多值字节,具体范围见 [AGY 请求合同](../../../../../docs/api.md#antigravity-客户端原生生成)。
实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造 实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造
@@ -57,6 +57,33 @@ pub enum AccountErrorOperator {
Equals, Equals,
Contains, Contains,
} }
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PromptRewriteRule {
pub name: String,
#[serde(default)]
pub providers: BTreeSet<String>,
pub match_mode: PromptMatchMode,
pub pattern: String,
pub replacement: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PromptMatchMode {
Prefix,
Regex,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PromptRewritePreviewRequest {
pub rule: PromptRewriteRule,
pub text: String,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct PromptRewritePreviewResult {
pub matched: bool,
pub output: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)] #[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct OpenAiWebSocketPoolSettings { pub struct OpenAiWebSocketPoolSettings {
@@ -188,6 +215,7 @@ pub struct RuntimeSettings {
pub usage_retention_days: u32, pub usage_retention_days: u32,
pub ops_event_retention_days: u32, pub ops_event_retention_days: u32,
pub audit_retention_days: u32, pub audit_retention_days: u32,
pub prompt_rewrite_rules: Vec<PromptRewriteRule>,
pub account_error_protection: AccountErrorProtection, pub account_error_protection: AccountErrorProtection,
pub account_warmup_enabled: bool, pub account_warmup_enabled: bool,
pub account_warmup_cron: String, pub account_warmup_cron: String,
@@ -230,6 +258,7 @@ pub struct ReplaceRuntimeSettings {
pub usage_retention_days: u32, pub usage_retention_days: u32,
pub ops_event_retention_days: u32, pub ops_event_retention_days: u32,
pub audit_retention_days: u32, pub audit_retention_days: u32,
pub prompt_rewrite_rules: Vec<PromptRewriteRule>,
pub account_error_protection: AccountErrorProtection, pub account_error_protection: AccountErrorProtection,
pub account_warmup_enabled: bool, pub account_warmup_enabled: bool,
pub account_warmup_cron: String, pub account_warmup_cron: String,
@@ -349,6 +378,12 @@ impl Operation for Load {
type Input = (); type Input = ();
type Output = RuntimeSettings; type Output = RuntimeSettings;
} }
pub struct PreviewPromptRewrite;
impl Operation for PreviewPromptRewrite {
const NAME: &'static str = "settings.preview_prompt_rewrite";
type Input = PromptRewritePreviewRequest;
type Output = PromptRewritePreviewResult;
}
pub struct PreviewPrivacyPolicy; pub struct PreviewPrivacyPolicy;
impl Operation for PreviewPrivacyPolicy { impl Operation for PreviewPrivacyPolicy {
const NAME: &'static str = "settings.preview_privacy_policy"; const NAME: &'static str = "settings.preview_privacy_policy";
@@ -444,6 +479,7 @@ impl From<RuntimeSettings> for ReplaceRuntimeSettings {
usage_retention_days: settings.usage_retention_days, usage_retention_days: settings.usage_retention_days,
ops_event_retention_days: settings.ops_event_retention_days, ops_event_retention_days: settings.ops_event_retention_days,
audit_retention_days: settings.audit_retention_days, audit_retention_days: settings.audit_retention_days,
prompt_rewrite_rules: settings.prompt_rewrite_rules,
account_error_protection: settings.account_error_protection, account_error_protection: settings.account_error_protection,
account_warmup_enabled: settings.account_warmup_enabled, account_warmup_enabled: settings.account_warmup_enabled,
account_warmup_cron: settings.account_warmup_cron, account_warmup_cron: settings.account_warmup_cron,
+1 -1
View File
@@ -18,7 +18,7 @@ http = "1.5.0"
httpdate = "1.0.3" httpdate = "1.0.3"
memchr = "2.8.3" memchr = "2.8.3"
serde = { version = "1.0.228", features = ["derive"] } serde = { version = "1.0.228", features = ["derive"] }
serde_json = { version = "1.0.150", features = ["arbitrary_precision", "preserve_order"] } serde_json = { version = "1.0.150", features = ["arbitrary_precision", "preserve_order", "raw_value"] }
thiserror = "2.0.18" thiserror = "2.0.18"
uuid = { version = "1.23.3", features = ["v4"] } uuid = { version = "1.23.3", features = ["v4"] }
@@ -14,4 +14,4 @@ pub use response::{
pub const GENAI_PROTOCOL: &str = "genai"; pub const GENAI_PROTOCOL: &str = "genai";
mod tokens; mod tokens;
pub use tokens::{CountTokensError, count_tokens_request}; pub use tokens::{CountTokensError, count_tokens_request, into_count_tokens_request};
@@ -8,15 +8,31 @@ use thiserror::Error;
#[error("generateContentRequest must be a JSON object.")] #[error("generateContentRequest must be a JSON object.")]
pub struct CountTokensError; pub struct CountTokensError;
fn wrapped_field(request: &Map<String, Value>) -> Option<&'static str> {
["generateContentRequest", "generate_content_request"]
.into_iter()
.find(|key| request.contains_key(*key))
}
/// 完整生成请求存在时,以它作为计数输入,外层 contents 不参与计数 /// 完整生成请求存在时,以它作为计数输入,外层 contents 不参与计数
pub fn count_tokens_request( pub fn count_tokens_request(
request: &Map<String, Value>, request: &Map<String, Value>,
) -> Result<&Map<String, Value>, CountTokensError> { ) -> Result<&Map<String, Value>, CountTokensError> {
match request match wrapped_field(request) {
.get("generateContentRequest") Some(key) => request[key].as_object().ok_or(CountTokensError),
.or_else(|| request.get("generate_content_request")) None => Ok(request),
{ }
Some(value) => value.as_object().ok_or(CountTokensError), }
/// 取出计数正文供上游适配,无需复制历史和工具
pub fn into_count_tokens_request(
mut request: Map<String, Value>,
) -> Result<Map<String, Value>, CountTokensError> {
match wrapped_field(&request) {
Some(key) => match request.remove(key) {
Some(Value::Object(body)) => Ok(body),
_ => Err(CountTokensError),
},
None => Ok(request), None => Ok(request),
} }
} }
+24 -1
View File
@@ -1,4 +1,7 @@
//! 跨协议 HTTP 头部传输边界与重试时间解析 //! 跨协议 HTTP 传输、下游环境头分类与重试时间解析
/// 上游可交给客户端的秒级与毫秒级重试等待头
pub const RETRY_AFTER_HEADERS: [&str; 2] = ["retry-after", "retry-after-ms"];
/// 解析 HTTP 和流内错误共用的 Retry-After,保留零延迟并向上取整剩余秒数 /// 解析 HTTP 和流内错误共用的 Retry-After,保留零延迟并向上取整剩余秒数
pub fn parse_retry_after_seconds(value: &str) -> Option<u64> { pub fn parse_retry_after_seconds(value: &str) -> Option<u64> {
@@ -46,6 +49,26 @@ pub fn is_transport_managed_request_header(name: &str) -> bool {
) )
} }
/// 判断小写请求头是否描述下游反代、浏览器或 SDK 环境
///
/// 仅提供分类,由 Provider 决定是否过滤,不加入 API 的通用传输头过滤
/// 不包含厂商身份、会话别名或业务字段,也不检查请求正文
#[must_use]
pub fn is_downstream_environment_request_header(name: &str) -> bool {
// 反代来源信息只描述客户端到网关这一段,cf-* 还可能携带 Access 认证
name.starts_with("cf-")
|| name.starts_with("x-forwarded-")
|| matches!(
name,
"forwarded" | "via" | "cdn-loop" | "x-real-ip" | "true-client-ip"
)
// SDK、浏览器与页面来源不代表网关连接上游时的环境
|| name.starts_with("x-stainless-")
|| name.starts_with("sec-ch-ua")
|| name.starts_with("sec-fetch-")
|| matches!(name, "origin" | "referer")
}
/// 判断响应头是否满足 HTTP 传输和通用鉴权材料的转发边界 /// 判断响应头是否满足 HTTP 传输和通用鉴权材料的转发边界
/// ///
/// `connection_options` 来自同一响应的 `Connection` 字段,调用方应先按逗号拆分并 /// `connection_options` 来自同一响应的 `Connection` 字段,调用方应先按逗号拆分并
@@ -24,3 +24,6 @@ pub mod peer;
/// Chat Completions 直接转换 /// Chat Completions 直接转换
pub mod chat_completions; pub mod chat_completions;
/// 原生协议与 Chat 的系统指令定位及局部替换
pub mod prompt_rewrite;

Some files were not shown because too many files have changed in this diff Show More