gateway_claude_oauth_body.go 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277
  1. package service
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha256"
  6. "encoding/json"
  7. "fmt"
  8. "strconv"
  9. "strings"
  10. "github.com/Wei-Shaw/sub2api/internal/pkg/anthropicfp"
  11. "github.com/Wei-Shaw/sub2api/internal/pkg/claude"
  12. infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
  13. "github.com/Wei-Shaw/sub2api/internal/pkg/logger"
  14. "github.com/google/uuid"
  15. "github.com/tidwall/gjson"
  16. "github.com/tidwall/sjson"
  17. "github.com/gin-gonic/gin"
  18. )
  19. type anthropicCacheControlPayload struct {
  20. Type string `json:"type"`
  21. TTL string `json:"ttl,omitempty"`
  22. }
  23. type anthropicSystemTextBlockPayload struct {
  24. Type string `json:"type"`
  25. Text string `json:"text"`
  26. CacheControl *anthropicCacheControlPayload `json:"cache_control,omitempty"`
  27. }
  28. type anthropicMetadataPayload struct {
  29. UserID string `json:"user_id"`
  30. }
  31. // replaceModelInBody 替换请求体中的model字段
  32. // 优先使用定点修改,尽量保持客户端原始字段顺序。
  33. func (s *GatewayService) replaceModelInBody(body []byte, newModel string) []byte {
  34. return ReplaceModelInBody(body, newModel)
  35. }
  36. type claudeOAuthNormalizeOptions struct {
  37. injectMetadata bool
  38. metadataUserID string
  39. stripSystemCacheControl bool
  40. }
  41. // sanitizeSystemText rewrites only the fixed OpenCode identity sentence (if present).
  42. // We intentionally avoid broad keyword replacement in system prompts to prevent
  43. // accidentally changing user-provided instructions.
  44. func sanitizeSystemText(text string) string {
  45. if text == "" {
  46. return text
  47. }
  48. // Some clients include a fixed OpenCode identity sentence. Anthropic may treat
  49. // this as a non-Claude-Code fingerprint, so rewrite it to the canonical
  50. // Claude Code banner before generic "OpenCode"/"opencode" replacements.
  51. text = strings.ReplaceAll(
  52. text,
  53. "You are OpenCode, the best coding agent on the planet.",
  54. strings.TrimSpace(claudeCodeSystemPrompt),
  55. )
  56. return text
  57. }
  58. func marshalAnthropicSystemTextBlock(text string, includeCacheControl bool) ([]byte, error) {
  59. block := anthropicSystemTextBlockPayload{
  60. Type: "text",
  61. Text: text,
  62. }
  63. if includeCacheControl {
  64. block.CacheControl = &anthropicCacheControlPayload{
  65. Type: "ephemeral",
  66. TTL: claude.DefaultCacheControlTTL,
  67. }
  68. }
  69. return json.Marshal(block)
  70. }
  71. func marshalAnthropicSystemTextBlockWithCacheControl(text string, cacheControl any) ([]byte, error) {
  72. block := map[string]any{
  73. "type": "text",
  74. "text": text,
  75. }
  76. if cacheControl != nil {
  77. block["cache_control"] = cacheControl
  78. }
  79. return json.Marshal(block)
  80. }
  81. func marshalAnthropicMetadata(userID string) ([]byte, error) {
  82. return json.Marshal(anthropicMetadataPayload{UserID: userID})
  83. }
  84. func buildJSONArrayRaw(items [][]byte) []byte {
  85. if len(items) == 0 {
  86. return []byte("[]")
  87. }
  88. total := 2
  89. for _, item := range items {
  90. total += len(item)
  91. }
  92. total += len(items) - 1
  93. buf := make([]byte, 0, total)
  94. buf = append(buf, '[')
  95. for i, item := range items {
  96. if i > 0 {
  97. buf = append(buf, ',')
  98. }
  99. buf = append(buf, item...)
  100. }
  101. buf = append(buf, ']')
  102. return buf
  103. }
  104. func setJSONValueBytes(body []byte, path string, value any) ([]byte, bool) {
  105. next, err := sjson.SetBytes(body, path, value)
  106. if err != nil {
  107. return body, false
  108. }
  109. return next, true
  110. }
  111. func setJSONRawBytes(body []byte, path string, raw []byte) ([]byte, bool) {
  112. next, err := sjson.SetRawBytes(body, path, raw)
  113. if err != nil {
  114. return body, false
  115. }
  116. return next, true
  117. }
  118. func deleteJSONPathBytes(body []byte, path string) ([]byte, bool) {
  119. next, err := sjson.DeleteBytes(body, path)
  120. if err != nil {
  121. return body, false
  122. }
  123. return next, true
  124. }
  125. func normalizeClaudeOAuthSystemBody(body []byte, opts claudeOAuthNormalizeOptions) ([]byte, bool) {
  126. sys := gjson.GetBytes(body, "system")
  127. if !sys.Exists() {
  128. return body, false
  129. }
  130. out := body
  131. modified := false
  132. switch {
  133. case sys.Type == gjson.String:
  134. sanitized := sanitizeSystemText(sys.String())
  135. if sanitized != sys.String() {
  136. if next, ok := setJSONValueBytes(out, "system", sanitized); ok {
  137. out = next
  138. modified = true
  139. }
  140. }
  141. case sys.IsArray():
  142. index := 0
  143. sys.ForEach(func(_, item gjson.Result) bool {
  144. if item.Get("type").String() == "text" {
  145. textResult := item.Get("text")
  146. if textResult.Exists() && textResult.Type == gjson.String {
  147. text := textResult.String()
  148. sanitized := sanitizeSystemText(text)
  149. if sanitized != text {
  150. if next, ok := setJSONValueBytes(out, fmt.Sprintf("system.%d.text", index), sanitized); ok {
  151. out = next
  152. modified = true
  153. }
  154. }
  155. }
  156. }
  157. if opts.stripSystemCacheControl && item.Get("cache_control").Exists() {
  158. if next, ok := deleteJSONPathBytes(out, fmt.Sprintf("system.%d.cache_control", index)); ok {
  159. out = next
  160. modified = true
  161. }
  162. }
  163. index++
  164. return true
  165. })
  166. }
  167. return out, modified
  168. }
  169. func ensureClaudeOAuthMetadataUserID(body []byte, userID string) ([]byte, bool) {
  170. if strings.TrimSpace(userID) == "" {
  171. return body, false
  172. }
  173. metadata := gjson.GetBytes(body, "metadata")
  174. if !metadata.Exists() || metadata.Type == gjson.Null {
  175. raw, err := marshalAnthropicMetadata(userID)
  176. if err != nil {
  177. return body, false
  178. }
  179. return setJSONRawBytes(body, "metadata", raw)
  180. }
  181. trimmedRaw := strings.TrimSpace(metadata.Raw)
  182. if strings.HasPrefix(trimmedRaw, "{") {
  183. existing := metadata.Get("user_id")
  184. if existing.Exists() && existing.Type == gjson.String && existing.String() != "" {
  185. return body, false
  186. }
  187. return setJSONValueBytes(body, "metadata.user_id", userID)
  188. }
  189. raw, err := marshalAnthropicMetadata(userID)
  190. if err != nil {
  191. return body, false
  192. }
  193. return setJSONRawBytes(body, "metadata", raw)
  194. }
  195. func normalizeClaudeOAuthRequestBody(body []byte, modelID string, opts claudeOAuthNormalizeOptions) ([]byte, string) {
  196. if len(body) == 0 {
  197. return body, modelID
  198. }
  199. out := body
  200. modified := false
  201. if next, changed := normalizeClaudeOAuthSystemBody(out, opts); changed {
  202. out = next
  203. modified = true
  204. }
  205. rawModel := gjson.GetBytes(out, "model")
  206. if rawModel.Exists() && rawModel.Type == gjson.String {
  207. normalized := claude.NormalizeModelID(rawModel.String())
  208. if normalized != rawModel.String() {
  209. if next, ok := setJSONValueBytes(out, "model", normalized); ok {
  210. out = next
  211. modified = true
  212. }
  213. modelID = normalized
  214. }
  215. }
  216. // 确保 tools 字段存在(即使为空数组)
  217. if !gjson.GetBytes(out, "tools").Exists() {
  218. if next, ok := setJSONRawBytes(out, "tools", []byte("[]")); ok {
  219. out = next
  220. modified = true
  221. }
  222. }
  223. if opts.injectMetadata && opts.metadataUserID != "" {
  224. if next, changed := ensureClaudeOAuthMetadataUserID(out, opts.metadataUserID); changed {
  225. out = next
  226. modified = true
  227. }
  228. }
  229. // temperature:真实 Claude Code CLI 总是发送 temperature(默认 1,客户端可覆盖)。
  230. // 之前的实现直接 delete 会导致 payload 缺字段,与真实 CLI 字节级不一致。
  231. // 策略:客户端传了什么就透传;没传则补默认 1。
  232. if !gjson.GetBytes(out, "temperature").Exists() {
  233. if next, ok := setJSONValueBytes(out, "temperature", 1); ok {
  234. out = next
  235. modified = true
  236. }
  237. }
  238. // max_tokens:真实 CLI 的默认值是 128000。缺失时补齐以对齐指纹。
  239. if !gjson.GetBytes(out, "max_tokens").Exists() {
  240. if next, ok := setJSONValueBytes(out, "max_tokens", 128000); ok {
  241. out = next
  242. modified = true
  243. }
  244. }
  245. // context_management:thinking.type 为 enabled/adaptive 时,真实 CLI 会自动
  246. // 附带 {"edits":[{"type":"clear_thinking_20251015","keep":"all"}]}。
  247. // 客户端显式传了就透传;否则按 CLI 行为补齐。
  248. //
  249. // 注:本函数不按 model 名决定是否保留 context_management。“最终 beta
  250. // header 不含 context-management-2025-06-27 时 strip 字段”的能力维度
  251. // 对称约束由 sanitizeAnthropicBodyForBetaTokens 在 buildUpstreamRequest /
  252. // buildCountTokensRequest 层统一执行,与 Bedrock 路径的
  253. // sanitizeBedrockFieldsForBetaTokens 对称。
  254. if !gjson.GetBytes(out, "context_management").Exists() {
  255. thinkingType := gjson.GetBytes(out, "thinking.type").String()
  256. if thinkingType == "enabled" || thinkingType == "adaptive" {
  257. const cmDefault = `{"edits":[{"type":"clear_thinking_20251015","keep":"all"}]}`
  258. if next, ok := setJSONRawBytes(out, "context_management", []byte(cmDefault)); ok {
  259. out = next
  260. modified = true
  261. }
  262. }
  263. }
  264. // tool_choice:与 Parrot 对齐,不再无条件删除。
  265. // - 客户端传了 {"type":"tool","name":"X"} → 保留结构,name 由
  266. // applyToolNameRewriteToBody 同步映射为假名
  267. // - 其他形态(auto/any/none)原样透传
  268. // 如果 body 里完全没有 tools(空数组),tool_choice 没意义时才删除
  269. if !gjson.GetBytes(out, "tools").IsArray() || len(gjson.GetBytes(out, "tools").Array()) == 0 {
  270. if gjson.GetBytes(out, "tool_choice").Exists() {
  271. if next, ok := deleteJSONPathBytes(out, "tool_choice"); ok {
  272. out = next
  273. modified = true
  274. }
  275. }
  276. }
  277. if !modified {
  278. return body, modelID
  279. }
  280. return out, modelID
  281. }
  282. func (s *GatewayService) buildOAuthMetadataUserID(parsed *ParsedRequest, account *Account, fp *Fingerprint) string {
  283. if parsed == nil || account == nil {
  284. return ""
  285. }
  286. if parsed.MetadataUserID != "" {
  287. return ""
  288. }
  289. userID := strings.TrimSpace(account.GetClaudeUserID())
  290. if userID == "" && fp != nil {
  291. userID = fp.ClientID
  292. }
  293. if userID == "" {
  294. // Fall back to a random, well-formed client id so we can still satisfy
  295. // Claude Code OAuth requirements when account metadata is incomplete.
  296. userID = generateClientID()
  297. }
  298. // session_id 用"会话级稳定种子"派生(账号 + 客户端区分因子 + 首条 user 文本):
  299. // 随对话在尾部追加 messages 时保持不变,贴近真实 CC 进程级稳定的 session_id。
  300. // 不复用 GenerateSessionHash —— 后者是粘性路由键、按设计逐轮变化(见其测试)。
  301. var firstUserText string
  302. if parsed.Body != nil {
  303. firstUserText = extractFirstUserText(parsed.Body.Bytes())
  304. }
  305. seed := buildStableSessionSeed(account.ID, sessionContextDiscriminator(parsed.SessionContext), firstUserText)
  306. sessionID := generateSessionUUID(seed)
  307. // 根据指纹 UA 版本选择输出格式
  308. var uaVersion string
  309. if fp != nil {
  310. uaVersion = ExtractCLIVersion(fp.UserAgent)
  311. }
  312. accountUUID := strings.TrimSpace(account.GetExtraString("account_uuid"))
  313. return FormatMetadataUserID(userID, accountUUID, sessionID, uaVersion)
  314. }
  315. // applyClaudeCodeOAuthMimicryToBody 将"非 Claude Code 客户端 + Claude OAuth 账号"
  316. // 路径上原本只在 /v1/messages 里做的完整伪装应用到任意 body 上。
  317. //
  318. // 这是 /v1/messages 主路径上 rewriteSystemForNonClaudeCode +
  319. // normalizeClaudeOAuthRequestBody 流程的通用版,供 OpenAI 协议兼容层
  320. // (ForwardAsChatCompletions / ForwardAsResponses) 复用。
  321. //
  322. // 未抽离之前,OpenAI 协议兼容层仅做 injectClaudeCodePrompt(前置追加),
  323. // 而仓内 /v1/messages 路径自己的注释明确说过"仅前置追加无法通过 Anthropic
  324. // 第三方检测";那条注释就是本函数存在的根因。
  325. //
  326. // 参数:
  327. // - ctx / c:用于读取指纹和 gateway settings;c 可为 nil(如 count_tokens)。
  328. // - account:必须是 OAuth 账号,且调用方已判断不是 Claude Code 客户端。
  329. // - body:已经 marshal 成 Anthropic /v1/messages 格式的请求体。
  330. // - systemRaw:body 中原始 system 字段(用于判断是否需要 rewrite)。
  331. // - model:最终会发给上游的模型 ID(用于模型规范化 + metadata 版本选择)。
  332. //
  333. // 返回:改写后的 body。即使中间任何一步失败,也会退化成原 body(不会 panic)。
  334. func (s *GatewayService) applyClaudeCodeOAuthMimicryToBody(
  335. ctx context.Context,
  336. c *gin.Context,
  337. account *Account,
  338. body []byte,
  339. systemRaw any,
  340. model string,
  341. ) []byte {
  342. if account == nil || !account.IsOAuth() || len(body) == 0 {
  343. return body
  344. }
  345. systemPromptInjectionEnabled, systemPrompt, systemPromptBlocks := s.claudeOAuthSystemPromptInjectionSettings(ctx)
  346. systemRewritten := false
  347. if systemPromptInjectionEnabled {
  348. systemPromptBlocks = claudeOAuthSystemPromptBlocksForModel(model, systemPromptBlocks)
  349. body = rewriteSystemForNonClaudeCodeWithPromptBlocks(body, normalizeSystemParam(systemRaw), systemPrompt, systemPromptBlocks)
  350. systemRewritten = true
  351. }
  352. normalizeOpts := claudeOAuthNormalizeOptions{stripSystemCacheControl: !systemRewritten}
  353. if s.identityService != nil && c != nil && c.Request != nil {
  354. if fp, err := s.identityService.GetOrCreateFingerprint(ctx, account.ID, c.Request.Header); err == nil && fp != nil {
  355. mimicMPT := false
  356. if s.settingService != nil {
  357. _, mimicMPT, _ = s.settingService.GetGatewayForwardingSettings(ctx)
  358. }
  359. if !mimicMPT {
  360. if uid := s.buildOAuthMetadataUserIDFromBody(ctx, account, fp, body); uid != "" {
  361. normalizeOpts.injectMetadata = true
  362. normalizeOpts.metadataUserID = uid
  363. }
  364. }
  365. }
  366. }
  367. body, _ = normalizeClaudeOAuthRequestBody(body, model, normalizeOpts)
  368. // Phase D+E+F: messages cache 策略 + 工具名混淆 + tools[-1] 断点
  369. // 对齐 Parrot transform_request 里剩余的字段级改写。顺序有语义约束:
  370. // 1) messages cache:仅在配置开启时清除客户端断点并注入代理断点
  371. // 2) tool rewrite:最后改 tools[*].name / tool_choice.name 并在 tools[-1]
  372. // 上打断点;mapping 存入 gin.Context 供响应侧 bytes.Replace 还原。
  373. body = s.rewriteMessageCacheControlIfEnabled(ctx, body)
  374. if rw := buildToolNameRewriteFromBody(body); rw != nil {
  375. body = applyToolNameRewriteToBody(body, rw)
  376. if c != nil {
  377. c.Set(toolNameRewriteKey, rw)
  378. }
  379. } else {
  380. body = applyToolsLastCacheBreakpoint(body)
  381. }
  382. return body
  383. }
  384. // buildOAuthMetadataUserIDFromBody 是 buildOAuthMetadataUserID 的变体,
  385. // 适用于调用方手上没有 ParsedRequest 的场景(如 OpenAI 协议兼容层)。
  386. //
  387. // 与 buildOAuthMetadataUserID 的唯一区别:
  388. // - session hash 从 body 本体按同样规则重算,而不是读取 ParsedRequest 缓存值。
  389. // - 如果 body 里已经存在 metadata.user_id,则返回空(由 ensureClaudeOAuthMetadataUserID
  390. // 自行决定是否覆盖)。
  391. func (s *GatewayService) buildOAuthMetadataUserIDFromBody(
  392. ctx context.Context,
  393. account *Account,
  394. fp *Fingerprint,
  395. body []byte,
  396. ) string {
  397. _ = ctx
  398. if account == nil {
  399. return ""
  400. }
  401. if existing := gjson.GetBytes(body, "metadata.user_id").String(); existing != "" {
  402. return ""
  403. }
  404. userID := strings.TrimSpace(account.GetClaudeUserID())
  405. if userID == "" && fp != nil {
  406. userID = fp.ClientID
  407. }
  408. if userID == "" {
  409. userID = generateClientID()
  410. }
  411. // 与 buildOAuthMetadataUserID 一致:用会话级稳定种子,避免整 body 哈希导致
  412. // 每轮(甚至每个 token 变化)都重算出不同的 session_id。
  413. var clientDiscriminator string
  414. if fp != nil {
  415. clientDiscriminator = fp.ClientID
  416. }
  417. seed := buildStableSessionSeed(account.ID, clientDiscriminator, extractFirstUserText(body))
  418. sessionID := generateSessionUUID(seed)
  419. var uaVersion string
  420. if fp != nil {
  421. uaVersion = ExtractCLIVersion(fp.UserAgent)
  422. }
  423. accountUUID := strings.TrimSpace(account.GetExtraString("account_uuid"))
  424. return FormatMetadataUserID(userID, accountUUID, sessionID, uaVersion)
  425. }
  426. // buildStableSessionSeed 为伪装路径合成的 metadata.user_id session_id 生成"会话级稳定"种子。
  427. //
  428. // 真实 Claude Code 的 session_id 是进程级随机 UUID,在一段会话内跨请求保持不变。无状态代理
  429. // 无法恢复该值,这里用"会话内不变的锚点"近似:账号 ID + 客户端区分因子 + 首条 user 消息文本。
  430. // 对话在尾部追加 messages 时这三者都不变,因此 generateSessionUUID(seed) 跨轮稳定。
  431. //
  432. // 注意:粘性路由键 GenerateSessionHash 按设计逐轮变化(见其测试),本函数与之独立、互不影响。
  433. // accountID 恒存在,故 seed 永不为空 —— 输出始终是确定性 UUID,而非随机值。
  434. func buildStableSessionSeed(accountID int64, clientDiscriminator, firstUserText string) string {
  435. var b strings.Builder
  436. _, _ = b.WriteString(strconv.FormatInt(accountID, 10))
  437. _, _ = b.WriteString("::")
  438. _, _ = b.WriteString(clientDiscriminator)
  439. _, _ = b.WriteString("::")
  440. _, _ = b.WriteString(firstUserText)
  441. return b.String()
  442. }
  443. // sessionContextDiscriminator 把请求上下文(客户端 IP / 归一化 UA / API Key ID)拼成
  444. // 一个跨客户端的区分因子,避免不同用户的相同首条消息派生出相同 session_id。
  445. func sessionContextDiscriminator(sc *SessionContext) string {
  446. if sc == nil {
  447. return ""
  448. }
  449. return sc.ClientIP + ":" + NormalizeSessionUserAgent(sc.UserAgent) + ":" + strconv.FormatInt(sc.APIKeyID, 10)
  450. }
  451. // GenerateSessionUUID creates a deterministic UUID4 from a seed string.
  452. func GenerateSessionUUID(seed string) string {
  453. return generateSessionUUID(seed)
  454. }
  455. func generateSessionUUID(seed string) string {
  456. if seed == "" {
  457. return uuid.NewString()
  458. }
  459. hash := sha256.Sum256([]byte(seed))
  460. bytes := hash[:16]
  461. bytes[6] = (bytes[6] & 0x0f) | 0x40
  462. bytes[8] = (bytes[8] & 0x3f) | 0x80
  463. return fmt.Sprintf("%x-%x-%x-%x-%x",
  464. bytes[0:4], bytes[4:6], bytes[6:8], bytes[8:10], bytes[10:16])
  465. }
  466. // normalizeSystemParam 将 json.RawMessage 类型的 system 参数转为标准 Go 类型(string / []any / nil),
  467. // 避免 type switch 中 json.RawMessage(底层 []byte)无法匹配 case string / case []any / case nil 的问题。
  468. // 这是 Go 的 typed nil 陷阱:(json.RawMessage, nil) ≠ (nil, nil)。
  469. func normalizeSystemParam(system any) any {
  470. raw, ok := system.(json.RawMessage)
  471. if !ok {
  472. return system
  473. }
  474. if len(raw) == 0 {
  475. return nil
  476. }
  477. var parsed any
  478. if err := json.Unmarshal(raw, &parsed); err != nil {
  479. return nil
  480. }
  481. return parsed
  482. }
  483. // systemIncludesClaudeCodePrompt 检查 system 中是否已包含 Claude Code 提示词
  484. // 使用前缀匹配支持多种变体(标准版、Agent SDK 版等)
  485. func systemIncludesClaudeCodePrompt(system any) bool {
  486. system = normalizeSystemParam(system)
  487. switch v := system.(type) {
  488. case string:
  489. return hasClaudeCodePrefix(v)
  490. case []any:
  491. for _, item := range v {
  492. if m, ok := item.(map[string]any); ok {
  493. if text, ok := m["text"].(string); ok && hasClaudeCodePrefix(text) {
  494. return true
  495. }
  496. }
  497. }
  498. }
  499. return false
  500. }
  501. // hasClaudeCodePrefix 检查文本是否以 Claude Code 提示词的特征前缀开头
  502. func hasClaudeCodePrefix(text string) bool {
  503. for _, prefix := range claudeCodePromptPrefixes {
  504. if strings.HasPrefix(text, prefix) {
  505. return true
  506. }
  507. }
  508. return false
  509. }
  510. // injectClaudeCodePrompt 在 system 开头注入 Claude Code 提示词
  511. // 处理 null、字符串、数组三种格式
  512. func injectClaudeCodePrompt(body []byte, system any) []byte {
  513. system = normalizeSystemParam(system)
  514. claudeCodeBlock, err := marshalAnthropicSystemTextBlock(claudeCodeSystemPrompt, true)
  515. if err != nil {
  516. logger.LegacyPrintf("service.gateway", "Warning: failed to build Claude Code prompt block: %v", err)
  517. return body
  518. }
  519. // Opencode plugin applies an extra safeguard: it not only prepends the Claude Code
  520. // banner, it also prefixes the next system instruction with the same banner plus
  521. // a blank line. This helps when upstream concatenates system instructions.
  522. claudeCodePrefix := strings.TrimSpace(claudeCodeSystemPrompt)
  523. var items [][]byte
  524. switch v := system.(type) {
  525. case nil:
  526. items = [][]byte{claudeCodeBlock}
  527. case string:
  528. // Be tolerant of older/newer clients that may differ only by trailing whitespace/newlines.
  529. if strings.TrimSpace(v) == "" || strings.TrimSpace(v) == strings.TrimSpace(claudeCodeSystemPrompt) {
  530. items = [][]byte{claudeCodeBlock}
  531. } else {
  532. // Mirror opencode behavior: keep the banner as a separate system entry,
  533. // but also prefix the next system text with the banner.
  534. merged := v
  535. if !strings.HasPrefix(v, claudeCodePrefix) {
  536. merged = claudeCodePrefix + "\n\n" + v
  537. }
  538. nextBlock, buildErr := marshalAnthropicSystemTextBlock(merged, false)
  539. if buildErr != nil {
  540. logger.LegacyPrintf("service.gateway", "Warning: failed to build prefixed Claude Code system block: %v", buildErr)
  541. return body
  542. }
  543. items = [][]byte{claudeCodeBlock, nextBlock}
  544. }
  545. case []any:
  546. items = make([][]byte, 0, len(v)+1)
  547. items = append(items, claudeCodeBlock)
  548. prefixedNext := false
  549. systemResult := gjson.GetBytes(body, "system")
  550. if systemResult.IsArray() {
  551. systemResult.ForEach(func(_, item gjson.Result) bool {
  552. textResult := item.Get("text")
  553. if textResult.Exists() && textResult.Type == gjson.String &&
  554. strings.TrimSpace(textResult.String()) == strings.TrimSpace(claudeCodeSystemPrompt) {
  555. return true
  556. }
  557. raw := []byte(item.Raw)
  558. // Prefix the first subsequent text system block once.
  559. if !prefixedNext && item.Get("type").String() == "text" && textResult.Exists() && textResult.Type == gjson.String {
  560. text := textResult.String()
  561. if strings.TrimSpace(text) != "" && !strings.HasPrefix(text, claudeCodePrefix) {
  562. next, setErr := sjson.SetBytes(raw, "text", claudeCodePrefix+"\n\n"+text)
  563. if setErr == nil {
  564. raw = next
  565. prefixedNext = true
  566. }
  567. }
  568. }
  569. items = append(items, raw)
  570. return true
  571. })
  572. } else {
  573. for _, item := range v {
  574. m, ok := item.(map[string]any)
  575. if !ok {
  576. raw, marshalErr := json.Marshal(item)
  577. if marshalErr == nil {
  578. items = append(items, raw)
  579. }
  580. continue
  581. }
  582. if text, ok := m["text"].(string); ok && strings.TrimSpace(text) == strings.TrimSpace(claudeCodeSystemPrompt) {
  583. continue
  584. }
  585. if !prefixedNext {
  586. if blockType, _ := m["type"].(string); blockType == "text" {
  587. if text, ok := m["text"].(string); ok && strings.TrimSpace(text) != "" && !strings.HasPrefix(text, claudeCodePrefix) {
  588. m["text"] = claudeCodePrefix + "\n\n" + text
  589. prefixedNext = true
  590. }
  591. }
  592. }
  593. raw, marshalErr := json.Marshal(m)
  594. if marshalErr == nil {
  595. items = append(items, raw)
  596. }
  597. }
  598. }
  599. default:
  600. items = [][]byte{claudeCodeBlock}
  601. }
  602. result, ok := setJSONRawBytes(body, "system", buildJSONArrayRaw(items))
  603. if !ok {
  604. logger.LegacyPrintf("service.gateway", "Warning: failed to inject Claude Code prompt")
  605. return body
  606. }
  607. return result
  608. }
  609. // rewriteSystemForNonClaudeCode 将非 Claude Code 客户端的 system prompt 迁移至 messages,
  610. // system 字段仅保留 Claude Code 标识提示词。
  611. // Anthropic 基于 system 参数内容检测第三方应用,仅前置追加 Claude Code 提示词
  612. // 无法通过检测,因为后续内容仍为非 Claude Code 格式。
  613. // 策略:将原始 system prompt 提取并注入为 user/assistant 消息对,system 仅保留 Claude Code 标识。
  614. func rewriteSystemForNonClaudeCode(body []byte, system any) []byte {
  615. return rewriteSystemForNonClaudeCodeWithPromptBlocks(body, system, "", "")
  616. }
  617. func rewriteSystemForNonClaudeCodeWithPrompt(body []byte, system any, expansionPrompt string) []byte {
  618. return rewriteSystemForNonClaudeCodeWithPromptBlocks(body, system, expansionPrompt, "")
  619. }
  620. type claudeOAuthSystemPromptBlockConfig struct {
  621. Enabled *bool `json:"enabled,omitempty"`
  622. Type string `json:"type,omitempty"`
  623. Text string `json:"text,omitempty"`
  624. CacheControl json.RawMessage `json:"cache_control,omitempty"`
  625. }
  626. type claudeOAuthSystemPromptBlocksEnvelope struct {
  627. Blocks []claudeOAuthSystemPromptBlockConfig `json:"blocks"`
  628. }
  629. // claudeFableOAuthSystemPromptBlocks keeps the Claude Code identity required by
  630. // OAuth credentials without the generic CLI expansion block. Fable 5 rejects
  631. // that expansion upstream with stop_reason=refusal and zero output tokens,
  632. // while the native billing + identity shape is accepted. Original client
  633. // system instructions are still migrated into the message history by
  634. // rewriteSystemForNonClaudeCodeWithPromptBlocks.
  635. const claudeFableOAuthSystemPromptBlocks = `[
  636. {"type":"text","text":"{billing_header}"},
  637. {"type":"text","text":"{claude_code_system_prompt}"}
  638. ]`
  639. func claudeOAuthSystemPromptBlocksForModel(model, configured string) string {
  640. if isAnthropicFableModel(model) {
  641. return claudeFableOAuthSystemPromptBlocks
  642. }
  643. return configured
  644. }
  645. func defaultClaudeOAuthExpansionPrompt(expansionPrompt string) string {
  646. expansionPrompt = strings.TrimSpace(expansionPrompt)
  647. if expansionPrompt == "" {
  648. return claudeCodeSystemPromptExpansion
  649. }
  650. return expansionPrompt
  651. }
  652. func parseClaudeOAuthSystemPromptBlocksConfig(raw string) ([]claudeOAuthSystemPromptBlockConfig, error) {
  653. raw = strings.TrimSpace(raw)
  654. if raw == "" {
  655. return nil, nil
  656. }
  657. if strings.HasPrefix(raw, "[") {
  658. var blocks []claudeOAuthSystemPromptBlockConfig
  659. if err := json.Unmarshal([]byte(raw), &blocks); err != nil {
  660. return nil, err
  661. }
  662. return blocks, nil
  663. }
  664. var envelope claudeOAuthSystemPromptBlocksEnvelope
  665. if err := json.Unmarshal([]byte(raw), &envelope); err != nil {
  666. return nil, err
  667. }
  668. return envelope.Blocks, nil
  669. }
  670. func decodeClaudeOAuthSystemPromptCacheControl(raw json.RawMessage) (any, error) {
  671. trimmed := bytes.TrimSpace(raw)
  672. if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) || bytes.Equal(trimmed, []byte("false")) {
  673. return nil, nil
  674. }
  675. if bytes.Equal(trimmed, []byte("true")) {
  676. return map[string]string{
  677. "type": "ephemeral",
  678. "ttl": claude.DefaultCacheControlTTL,
  679. }, nil
  680. }
  681. var value any
  682. if err := json.Unmarshal(trimmed, &value); err != nil {
  683. return nil, err
  684. }
  685. if _, ok := value.(map[string]any); !ok {
  686. return nil, fmt.Errorf("cache_control must be boolean, null, or object")
  687. }
  688. return value, nil
  689. }
  690. func expandClaudeOAuthSystemPromptTextTemplate(body []byte, text string, expansionPrompt string) (string, error) {
  691. if text == "" {
  692. return "", nil
  693. }
  694. expansionPrompt = defaultClaudeOAuthExpansionPrompt(expansionPrompt)
  695. billingText, err := buildBillingAttributionText(body, claude.CLIVersion())
  696. if err != nil {
  697. return "", err
  698. }
  699. fp := computeClaudeCodeFingerprint(body, claude.CLIVersion())
  700. replacer := strings.NewReplacer(
  701. "{billing_header}", billingText,
  702. "{cc_version}", claude.CLIVersion(),
  703. "{fp}", fp,
  704. "{claude_code_system_prompt}", claudeCodeSystemPrompt,
  705. "{claude_code_expansion_prompt}", expansionPrompt,
  706. )
  707. return replacer.Replace(text), nil
  708. }
  709. func defaultClaudeOAuthSystemPromptBlockConfig() []claudeOAuthSystemPromptBlockConfig {
  710. enabled := true
  711. return []claudeOAuthSystemPromptBlockConfig{
  712. {
  713. Enabled: &enabled,
  714. Type: "text",
  715. Text: "{billing_header}",
  716. },
  717. {
  718. Enabled: &enabled,
  719. Type: "text",
  720. Text: "{claude_code_system_prompt}",
  721. },
  722. {
  723. Enabled: &enabled,
  724. Type: "text",
  725. Text: "{claude_code_expansion_prompt}",
  726. CacheControl: json.RawMessage(
  727. fmt.Sprintf(`{"type":"ephemeral","ttl":%q}`, claude.DefaultCacheControlTTL),
  728. ),
  729. },
  730. }
  731. }
  732. func buildClaudeOAuthSystemPromptBlocksJSON(body []byte, expansionPrompt string, blocksConfig string) ([][]byte, error) {
  733. blocks, err := parseClaudeOAuthSystemPromptBlocksConfig(blocksConfig)
  734. if err != nil {
  735. return nil, err
  736. }
  737. if len(blocks) == 0 {
  738. blocks = defaultClaudeOAuthSystemPromptBlockConfig()
  739. }
  740. items := make([][]byte, 0, len(blocks))
  741. for i, block := range blocks {
  742. if block.Enabled != nil && !*block.Enabled {
  743. continue
  744. }
  745. blockType := strings.TrimSpace(block.Type)
  746. if blockType == "" {
  747. blockType = "text"
  748. }
  749. if blockType != "text" {
  750. return nil, fmt.Errorf("system block %d type %q is not supported", i, block.Type)
  751. }
  752. text, err := expandClaudeOAuthSystemPromptTextTemplate(body, block.Text, expansionPrompt)
  753. if err != nil {
  754. return nil, err
  755. }
  756. if strings.TrimSpace(text) == "" {
  757. continue
  758. }
  759. cacheControl, err := decodeClaudeOAuthSystemPromptCacheControl(block.CacheControl)
  760. if err != nil {
  761. return nil, fmt.Errorf("system block %d cache_control: %w", i, err)
  762. }
  763. raw, err := marshalAnthropicSystemTextBlockWithCacheControl(text, cacheControl)
  764. if err != nil {
  765. return nil, err
  766. }
  767. items = append(items, raw)
  768. }
  769. return items, nil
  770. }
  771. func ValidateClaudeOAuthSystemPromptBlocksConfig(raw string) error {
  772. if strings.TrimSpace(raw) == "" {
  773. return nil
  774. }
  775. blocks, err := parseClaudeOAuthSystemPromptBlocksConfig(raw)
  776. if err != nil {
  777. return infraerrors.BadRequest("INVALID_CLAUDE_OAUTH_SYSTEM_PROMPT_BLOCKS", "claude oauth system prompt blocks must be valid JSON")
  778. }
  779. for i, block := range blocks {
  780. blockType := strings.TrimSpace(block.Type)
  781. if blockType == "" {
  782. blockType = "text"
  783. }
  784. if blockType != "text" {
  785. return infraerrors.BadRequest("INVALID_CLAUDE_OAUTH_SYSTEM_PROMPT_BLOCKS", fmt.Sprintf("system block %d type must be text", i))
  786. }
  787. if _, err := decodeClaudeOAuthSystemPromptCacheControl(block.CacheControl); err != nil {
  788. return infraerrors.BadRequest("INVALID_CLAUDE_OAUTH_SYSTEM_PROMPT_BLOCKS", fmt.Sprintf("system block %d cache_control is invalid", i))
  789. }
  790. }
  791. return nil
  792. }
  793. func extractSystemTextAndCacheControl(system any) (string, any) {
  794. switch v := system.(type) {
  795. case string:
  796. return strings.TrimSpace(v), nil
  797. case []any:
  798. var parts []string
  799. var cacheControl any
  800. for _, item := range v {
  801. m, ok := item.(map[string]any)
  802. if !ok {
  803. continue
  804. }
  805. text, ok := m["text"].(string)
  806. if !ok || strings.TrimSpace(text) == "" {
  807. continue
  808. }
  809. parts = append(parts, text)
  810. // system blocks are collapsed into one messages text block below.
  811. // Preserve the last original breakpoint as the closest equivalent
  812. // boundary, including its client-selected TTL.
  813. if cc, exists := m["cache_control"]; exists && cc != nil {
  814. cacheControl = cc
  815. }
  816. }
  817. return strings.Join(parts, "\n\n"), cacheControl
  818. default:
  819. return "", nil
  820. }
  821. }
  822. func rewriteSystemForNonClaudeCodeWithPromptBlocks(body []byte, system any, expansionPrompt string, blocksConfig string) []byte {
  823. system = normalizeSystemParam(system)
  824. expansionPrompt = defaultClaudeOAuthExpansionPrompt(expansionPrompt)
  825. // 1. 提取原始 system prompt 文本及其缓存断点
  826. originalSystemText, originalSystemCacheControl := extractSystemTextAndCacheControl(system)
  827. // 2. 构造 system 数组,对齐真实 Claude Code CLI 的 3-block 形态:
  828. // [0] billing attribution block(cc_version={cliVer}.{fp}; cc_entrypoint=cli;)
  829. // [1] "You are Claude Code..." 身份前缀 block(默认不带 cache_control)
  830. // [2] 工具无关的通用提示词扩充 block(带 cache_control 作为稳定缓存断点)
  831. //
  832. // 真实 CC 的 system 在身份前缀之后还有大段提示词,仅有 2 块会在块数/体量上明显
  833. // 区别于真实 CLI。这里注入 claudeCodeSystemPromptExpansion(中性段落)把形态做到
  834. // 接近真实,同时不注入会污染被代理用户行为的工具专属指令。
  835. //
  836. // 缺失 billing block 的系统 payload 是 Anthropic 判定第三方的关键信号之一
  837. // (真实 CLI 每个请求都带)。新版 CLI 已取消 cch=... 签名字段,故 block 不再注入
  838. // cch(见 buildBillingAttributionText)。
  839. systemBlocks, blockErr := buildClaudeOAuthSystemPromptBlocksJSON(body, expansionPrompt, blocksConfig)
  840. if blockErr != nil {
  841. logger.LegacyPrintf("service.gateway", "Warning: failed to build configured Claude OAuth system blocks: %v", blockErr)
  842. systemBlocks, blockErr = buildClaudeOAuthSystemPromptBlocksJSON(body, expansionPrompt, "")
  843. }
  844. if blockErr != nil {
  845. logger.LegacyPrintf("service.gateway", "Warning: failed to build default Claude OAuth system blocks: %v", blockErr)
  846. return body
  847. }
  848. out, ok := setJSONRawBytes(body, "system", buildJSONArrayRaw(systemBlocks))
  849. if !ok {
  850. logger.LegacyPrintf("service.gateway", "Warning: failed to set Claude Code system prompt")
  851. return body
  852. }
  853. // 3. 将原始 system prompt 作为 user/assistant 消息对注入到 messages 开头
  854. // 模型仍通过 messages 接收完整指令,保留客户端功能
  855. ccPromptTrimmed := strings.TrimSpace(claudeCodeSystemPrompt)
  856. if originalSystemText != "" && originalSystemText != ccPromptTrimmed && !hasClaudeCodePrefix(originalSystemText) {
  857. instructionBlock := map[string]any{
  858. "type": "text",
  859. "text": "[System Instructions]\n" + originalSystemText,
  860. }
  861. if originalSystemCacheControl != nil {
  862. instructionBlock["cache_control"] = originalSystemCacheControl
  863. }
  864. instrMsg, err1 := json.Marshal(map[string]any{
  865. "role": "user",
  866. "content": []map[string]any{
  867. instructionBlock,
  868. },
  869. })
  870. ackMsg, err2 := json.Marshal(map[string]any{
  871. "role": "assistant",
  872. "content": []map[string]any{
  873. {"type": "text", "text": "Understood. I will follow these instructions."},
  874. },
  875. })
  876. if err1 != nil || err2 != nil {
  877. logger.LegacyPrintf("service.gateway", "Warning: failed to marshal system-to-messages injection")
  878. return out
  879. }
  880. // 重建 messages 数组:[instruction, ack, ...originalMessages]
  881. items := [][]byte{instrMsg, ackMsg}
  882. messagesResult := gjson.GetBytes(out, "messages")
  883. if messagesResult.IsArray() {
  884. messagesResult.ForEach(func(_, msg gjson.Result) bool {
  885. items = append(items, []byte(msg.Raw))
  886. return true
  887. })
  888. }
  889. if next, setOk := setJSONRawBytes(out, "messages", buildJSONArrayRaw(items)); setOk {
  890. out = next
  891. }
  892. }
  893. return out
  894. }
  895. type cacheControlPath struct {
  896. path string
  897. log string
  898. }
  899. func collectCacheControlPaths(body []byte) (invalidThinking []cacheControlPath, messagePaths []string, toolPaths []string, systemPaths []string) {
  900. system := gjson.GetBytes(body, "system")
  901. if system.IsArray() {
  902. sysIndex := 0
  903. system.ForEach(func(_, item gjson.Result) bool {
  904. if item.Get("cache_control").Exists() {
  905. path := fmt.Sprintf("system.%d.cache_control", sysIndex)
  906. if item.Get("type").String() == "thinking" {
  907. invalidThinking = append(invalidThinking, cacheControlPath{
  908. path: path,
  909. log: "[Warning] Removed illegal cache_control from thinking block in system",
  910. })
  911. } else {
  912. systemPaths = append(systemPaths, path)
  913. }
  914. }
  915. sysIndex++
  916. return true
  917. })
  918. }
  919. messages := gjson.GetBytes(body, "messages")
  920. if messages.IsArray() {
  921. msgIndex := 0
  922. messages.ForEach(func(_, msg gjson.Result) bool {
  923. content := msg.Get("content")
  924. if content.IsArray() {
  925. contentIndex := 0
  926. content.ForEach(func(_, item gjson.Result) bool {
  927. if item.Get("cache_control").Exists() {
  928. path := fmt.Sprintf("messages.%d.content.%d.cache_control", msgIndex, contentIndex)
  929. if item.Get("type").String() == "thinking" {
  930. invalidThinking = append(invalidThinking, cacheControlPath{
  931. path: path,
  932. log: fmt.Sprintf("[Warning] Removed illegal cache_control from thinking block in messages[%d].content[%d]", msgIndex, contentIndex),
  933. })
  934. } else {
  935. messagePaths = append(messagePaths, path)
  936. }
  937. }
  938. contentIndex++
  939. return true
  940. })
  941. }
  942. msgIndex++
  943. return true
  944. })
  945. }
  946. tools := gjson.GetBytes(body, "tools")
  947. if tools.IsArray() {
  948. toolIndex := 0
  949. tools.ForEach(func(_, tool gjson.Result) bool {
  950. if tool.Get("cache_control").Exists() {
  951. toolPaths = append(toolPaths, fmt.Sprintf("tools.%d.cache_control", toolIndex))
  952. }
  953. toolIndex++
  954. return true
  955. })
  956. }
  957. return invalidThinking, messagePaths, toolPaths, systemPaths
  958. }
  959. // enforceCacheControlLimit 强制执行 cache_control 块数量限制(最多 4 个)
  960. // 超限时优先移除工具断点,再移除 messages 断点,最后才移除 system 断点。
  961. func enforceCacheControlLimit(body []byte) []byte {
  962. if len(body) == 0 {
  963. return body
  964. }
  965. invalidThinking, messagePaths, toolPaths, systemPaths := collectCacheControlPaths(body)
  966. out := body
  967. modified := false
  968. // 先清理 thinking 块中的非法 cache_control(thinking 块不支持该字段)
  969. for _, item := range invalidThinking {
  970. if !gjson.GetBytes(out, item.path).Exists() {
  971. continue
  972. }
  973. next, ok := deleteJSONPathBytes(out, item.path)
  974. if !ok {
  975. continue
  976. }
  977. out = next
  978. modified = true
  979. logger.LegacyPrintf("service.gateway", "%s", item.log)
  980. }
  981. count := len(messagePaths) + len(toolPaths) + len(systemPaths)
  982. if count <= maxCacheControlBlocks {
  983. if modified {
  984. return out
  985. }
  986. return body
  987. }
  988. // 超限:优先从 tools 中移除,再从 messages 中移除,最后才从 system 中移除。
  989. remaining := count - maxCacheControlBlocks
  990. for i := len(toolPaths) - 1; i >= 0 && remaining > 0; i-- {
  991. path := toolPaths[i]
  992. if !gjson.GetBytes(out, path).Exists() {
  993. continue
  994. }
  995. next, ok := deleteJSONPathBytes(out, path)
  996. if !ok {
  997. continue
  998. }
  999. out = next
  1000. modified = true
  1001. remaining--
  1002. }
  1003. for _, path := range messagePaths {
  1004. if remaining <= 0 {
  1005. break
  1006. }
  1007. if !gjson.GetBytes(out, path).Exists() {
  1008. continue
  1009. }
  1010. next, ok := deleteJSONPathBytes(out, path)
  1011. if !ok {
  1012. continue
  1013. }
  1014. out = next
  1015. modified = true
  1016. remaining--
  1017. }
  1018. for i := len(systemPaths) - 1; i >= 0 && remaining > 0; i-- {
  1019. path := systemPaths[i]
  1020. if !gjson.GetBytes(out, path).Exists() {
  1021. continue
  1022. }
  1023. next, ok := deleteJSONPathBytes(out, path)
  1024. if !ok {
  1025. continue
  1026. }
  1027. out = next
  1028. modified = true
  1029. remaining--
  1030. }
  1031. if modified {
  1032. return out
  1033. }
  1034. return body
  1035. }
  1036. // injectAnthropicCacheControlTTL1h 将已有 ephemeral cache_control 块的 ttl 强制写为 1h。
  1037. // 仅修改已经存在的 cache_control,不新增缓存断点。
  1038. func injectAnthropicCacheControlTTL1h(body []byte) []byte {
  1039. return forceEphemeralCacheControlTTL(body, cacheTTLTarget1h)
  1040. }
  1041. func forceEphemeralCacheControlTTL(body []byte, ttl string) []byte {
  1042. if len(body) == 0 || ttl == "" {
  1043. return body
  1044. }
  1045. out := body
  1046. var paths []string
  1047. addPath := func(path string, value gjson.Result) {
  1048. cc := value.Get("cache_control")
  1049. if !cc.Exists() || cc.Get("type").String() != "ephemeral" {
  1050. return
  1051. }
  1052. if cc.Get("ttl").String() == ttl {
  1053. return
  1054. }
  1055. paths = append(paths, path+".cache_control.ttl")
  1056. }
  1057. if topCC := gjson.GetBytes(body, "cache_control"); topCC.Exists() && topCC.Get("type").String() == "ephemeral" && topCC.Get("ttl").String() != ttl {
  1058. paths = append(paths, "cache_control.ttl")
  1059. }
  1060. system := gjson.GetBytes(body, "system")
  1061. if system.IsArray() {
  1062. idx := -1
  1063. system.ForEach(func(_, block gjson.Result) bool {
  1064. idx++
  1065. addPath(fmt.Sprintf("system.%d", idx), block)
  1066. return true
  1067. })
  1068. }
  1069. messages := gjson.GetBytes(body, "messages")
  1070. if messages.IsArray() {
  1071. msgIdx := -1
  1072. messages.ForEach(func(_, msg gjson.Result) bool {
  1073. msgIdx++
  1074. content := msg.Get("content")
  1075. if !content.IsArray() {
  1076. return true
  1077. }
  1078. contentIdx := -1
  1079. content.ForEach(func(_, block gjson.Result) bool {
  1080. contentIdx++
  1081. addPath(fmt.Sprintf("messages.%d.content.%d", msgIdx, contentIdx), block)
  1082. return true
  1083. })
  1084. return true
  1085. })
  1086. }
  1087. tools := gjson.GetBytes(body, "tools")
  1088. if tools.IsArray() {
  1089. idx := -1
  1090. tools.ForEach(func(_, tool gjson.Result) bool {
  1091. idx++
  1092. addPath(fmt.Sprintf("tools.%d", idx), tool)
  1093. return true
  1094. })
  1095. }
  1096. for _, path := range paths {
  1097. if next, err := sjson.SetBytes(out, path, ttl); err == nil {
  1098. out = next
  1099. }
  1100. }
  1101. return out
  1102. }
  1103. func (s *GatewayService) shouldInjectAnthropicCacheTTL1h(ctx context.Context, account *Account) bool {
  1104. if account == nil || !account.IsAnthropicOAuthOrSetupToken() || s == nil || s.settingService == nil {
  1105. return false
  1106. }
  1107. return s.settingService.IsAnthropicCacheTTL1hInjectionEnabled(ctx)
  1108. }
  1109. // shouldNormalizeClientDateline reports whether the request body's client
  1110. // dateline should be normalized before forwarding to Anthropic. The switch is
  1111. // scoped to Anthropic OAuth/SetupToken accounts only; API-Key accounts and
  1112. // non-Anthropic platforms bypass this step entirely.
  1113. func (s *GatewayService) shouldNormalizeClientDateline(ctx context.Context, account *Account) bool {
  1114. if account == nil || !account.IsAnthropicOAuthOrSetupToken() || s == nil || s.settingService == nil {
  1115. return false
  1116. }
  1117. return s.settingService.IsClientDatelineNormalizationEnabled(ctx)
  1118. }
  1119. // normalizeClientDatelineIfEnabled applies dateline normalization to body when
  1120. // the switch is on and the account qualifies. Returns (nextBody, true) only
  1121. // when the body actually changed; otherwise returns (nil, false) so callers
  1122. // can skip the writeback.
  1123. func (s *GatewayService) normalizeClientDatelineIfEnabled(ctx context.Context, account *Account, body []byte) ([]byte, bool) {
  1124. if !s.shouldNormalizeClientDateline(ctx, account) {
  1125. return nil, false
  1126. }
  1127. next, _, changed := anthropicfp.NormalizeDateline(body)
  1128. if !changed {
  1129. return nil, false
  1130. }
  1131. return next, true
  1132. }
  1133. func (s *GatewayService) claudeOAuthSystemPromptInjectionSettings(ctx context.Context) (bool, string, string) {
  1134. if s == nil || s.settingService == nil {
  1135. return true, "", ""
  1136. }
  1137. return s.settingService.GetClaudeOAuthSystemPromptInjectionSettings(ctx)
  1138. }
  1139. // systemHasBillingAttributionBlock 检查请求体的 system 字段中是否包含真实 Claude Code
  1140. // 客户端注入的 billing attribution block。该 block 格式稳定(见 gateway_billing_block.go),
  1141. // 仅由真实 Claude Code CLI 生成;第三方客户端(opencode 等)不会生成此 block。
  1142. //
  1143. // 用于识别被上游 API 网关代理的真实 Claude Code 流量:此类请求的 User-Agent 被网关替换
  1144. // 为 Go-http-client,但 body 保留了完整的客户端特征。如果不识别这类请求而走 mimicry
  1145. // 重写 system,会破坏 Anthropic prompt cache 的前缀一致性,导致 messages 级缓存永不命中。
  1146. func systemHasBillingAttributionBlock(body []byte) bool {
  1147. system := gjson.GetBytes(body, "system")
  1148. if !system.IsArray() {
  1149. return false
  1150. }
  1151. found := false
  1152. system.ForEach(func(_, item gjson.Result) bool {
  1153. text := item.Get("text").String()
  1154. if strings.HasPrefix(text, claudeCodeBillingHeaderPrefix) &&
  1155. strings.Contains(text, claudeCodeEntrypointMarker) {
  1156. found = true
  1157. return false
  1158. }
  1159. return true
  1160. })
  1161. return found
  1162. }