fix(proxy): 将 messages 中的 role:"system" 消息合并到顶层 system 字段,修复严格上游 400
背景
Fixes #1265
Claude Code 2.1.172+(2.1.153 之后引入的行为变化)配合自定义模型名(ANTHROPIC_DEFAULT_OPUS_MODEL 等指向 cchub 渠道模型)使用时,会在 messages 数组中注入独立的 {"role": "system", "content": "..."} 消息(skills 列表)。Anthropic 官方 API 接受该写法,但 Vertex/Bedrock 类严格校验 messages 角色的兼容上游会以 400 拒绝,cchub 原样透传导致重试耗尽全部供应商后熔断,客户端收到 503「所有供应商暂时不可用」。
修复方案
参照现有 billing-header-rectifier.ts 的 proactive rectifier 模式:
核心模块 src/app/v1/_lib/proxy/system-message-rectifier.ts
- 转发前扫描
messages,取出role: "system"条目 - string content 转为
{type: "text", text}block;数组 content 保留 text block(含cache_control等附加字段),丢弃非 text block - 追加到顶层
system字段末尾(顶层为 string 时先转为首个 text block) - 原地变异,语义与 Anthropic 官方 API 对该写法的处理一致:宽容上游无行为变化,严格上游消除 400
forwarder 集成
- 仅对
claude/claude-auth供应商生效 - 置于 billing header rectifier 之前,确保 system 消息内若携带
x-anthropic-billing-header文本块,搬移后仍会被后续剥离 - 命中时记录
system_message_rectifierspecialSetting 审计并写日志
系统设置开关 enableSystemMessageRectifier(默认开启)
- 全链路:schema 新列 + 迁移(
drizzle/0105_easy_cyclops.sql)、settings cache、types、zod 校验、Server Action、admin REST、v1 OpenAPI schema、repository、transformers - 按既有模式接入
system_settings缺列降级链(读取与更新路径均在链头新增一层剔除该列的降级),迁移前部署的实例读取/更新设置不受影响 - 设置页新增开关项,补全 zh-CN / zh-TW / en / ja / ru 五语言文案
测试
新增 tests/unit/proxy/system-message-rectifier.test.ts,16 个用例:
- string / array content、空 content、非法 content
- 顶层 system 为 undefined / string / array / 空串 / 未知类型
- 多条 system 消息保序、messages 含 null / 非对象条目
- 原地变异引用不变
- 与 billing rectifier 按 forwarder 实际顺序的组合场景(system 消息内携带 billing header 块最终被剥离)
验证
bun run build通过bun run lint/lint:fix通过bun run typecheck通过bun run test全量 6370 个测试通过bun run openapi:check通过
Greptile Summary
This PR adds a proactive rectifier that lifts role:"system" messages out of the messages array and merges them into the top-level system field before forwarding, matching the lenient interpretation the official Anthropic API already applies and removing the source of 400 errors on strict upstreams like Vertex/Bedrock.
- Core rectifier (
system-message-rectifier.ts): synchronous, in-place mutation; correctly handles all content shapes (string → single block, array → filter to text blocks, empty string → no block, unknown type → discard), and all top-levelsystemshapes (undefined, null, string, array, unknown). - Forwarder integration: runs before the billing-header rectifier (so billing blocks moved via this pass are still stripped), guarded by
enableSystemMessageRectifiersetting; both rectifiers share the singlegetCachedSystemSettings()result fetched once perdoForwardcall. - Settings plumbing: full migration, cache, schema, zod, admin API, and admin UI coverage; column-missing fallback chain prepends the new column to the existing degradation ladder.
Confidence Score: 5/5
Safe to merge. The rectifier is synchronous, idempotent, and only mutates messages when role:"system" entries are present — requests without them pass through unchanged.
The change is a well-bounded proactive transformation applied only to claude/claude-auth providers, guarded by a feature flag that defaults to the safe/on state. The core function handles all edge cases and is tested with 16 targeted unit tests. Settings plumbing follows the established pattern with the new column correctly positioned as the outermost entry in the degradation ladder.
No files require special attention.
Important Files Changed
| Filename | Overview |
|---|---|
| src/app/v1/_lib/proxy/system-message-rectifier.ts | New core rectifier module — well-typed, mutates in place, handles all content/system field shapes correctly; comprehensive unit tests. |
| src/app/v1/_lib/proxy/forwarder.ts | Integrates the new rectifier before the billing-header rectifier, both sharing a single getCachedSystemSettings() result. Logic and ordering are correct. |
| src/repository/system-config.ts | Adds enableSystemMessageRectifier to both full-select and fallback ladder (as the outermost/newest fallback step), and to the update path fallback; consistent with prior pattern. |
| drizzle/0106_stiff_dormammu.sql | Single-column migration adding enable_system_message_rectifier boolean NOT NULL DEFAULT true — safe, additive, non-blocking. |
| tests/unit/proxy/system-message-rectifier.test.ts | 16 well-chosen unit tests covering all content shapes, system field shapes, ordering, in-place mutation, and the combined billing-header interaction. |
| src/types/special-settings.ts | Adds SystemMessageRectifierSpecialSetting type; consistent shape with BillingHeaderRectifierSpecialSetting. |
| src/lib/config/system-settings-cache.ts | Adds enableSystemMessageRectifier: true to the DEFAULT_SETTINGS fallback and to the cold-cache fallback object; consistent with other rectifier defaults. |
| tests/unit/repository/system-config-update-missing-columns.test.ts | Existing test updated with the new fallback path; the test mock for the full-column set does not include the new enableSystemMessageRectifier field (minor gap, but not blocking). |
Sequence Diagram
sequenceDiagram
participant CC as Claude Code Client
participant FW as ProxyForwarder.doForward
participant SMR as SystemMessageRectifier
participant BHR as BillingHeaderRectifier
participant UP as Upstream (Vertex/Bedrock)
CC->>FW: POST /v1/messages
FW->>FW: getCachedSystemSettings()
alt "enableSystemMessageRectifier = true"
FW->>SMR: rectifySystemMessages(message)
SMR-->>FW: "applied=true, messages cleaned, system merged"
end
alt "enableBillingHeaderRectifier = true"
FW->>BHR: rectifyBillingHeader(message)
BHR-->>FW: billing header blocks stripped
end
FW->>UP: POST with clean messages array
UP-->>FW: 200 OK
FW-->>CC: 200 OK
Comments Outside Diff (1)
-
src/app/v1/_lib/proxy/forwarder.ts, line 2480-2483 (link)Two consecutive
getCachedSystemSettings()calls are made in the same code path — one for the system message rectifier and one for the billing header rectifier. Since the cache returns the same in-memory object within the 1-minute TTL, the second call is a no-op but still adds an unnecessaryawait. Both rectifiers could share the singlesettingsobject that was already fetched.Prompt To Fix With AI
This is a comment left during a code review. Path: src/app/v1/_lib/proxy/forwarder.ts Line: 2480-2483 Comment: Two consecutive `getCachedSystemSettings()` calls are made in the same code path — one for the system message rectifier and one for the billing header rectifier. Since the cache returns the same in-memory object within the 1-minute TTL, the second call is a no-op but still adds an unnecessary `await`. Both rectifiers could share the single `settings` object that was already fetched. How can I resolve this? If you propose a fix, please make it concise.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Reviews (3): Last reviewed commit: "merge: resolve conflicts with dev (PR #1..." | Re-trigger Greptile
📝 Walkthrough
Walkthrough
本 PR 实现系统消息整流器功能。当 Claude Code 2.1.172+ 使用自定义模型名时,会在 messages 数组中注入 role: "system" 的消息,导致严格校验的 Anthropic 兼容上游(Vertex/Bedrock 等)拒绝。整流器在转发前自动抽取这些消息并合并到顶层 system 字段,消除 400 错误。
变更说明
System Message Rectifier 整体实现
| Layer / File(s) | Summary |
|---|---|
数据库迁移与类型契约 drizzle/0106_stiff_dormammu.sql, drizzle/meta/_journal.json, src/drizzle/schema.ts, src/types/system-config.ts, src/lib/api/v1/schemas/system-config.ts, src/lib/api-client/v1/openapi-types.gen.ts, src/lib/validation/schemas.ts |
新增数据库迁移添加 enable_system_message_rectifier 列(默认 true),日志记录迁移版本;在 schema、类型、生成 API 类型、validation schema 中声明布尔字段 enableSystemMessageRectifier。 |
默认值、缓存与数据转换 src/lib/config/system-settings-cache.ts, src/repository/_shared/transformers.ts |
系统设置缓存默认值补充 enableSystemMessageRectifier: true;toSystemSettings transformer 在返回对象中合并该字段,缺失时默认为 true。 |
Repository 读取更新与缺列降级兼容 src/repository/system-config.ts |
getSystemSettings() 和 updateSystemSettings() 的读取更新路径中包含新字段;数据库缺列时分层降级,最先移除该字段后重试,然后依次降级到已有字段集。 |
国际化文案与管理端 API messages/{en,ja,ru,zh-CN,zh-TW}/settings/config.json, src/app/api/admin/system-config/route.ts |
5 种语言配置文件新增 enableSystemMessageRectifier 与 enableSystemMessageRectifierDesc 文案;POST 路由从校验结果映射该字段到 updateSystemSettings 入参。 |
设置表单、页面与服务端操作 src/actions/system-config.ts, src/app/[locale]/settings/config/page.tsx, src/app/[locale]/settings/config/_components/system-settings-form.tsx |
客户端操作函数入参、设置页面初始化、表单组件新增该字段的状态管理、表单提交与保存成功后的回填逻辑;UI 新增 Switch 控件用于用户启用/禁用整流器。 |
整流器核心实现与审计类型 src/app/v1/_lib/proxy/system-message-rectifier.ts, src/types/special-settings.ts |
新增 rectifySystemMessages() 函数从 messages 中抽取 system 条目、规范化其内容为文本块、合并到顶层 system;定义 SystemMessageRectifierSpecialSetting 类型用于审计 applied/movedCount/extractedValues。 |
Forwarder 转发链路集成与审计键 src/app/v1/_lib/proxy/forwarder.ts, src/lib/utils/special-settings.ts |
Claude/Claude-auth provider 的覆写逻辑中条件执行整流器(在 billing header rectifier 之前),命中后构建并持久化 special setting;buildSettingKey() 新增 system_message_rectifier 分支用于去重。 |
整流器与缺列降级测试覆盖 tests/unit/proxy/system-message-rectifier.test.ts, tests/unit/repository/system-config-update-missing-columns.test.ts |
新增 13 个单元测试覆盖整流器的常规迁移、边界情况、原地引用语义与 billing header 联动;新增 3 个 repository 缺列降级测试验证分层移除字段的逻辑。 |
预估代码审查工作量
🎯 3 (Moderate) | ⏱️ ~25 minutes
可能相关的 PR
- ding113/claude-code-hub#576: 同样在
ProxyForwarder.doForward中为不同的 rectifier(thinking_signature_rectifiervssystem_message_rectifier)添加请求改写与特殊设置持久化逻辑。 - ding113/claude-code-hub#784: System message rectifier 作为额外的转发前处理步骤集成在 forwarder.ts 中,直接扩展现有的 billing header rectifier 工作。
- ding113/claude-code-hub#979: 新增
system_message_rectifier特殊设置并通过persistSpecialSettings(session)持久化,与该 PR 在相同的特殊设置持久化路径上重叠。
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 46.67% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | PR 标题清晰准确地概括了主要变更:将 messages 中的 role:"system" 消息合并到顶层 system 字段以修复严格上游 400 错误。 |
| Linked Issues check | ✅ Passed | PR 完整实现了 Issue #1265 的所有编码需求:系统消息整流器核心逻辑、forwarder 集成、系统设置开关全链路、16 个单元测试、向后兼容的缺列降级链。 |
| Out of Scope Changes check | ✅ Passed | 所有变更都在 Issue #1265 指定的修复范围内,包括核心整流器、forwarder 集成、系统设置、数据库迁移、UI 文案和测试,无超出范围的改动。 |
| Description check | ✅ Passed | PR 描述与变更集高度相关,详细说明了背景问题(Claude Code 2.1.172+ 注入 system 消息导致严格上游 400)、修复方案(system-message-rectifier 核心模块)、系统设置开关、测试覆盖与验证。 |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
✨ Finishing Touches
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
已根据审查意见更新(1d2bd1a8):
- CodeRabbit – NOOP_RESULT 共享数组引用:已修复,改为
createNoopResult()工厂函数,每次返回独立的extractedValues数组。 - Greptile – 重复的
getCachedSystemSettings()调用:已修复,两个 rectifier 块现共用同一次 settings 读取。 - CodeRabbit –
@/别名导入:不采纳,本文件对同目录模块统一使用相对导入(与./billing-header-rectifier等保持一致),详见行内回复。
验证:bun run build / typecheck / 改动文件 lint 干净 / 全量 6370 测试通过。
hi,对于涉及请求体变更的整流器,建议按照思考签名整流器的思路,在检测到特定报错模式之后被动整流。 主动对请求体进行修改可能引发意料外后果。
放弃此方向,关闭 PR。