openai_codex_models_service.go 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582
  1. package service
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha256"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "sort"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/Wei-Shaw/sub2api/internal/pkg/claude"
  18. infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
  19. "github.com/Wei-Shaw/sub2api/internal/pkg/httpclient"
  20. "github.com/Wei-Shaw/sub2api/internal/pkg/openai"
  21. "github.com/Wei-Shaw/sub2api/internal/pkg/xai"
  22. "golang.org/x/net/http2"
  23. "golang.org/x/sync/singleflight"
  24. )
  25. // chatgptCodexModelsURL is the ChatGPT Codex models manifest endpoint.
  26. // Package-level variable so tests can point it at a stub server.
  27. var chatgptCodexModelsURL = "https://chatgpt.com/backend-api/codex/models"
  28. const (
  29. openAIModelsCacheBodyLimit = 1 << 20
  30. // openAIModelsCacheMaxEntries 上限按「账号数 × 客户端版本数 × 代理形态」
  31. // 估算:缓存同时覆盖 OAuth 与 API Key 账号,且缓存键含 Authorization 与
  32. // Version 头,不同客户端版本各自占一条;64 条在大规模部署下会被淘汰导致
  33. // 额外上游请求。单条清单通常几十 KB,512 条最坏内存占用在几十 MB 量级。
  34. openAIModelsCacheMaxEntries = 512
  35. // 三段时效:≤TTL 为新鲜(直接返回缓存,零上游请求);TTL 到 StaleTTL 之间
  36. // 乐观返回旧值并后台单飞刷新(携带上游 ETag,304 续期);超过 StaleTTL 丢弃
  37. // 缓存同步等待刷新。TTL 取 1 分钟:manifest 变化低频,1 分钟内同账号重复
  38. // 请求完全吸收;StaleTTL 取 5 分钟,控制旧内容最长可见时间在分钟级。
  39. openAIModelsCacheTTL = 60 * time.Second
  40. openAIModelsCacheStaleTTL = 5 * time.Minute
  41. codexModelsManifestRequestTimeout = 15 * time.Second
  42. codexAutoModelPrefix = "codex-auto-"
  43. )
  44. // FilterCodexModelIDsForGroup removes dedicated media-generation models,
  45. // wildcard mapping keys, and Codex automatic modes from a client catalog.
  46. // Automatic modes are retained only when the group's enabled model allowlist
  47. // explicitly selects the exact slug; account model mappings describe routing
  48. // and are not feature opt-ins. Wildcard keys such as "foo-*" are routing
  49. // patterns, not concrete Codex models. When the allowlist is enabled the
  50. // catalog is additionally restricted by FilterForListing (wildcard entries
  51. // expand against the catalog).
  52. func FilterCodexModelIDsForGroup(modelIDs []string, group *Group) []string {
  53. explicitlyEnabled := make(map[string]struct{})
  54. if group != nil && group.ModelAllowlistEnabled() {
  55. for _, modelID := range group.ModelAllowlist.Models {
  56. modelID = strings.TrimSpace(modelID)
  57. if strings.HasPrefix(modelID, codexAutoModelPrefix) {
  58. explicitlyEnabled[modelID] = struct{}{}
  59. }
  60. }
  61. }
  62. filtered := make([]string, 0, len(modelIDs))
  63. for _, modelID := range modelIDs {
  64. modelID = strings.TrimSpace(modelID)
  65. if modelID == "" {
  66. continue
  67. }
  68. if isCodexDedicatedMediaModel(modelID) {
  69. continue
  70. }
  71. if strings.Contains(modelID, "*") {
  72. continue
  73. }
  74. if strings.HasPrefix(modelID, codexAutoModelPrefix) {
  75. if _, ok := explicitlyEnabled[modelID]; !ok {
  76. continue
  77. }
  78. }
  79. filtered = append(filtered, modelID)
  80. }
  81. if group != nil && group.ModelAllowlistEnabled() {
  82. filtered = group.ModelAllowlist.FilterForListing(filtered)
  83. }
  84. return filtered
  85. }
  86. func isCodexDedicatedMediaModel(modelID string) bool {
  87. canonical := codexProviderQualifiedModelID(modelID)
  88. return IsGPTImageGenerationModel(canonical) ||
  89. isImageGenerationModel(canonical) ||
  90. xai.IsGrokImagineModel(modelID)
  91. }
  92. func codexProviderQualifiedModelID(modelID string) string {
  93. modelID = strings.TrimSpace(modelID)
  94. if slash := strings.LastIndexByte(modelID, '/'); slash >= 0 {
  95. modelID = strings.TrimSpace(modelID[slash+1:])
  96. }
  97. return strings.TrimPrefix(modelID, "models/")
  98. }
  99. // OpenAIModelsResponse carries either an OpenAI model list or a Codex manifest
  100. // together with upstream and client caching metadata.
  101. type OpenAIModelsResponse struct {
  102. Body []byte
  103. ETag string
  104. upstreamETag string
  105. upstreamSourceBody []byte
  106. convertedFromOpenAIModelList bool
  107. NotModified bool
  108. }
  109. // BuildGroupConfiguredCodexModelsManifest builds a Codex catalog from configured
  110. // public model names, supplemented by defaults for unmapped OpenAI accounts. The
  111. // boolean result distinguishes "no explicit configuration" from a configured
  112. // catalog that becomes empty after group-level filtering.
  113. func (s *OpenAIGatewayService) BuildGroupConfiguredCodexModelsManifest(
  114. ctx context.Context,
  115. group *Group,
  116. ifNoneMatch string,
  117. ) (*OpenAIModelsResponse, bool, error) {
  118. if s == nil || s.accountRepo == nil || group == nil || group.Platform != PlatformOpenAI {
  119. return nil, false, nil
  120. }
  121. visible, catalog, err := loadCodexGroupCatalogAccounts(ctx, s.accountRepo, group.ID)
  122. if err != nil {
  123. return nil, false, fmt.Errorf("load group configured Codex models: %w", err)
  124. }
  125. configuredModels := openAIConfiguredCodexModelIDsForGroup(visible, group)
  126. if len(configuredModels) == 0 {
  127. return nil, false, nil
  128. }
  129. body, err := buildCodexModelsManifestForAccounts(
  130. PlatformOpenAI,
  131. configuredModels,
  132. catalog,
  133. group,
  134. nil,
  135. true,
  136. )
  137. if err != nil {
  138. return nil, false, fmt.Errorf("initialize group configured Codex models: %w", err)
  139. }
  140. body, _, err = mergeConfiguredCodexModelsManifest(
  141. body,
  142. nil,
  143. group.ModelAllowlist.Models,
  144. group.ModelAllowlistEnabled(),
  145. )
  146. if err != nil {
  147. return nil, false, fmt.Errorf("build group configured Codex models: %w", err)
  148. }
  149. manifest := &OpenAIModelsResponse{
  150. Body: body,
  151. ETag: codexModelsManifestBodyETag(body),
  152. }
  153. if codexModelsManifestETagMatches(ifNoneMatch, manifest.ETag) {
  154. manifest.Body = nil
  155. manifest.NotModified = true
  156. }
  157. return manifest, true, nil
  158. }
  159. // MergeGroupConfiguredCodexModels adds account model aliases that are visible
  160. // to the authenticated OpenAI group without discarding metadata from upstream
  161. // Codex model entries. A group's custom models list also filters the picker,
  162. // matching the standard /v1/models display policy.
  163. func (s *OpenAIGatewayService) MergeGroupConfiguredCodexModels(
  164. ctx context.Context,
  165. group *Group,
  166. manifest *OpenAIModelsResponse,
  167. ifNoneMatch string,
  168. ) error {
  169. if s == nil || s.accountRepo == nil || group == nil || manifest == nil || manifest.NotModified {
  170. return nil
  171. }
  172. if group.Platform != PlatformOpenAI || len(manifest.Body) == 0 {
  173. return nil
  174. }
  175. var configuredModels []string
  176. if !group.CodexModelsManifestConfig.Enabled {
  177. var err error
  178. configuredModels, err = s.groupConfiguredCodexModelIDs(ctx, group)
  179. if err != nil {
  180. return fmt.Errorf("load group configured Codex models: %w", err)
  181. }
  182. }
  183. body, changed, err := mergeConfiguredCodexModelsManifest(
  184. manifest.Body,
  185. configuredModels,
  186. group.ModelAllowlist.Models,
  187. group.ModelAllowlistEnabled(),
  188. )
  189. if err != nil {
  190. return fmt.Errorf("merge group configured Codex models: %w", err)
  191. }
  192. if group.CodexModelsManifestConfig.Enabled && group.ModelAllowlistEnabled() {
  193. body, err = orderPinnedCodexModelsBySelection(body, group.ModelAllowlist)
  194. if err != nil {
  195. return fmt.Errorf("order pinned Codex models: %w", err)
  196. }
  197. changed = true
  198. }
  199. if changed {
  200. manifest.Body = body
  201. manifest.ETag = codexModelsManifestBodyETag(body)
  202. }
  203. if codexModelsManifestETagMatches(ifNoneMatch, manifest.ETag) {
  204. manifest.Body = nil
  205. manifest.NotModified = true
  206. }
  207. return nil
  208. }
  209. func (s *OpenAIGatewayService) groupConfiguredCodexModelIDs(ctx context.Context, group *Group) ([]string, error) {
  210. if group == nil {
  211. return nil, nil
  212. }
  213. accounts, err := s.accountRepo.ListSchedulableByGroupID(ctx, group.ID)
  214. if err != nil {
  215. return nil, err
  216. }
  217. return openAIConfiguredCodexModelIDsForGroup(accounts, group), nil
  218. }
  219. // loadCodexGroupCatalogAccounts separates picker membership from capability
  220. // intersection. visible accounts are currently schedulable and decide which
  221. // public aliases appear. catalog accounts are persistently enabled group
  222. // members; the availability query ignores transient rate-limit, overload, and
  223. // temporary-unschedulable state so those conditions cannot widen advertised
  224. // capabilities. Persistently disabled accounts are excluded because routing
  225. // cannot select them. If the availability query fails, the catalog falls back
  226. // to the schedulable set so a listing error does not fail the client request.
  227. func loadCodexGroupCatalogAccounts(ctx context.Context, repo AccountRepository, groupID int64) (visible []Account, catalog []Account, err error) {
  228. if repo == nil {
  229. return nil, nil, nil
  230. }
  231. visible, err = repo.ListSchedulableByGroupID(ctx, groupID)
  232. if err != nil {
  233. return nil, nil, err
  234. }
  235. catalog = visible
  236. groupAccounts, listErr := repo.ListModelAvailabilityCandidates(
  237. ctx,
  238. &groupID,
  239. []string{
  240. PlatformAnthropic,
  241. PlatformOpenAI,
  242. PlatformGemini,
  243. PlatformAntigravity,
  244. PlatformGrok,
  245. PlatformKimi,
  246. PlatformZhipu,
  247. PlatformDeepseek,
  248. PlatformMiniMax,
  249. },
  250. false,
  251. )
  252. if listErr != nil {
  253. return visible, catalog, nil
  254. }
  255. return visible, groupAccounts, nil
  256. }
  257. func openAIConfiguredCodexModelIDs(accounts []Account) []string {
  258. seen := make(map[string]struct{})
  259. models := make([]string, 0)
  260. for i := range accounts {
  261. account := &accounts[i]
  262. if account.Platform != PlatformOpenAI {
  263. continue
  264. }
  265. for modelID := range account.GetModelMapping() {
  266. modelID = strings.TrimSpace(modelID)
  267. if modelID == "" || strings.Contains(modelID, "*") {
  268. continue
  269. }
  270. if _, exists := seen[modelID]; exists {
  271. continue
  272. }
  273. seen[modelID] = struct{}{}
  274. models = append(models, modelID)
  275. }
  276. }
  277. sort.Strings(models)
  278. return models
  279. }
  280. func openAIConfiguredCodexModelIDsForGroup(accounts []Account, group *Group) []string {
  281. models := supplementUnmappedOpenAIModels(accounts, openAIConfiguredCodexModelIDs(accounts))
  282. if group == nil || !group.ModelAllowlistEnabled() {
  283. return models
  284. }
  285. seen := make(map[string]struct{}, len(models)+len(group.ModelAllowlist.Models))
  286. for _, modelID := range models {
  287. seen[modelID] = struct{}{}
  288. }
  289. for _, selectedModel := range group.ModelAllowlist.Models {
  290. selectedModel = strings.TrimSpace(selectedModel)
  291. if selectedModel == "" || strings.Contains(selectedModel, "*") {
  292. continue
  293. }
  294. for i := range accounts {
  295. account := &accounts[i]
  296. if account.Platform != PlatformOpenAI {
  297. continue
  298. }
  299. mappedModel, matched := account.ResolveMappedModel(selectedModel)
  300. if !matched || strings.TrimSpace(mappedModel) == "" {
  301. continue
  302. }
  303. if _, exists := seen[selectedModel]; !exists {
  304. seen[selectedModel] = struct{}{}
  305. models = append(models, selectedModel)
  306. }
  307. break
  308. }
  309. }
  310. sort.Strings(models)
  311. return models
  312. }
  313. const (
  314. configuredCodexModelPriority = 50
  315. configuredCodexCustomDescription = "Custom model routed through Sub2API."
  316. configuredCodexFallbackContext = 272_000
  317. configuredCodexDeepSeekV4Context = 1_000_000
  318. configuredCodexGrokContext = 500_000
  319. configuredCodexGrokBuildContext = 256_000
  320. configuredCodexGPT56MaxContext = 872_000
  321. configuredCodexGPT6AstraContext = 1_050_000
  322. configuredCodexToolOutputMaxTokens = 10_000
  323. )
  324. type configuredCodexReasoningLevel struct {
  325. Effort string `json:"effort"`
  326. Description string `json:"description"`
  327. }
  328. type configuredCodexTruncationPolicy struct {
  329. Mode string `json:"mode"`
  330. Limit int64 `json:"limit"`
  331. }
  332. type configuredCodexServiceTier struct {
  333. ID string `json:"id"`
  334. Name string `json:"name"`
  335. Description string `json:"description"`
  336. }
  337. type configuredCodexModelMessages struct {
  338. InstructionsTemplate string `json:"instructions_template"`
  339. InstructionsVariables any `json:"instructions_variables"`
  340. Approvals any `json:"approvals"`
  341. CollaborationModes any `json:"collaboration_modes"`
  342. AutoReview any `json:"auto_review"`
  343. Permissions any `json:"permissions"`
  344. MultiAgent any `json:"multi_agent"`
  345. TokenBudget any `json:"token_budget"`
  346. GuardianV2 any `json:"guardian_v2"`
  347. }
  348. // configuredCodexModelDescriptor is the minimum complete ModelInfo contract
  349. // understood by current Codex clients. Several nullable fields are intentionally
  350. // emitted: unlike ordinary OpenAI /v1/models entries, the Codex manifest parser
  351. // requires them to be present.
  352. type configuredCodexModelDescriptor struct {
  353. Slug string `json:"slug"`
  354. DisplayName string `json:"display_name"`
  355. Description string `json:"description"`
  356. DefaultReasoningLevel *string `json:"default_reasoning_level,omitempty"`
  357. SupportedReasoningLevels []configuredCodexReasoningLevel `json:"supported_reasoning_levels"`
  358. MultiAgentReasoningEffort *string `json:"multi_agent_reasoning_effort,omitempty"`
  359. ShellType string `json:"shell_type"`
  360. Visibility string `json:"visibility"`
  361. SupportedInAPI bool `json:"supported_in_api"`
  362. Priority int `json:"priority"`
  363. AdditionalSpeedTiers []string `json:"additional_speed_tiers"`
  364. ServiceTiers []configuredCodexServiceTier `json:"service_tiers"`
  365. DefaultServiceTier any `json:"default_service_tier"`
  366. AvailabilityNUX any `json:"availability_nux"`
  367. Upgrade any `json:"upgrade"`
  368. ModelMessages configuredCodexModelMessages `json:"model_messages"`
  369. IncludeSkillsUsageInstructions bool `json:"include_skills_usage_instructions"`
  370. IncludePluginUsageInstructions bool `json:"include_plugin_usage_instructions"`
  371. IncludeAppsUsageInstructions bool `json:"include_apps_usage_instructions"`
  372. SupportsReasoningSummaryParameter bool `json:"supports_reasoning_summary_parameter"`
  373. DefaultReasoningSummary string `json:"default_reasoning_summary"`
  374. SupportVerbosity bool `json:"support_verbosity"`
  375. DefaultVerbosity *string `json:"default_verbosity"`
  376. ApplyPatchToolType *string `json:"apply_patch_tool_type"`
  377. WebSearchToolType string `json:"web_search_tool_type"`
  378. TruncationPolicy configuredCodexTruncationPolicy `json:"truncation_policy"`
  379. SupportsImageDetailOriginal bool `json:"supports_image_detail_original"`
  380. SupportsParallelToolCalls bool `json:"supports_parallel_tool_calls"`
  381. ContextWindow int64 `json:"context_window"`
  382. MaxContextWindow int64 `json:"max_context_window"`
  383. AutoCompactTokenLimit any `json:"auto_compact_token_limit"`
  384. CompHash any `json:"comp_hash"`
  385. EffectiveContextWindowPercent int64 `json:"effective_context_window_percent"`
  386. ExperimentalSupportedTools []string `json:"experimental_supported_tools"`
  387. InputModalities []string `json:"input_modalities"`
  388. SupportsSearchTool bool `json:"supports_search_tool"`
  389. UseResponsesLite bool `json:"use_responses_lite"`
  390. NodeREPLAutoReviewRequired bool `json:"node_repl_auto_review_required"`
  391. NodeREPLDisabled bool `json:"node_repl_disabled"`
  392. AutoReviewModelOverride any `json:"auto_review_model_override"`
  393. ModelSpecialty any `json:"model_specialty"`
  394. ToolMode any `json:"tool_mode"`
  395. MultiAgentVersion any `json:"multi_agent_version"`
  396. }
  397. type codexModelMetadataOverride struct {
  398. UpstreamModelMetadata
  399. reasoningConflict bool
  400. inputModalitiesConflict bool
  401. }
  402. func newConfiguredCodexModelDescriptor(modelID string) configuredCodexModelDescriptor {
  403. modelID = strings.TrimSpace(modelID)
  404. noReasoningLevel := "none"
  405. descriptor := configuredCodexModelDescriptor{
  406. Slug: modelID,
  407. DisplayName: modelID,
  408. Description: configuredCodexCustomDescription,
  409. DefaultReasoningLevel: &noReasoningLevel,
  410. SupportedReasoningLevels: []configuredCodexReasoningLevel{
  411. {Effort: "none", Description: configuredCodexReasoningLevelDescription("none")},
  412. },
  413. ShellType: "unified_exec",
  414. Visibility: "list",
  415. SupportedInAPI: true,
  416. Priority: configuredCodexModelPriority,
  417. AdditionalSpeedTiers: []string{},
  418. ServiceTiers: []configuredCodexServiceTier{},
  419. ModelMessages: configuredCodexModelMessages{InstructionsTemplate: openai.CodexBaseInstructionsForModel(modelID)},
  420. SupportsReasoningSummaryParameter: true,
  421. DefaultReasoningSummary: "auto",
  422. WebSearchToolType: "text",
  423. TruncationPolicy: configuredCodexTruncationPolicy{Mode: "bytes", Limit: configuredCodexToolOutputMaxTokens},
  424. ContextWindow: configuredCodexFallbackContext,
  425. MaxContextWindow: configuredCodexFallbackContext,
  426. EffectiveContextWindowPercent: 95,
  427. ExperimentalSupportedTools: []string{},
  428. InputModalities: []string{"text"},
  429. }
  430. if isDeepSeekCodexModel(modelID) {
  431. defaultReasoningLevel := "high"
  432. descriptor.DisplayName = deepSeekCodexDisplayName(modelID)
  433. descriptor.Description = "DeepSeek coding and reasoning model routed through Sub2API."
  434. descriptor.DefaultReasoningLevel = &defaultReasoningLevel
  435. descriptor.SupportedReasoningLevels = []configuredCodexReasoningLevel{
  436. {Effort: "low", Description: "Fast responses with lighter reasoning"},
  437. {Effort: "high", Description: "Greater reasoning depth for coding and agent tasks"},
  438. {Effort: "max", Description: "Maximum reasoning depth for complex tasks"},
  439. }
  440. descriptor.SupportsParallelToolCalls = true
  441. descriptor.ContextWindow = configuredCodexDeepSeekV4Context
  442. descriptor.MaxContextWindow = configuredCodexDeepSeekV4Context
  443. }
  444. if isGrokCodexModel(modelID) {
  445. descriptor.DisplayName = grokCodexDisplayName(modelID)
  446. descriptor.Description = "Grok coding and reasoning model routed through Sub2API."
  447. descriptor.SupportsParallelToolCalls = true
  448. descriptor.ContextWindow = grokCodexContextWindow(modelID)
  449. descriptor.MaxContextWindow = descriptor.ContextWindow
  450. if grokCodexSupportsReasoningEffort(modelID) {
  451. defaultReasoningLevel := "high"
  452. descriptor.DefaultReasoningLevel = &defaultReasoningLevel
  453. descriptor.SupportedReasoningLevels = configuredCodexGrokReasoningLevels(modelID)
  454. }
  455. }
  456. if isClaudeCodexModel(modelID) {
  457. descriptor.DisplayName = claudeCodexDisplayName(modelID)
  458. descriptor.Description = "Claude coding and reasoning model routed through Sub2API."
  459. descriptor.SupportsParallelToolCalls = true
  460. if levels := configuredCodexClaudeReasoningLevels(modelID); len(levels) > 0 {
  461. defaultReasoningLevel := claudeCodexDefaultReasoningLevel(levels)
  462. descriptor.DefaultReasoningLevel = &defaultReasoningLevel
  463. descriptor.SupportedReasoningLevels = levels
  464. }
  465. }
  466. if isOpenAICodexGPTModel(modelID) {
  467. descriptor.DisplayName = openaiCodexDisplayName(modelID)
  468. descriptor.Description = "OpenAI GPT coding model routed through Sub2API."
  469. descriptor.SupportsParallelToolCalls = true
  470. descriptor.ServiceTiers = configuredCodexServiceTiersForModel(modelID)
  471. if isOpenAICodexReasoningGPTModel(modelID) {
  472. defaultReasoningLevel := "medium"
  473. if getNormalizedCodexModel(modelID) == "gpt-5.6-sol" {
  474. defaultReasoningLevel = "low"
  475. }
  476. descriptor.DefaultReasoningLevel = &defaultReasoningLevel
  477. descriptor.SupportedReasoningLevels = configuredCodexGPTReasoningLevels(modelID)
  478. descriptor.DefaultReasoningSummary = "none"
  479. descriptor.TruncationPolicy = configuredCodexTruncationPolicy{Mode: "tokens", Limit: configuredCodexToolOutputMaxTokens}
  480. if isOpenAIGPT56Model(modelID) {
  481. descriptor.MaxContextWindow = configuredCodexGPT56MaxContext
  482. }
  483. if isOpenAIGPT6AstraModel(modelID) {
  484. // Codex resolves the Ultra workflow to this effort before inference.
  485. // openai/codex a9896da3: codex-rs/models-manager/models.json.
  486. multiAgentEffort := "xhigh"
  487. descriptor.MultiAgentReasoningEffort = &multiAgentEffort
  488. descriptor.MultiAgentVersion = "v2"
  489. descriptor.ContextWindow = configuredCodexGPT6AstraContext
  490. descriptor.MaxContextWindow = configuredCodexGPT6AstraContext
  491. }
  492. }
  493. if SupportsVerbosity(modelID) {
  494. defaultVerbosity := "low"
  495. descriptor.SupportVerbosity = true
  496. descriptor.DefaultVerbosity = &defaultVerbosity
  497. }
  498. }
  499. return descriptor
  500. }
  501. func configuredCodexServiceTiersForModel(modelID string) []configuredCodexServiceTier {
  502. tiers := make([]configuredCodexServiceTier, 0, 2)
  503. if configuredCodexSupportsPriorityServiceTier(modelID) {
  504. tiers = append(tiers, configuredCodexServiceTier{
  505. ID: OpenAIFastTierPriority,
  506. Name: "Fast",
  507. Description: "Priority processing for lower latency.",
  508. })
  509. }
  510. if configuredCodexSupportsUltrafastServiceTier(modelID) {
  511. tiers = append(tiers, configuredCodexServiceTier{
  512. ID: OpenAIFastTierUltrafast,
  513. Name: "Ultrafast",
  514. Description: "Ultra-low latency processing.",
  515. })
  516. }
  517. return tiers
  518. }
  519. func configuredCodexSupportsPriorityServiceTier(modelID string) bool {
  520. normalized := canonicalizeOpenAIModelAliasSpelling(modelID)
  521. for _, family := range []string{"gpt-5.4", "gpt-5.5", "gpt-5.6"} {
  522. if normalized == family || strings.HasPrefix(normalized, family+"-") {
  523. return true
  524. }
  525. }
  526. // GPT-6 Astra advertises Fast via service_tier=priority in public model metadata.
  527. return isOpenAIGPT6AstraModel(modelID)
  528. }
  529. func configuredCodexSupportsUltrafastServiceTier(modelID string) bool {
  530. return normalizeKnownOpenAICodexModel(modelID) == "gpt-5.6-sol"
  531. }
  532. func configuredCodexGrokReasoningLevels(modelID string) []configuredCodexReasoningLevel {
  533. levels := []configuredCodexReasoningLevel{
  534. {Effort: "low", Description: "Fast responses with lighter reasoning"},
  535. {Effort: "medium", Description: "Balanced reasoning for most coding tasks"},
  536. {Effort: "high", Description: "Greater reasoning depth for coding and agent tasks"},
  537. }
  538. if GrokSupportsXHighReasoningEffort(modelID) {
  539. levels = append(levels, configuredCodexReasoningLevel{
  540. Effort: "xhigh",
  541. Description: "Extra-high reasoning depth for difficult tasks",
  542. })
  543. }
  544. return levels
  545. }
  546. func configuredCodexClaudeReasoningLevels(modelID string) []configuredCodexReasoningLevel {
  547. descriptions := map[string]string{
  548. "low": "Fast responses with lighter reasoning",
  549. "medium": "Balanced reasoning for most coding tasks",
  550. "high": "Greater reasoning depth for coding and agent tasks",
  551. "xhigh": "Extra-high reasoning depth for difficult tasks",
  552. "max": "Maximum reasoning depth for complex tasks",
  553. }
  554. levels := claude.EffortLevelsForModel(modelID)
  555. out := make([]configuredCodexReasoningLevel, 0, len(levels))
  556. for _, effort := range levels {
  557. out = append(out, configuredCodexReasoningLevel{
  558. Effort: effort,
  559. Description: descriptions[effort],
  560. })
  561. }
  562. return out
  563. }
  564. func claudeCodexDefaultReasoningLevel(levels []configuredCodexReasoningLevel) string {
  565. for _, preferred := range []string{"medium", "high", "low"} {
  566. for _, level := range levels {
  567. if level.Effort == preferred {
  568. return preferred
  569. }
  570. }
  571. }
  572. if len(levels) == 0 {
  573. return ""
  574. }
  575. return levels[0].Effort
  576. }
  577. func configuredCodexGPTReasoningLevels(modelID string) []configuredCodexReasoningLevel {
  578. levels := []configuredCodexReasoningLevel{
  579. {Effort: "low", Description: "Fast responses with lighter reasoning"},
  580. {Effort: "medium", Description: "Balanced reasoning for most coding tasks"},
  581. {Effort: "high", Description: "Greater reasoning depth for coding and agent tasks"},
  582. {Effort: "xhigh", Description: "Extra-high reasoning depth for difficult tasks"},
  583. }
  584. normalized := getNormalizedCodexModel(modelID)
  585. if isOpenAIGPT56Model(modelID) || isOpenAIGPT6AstraModel(modelID) {
  586. levels = append(levels, configuredCodexReasoningLevel{
  587. Effort: "max",
  588. Description: "Maximum reasoning depth for complex tasks",
  589. })
  590. }
  591. if isOpenAIGPT6AstraModel(modelID) || normalized == "gpt-5.6-sol" || normalized == "gpt-5.6-terra" {
  592. levels = append(levels, configuredCodexReasoningLevel{
  593. Effort: "ultra",
  594. Description: "Maximum reasoning with automatic task delegation",
  595. })
  596. }
  597. return levels
  598. }
  599. func isOpenAICodexGPTModel(modelID string) bool {
  600. normalized := canonicalizeOpenAIModelAliasSpelling(modelID)
  601. if normalized == "" || strings.HasPrefix(normalized, "gpt-image") {
  602. return false
  603. }
  604. return strings.HasPrefix(normalized, "gpt-")
  605. }
  606. func isOpenAICodexReasoningGPTModel(modelID string) bool {
  607. normalized := canonicalizeOpenAIModelAliasSpelling(modelID)
  608. return isOpenAIGPT6AstraModel(normalized) || strings.HasPrefix(normalized, "gpt-5")
  609. }
  610. func isOpenAICodexImageInputModel(modelID string) bool {
  611. normalized := canonicalizeOpenAIModelAliasSpelling(modelID)
  612. return isOpenAIGPT6AstraModel(normalized) ||
  613. strings.HasPrefix(normalized, "gpt-5") ||
  614. strings.HasPrefix(normalized, "gpt-4o") ||
  615. strings.HasPrefix(normalized, "gpt-4.1") ||
  616. strings.HasPrefix(normalized, "gpt-4.5") ||
  617. strings.HasPrefix(normalized, "gpt-4-turbo") ||
  618. strings.HasPrefix(normalized, "gpt-4-vision")
  619. }
  620. func isOfficialOpenAICodexCatalogModel(modelID string) bool {
  621. normalized := strings.ToLower(codexProviderQualifiedModelID(modelID))
  622. if normalized == "" || isCodexDedicatedMediaModel(normalized) {
  623. return false
  624. }
  625. if strings.HasPrefix(normalized, "codex-") {
  626. return true
  627. }
  628. if strings.HasPrefix(normalized, "o1") || strings.HasPrefix(normalized, "o3") || strings.HasPrefix(normalized, "o4") {
  629. return true
  630. }
  631. if !strings.HasPrefix(normalized, "gpt-") {
  632. return false
  633. }
  634. for _, incompatibleFamily := range []string{"audio", "realtime", "transcribe", "tts"} {
  635. if strings.Contains(normalized, incompatibleFamily) {
  636. return false
  637. }
  638. }
  639. return true
  640. }
  641. func openaiCodexDisplayName(modelID string) string {
  642. normalized := canonicalizeOpenAIModelAliasSpelling(modelID)
  643. if normalized == "" {
  644. return modelID
  645. }
  646. for _, model := range openai.DefaultModels {
  647. if strings.EqualFold(model.ID, normalized) && strings.TrimSpace(model.DisplayName) != "" {
  648. return model.DisplayName
  649. }
  650. }
  651. return modelID
  652. }
  653. func deepSeekCodexDisplayName(modelID string) string {
  654. switch strings.ToLower(strings.TrimSpace(modelID)) {
  655. case "deepseek-v4-pro", "deepseek-4-pro":
  656. return "DeepSeek V4 Pro"
  657. case "deepseek-v4-flash", "deepseek-4-flash":
  658. return "DeepSeek V4 Flash"
  659. default:
  660. return modelID
  661. }
  662. }
  663. func isDeepSeekCodexModel(modelID string) bool {
  664. return strings.HasPrefix(strings.ToLower(strings.TrimSpace(modelID)), "deepseek-")
  665. }
  666. func isGrokCodexModel(modelID string) bool {
  667. return xai.IsGrokModelID(modelID)
  668. }
  669. func grokCodexSupportsReasoningEffort(modelID string) bool {
  670. if grokSupportsReasoningEffort(modelID) {
  671. return true
  672. }
  673. canonical := xai.ResolveGrokTextResponsesModelID(modelID)
  674. if canonical == "" || strings.EqualFold(canonical, modelID) {
  675. return false
  676. }
  677. return grokSupportsReasoningEffort(canonical)
  678. }
  679. func grokCodexDisplayName(modelID string) string {
  680. normalized := strings.ToLower(xai.StripGrokProviderPrefix(strings.TrimSpace(modelID)))
  681. if normalized == "" {
  682. return modelID
  683. }
  684. if name := grokDefaultDisplayName(normalized); name != "" {
  685. return name
  686. }
  687. canonical := strings.ToLower(xai.ResolveGrokTextResponsesModelID(normalized))
  688. if canonical != "" && canonical != normalized {
  689. if name := grokDefaultDisplayName(canonical); name != "" {
  690. return name
  691. }
  692. }
  693. return modelID
  694. }
  695. func grokDefaultDisplayName(modelID string) string {
  696. for _, model := range xai.DefaultModels() {
  697. if model.ID == modelID {
  698. return strings.TrimSpace(model.DisplayName)
  699. }
  700. }
  701. return ""
  702. }
  703. func grokCodexContextWindow(modelID string) int64 {
  704. normalized := strings.ToLower(xai.StripGrokProviderPrefix(strings.TrimSpace(modelID)))
  705. if strings.HasPrefix(normalized, "grok-build") {
  706. return configuredCodexGrokBuildContext
  707. }
  708. return configuredCodexGrokContext
  709. }
  710. func isClaudeCodexModel(modelID string) bool {
  711. platform, detected := DetectModelPlatform(modelID)
  712. return detected && platform == PlatformAnthropic
  713. }
  714. func claudeCodexDisplayName(modelID string) string {
  715. normalized := strings.ToLower(codexProviderQualifiedModelID(modelID))
  716. normalized = strings.TrimPrefix(normalized, "anthropic.")
  717. if normalized == "" {
  718. return modelID
  719. }
  720. for _, model := range claude.DefaultModels {
  721. if strings.EqualFold(model.ID, normalized) && strings.TrimSpace(model.DisplayName) != "" {
  722. return model.DisplayName
  723. }
  724. }
  725. if canonical, ok := claude.ModelIDOverrides[normalized]; ok {
  726. for _, model := range claude.DefaultModels {
  727. if model.ID == canonical && strings.TrimSpace(model.DisplayName) != "" {
  728. return model.DisplayName
  729. }
  730. }
  731. }
  732. return modelID
  733. }
  734. // BuildCodexModelsManifest builds a standalone Codex model catalog for models
  735. // routed through a custom provider. The response is also suitable for saving
  736. // as model_catalog_json in clients that do not refresh custom-provider catalogs.
  737. func BuildCodexModelsManifest(modelIDs []string) ([]byte, error) {
  738. return buildCodexModelsManifest(modelIDs, nil, nil, nil, nil)
  739. }
  740. // BuildCodexModelsManifestForGroup derives input capabilities from the
  741. // concrete Responses route and group accounts behind a group. Unknown or mixed
  742. // capabilities fail closed to the text-only descriptor used by the standalone
  743. // builder. Caller-supplied model IDs still decide which slugs appear; advertised
  744. // capabilities intersect all active group members that map the alias, including
  745. // accounts that are not currently schedulable.
  746. func (s *GatewayService) BuildCodexModelsManifestForGroup(
  747. ctx context.Context,
  748. group *Group,
  749. platformOverride string,
  750. modelIDs []string,
  751. ) ([]byte, error) {
  752. if s == nil || s.accountRepo == nil || group == nil {
  753. return BuildCodexModelsManifest(modelIDs)
  754. }
  755. effectivePlatform := strings.TrimSpace(platformOverride)
  756. if effectivePlatform == "" {
  757. effectivePlatform = group.Platform
  758. }
  759. if effectivePlatform != PlatformComposite && !isConcreteRequestPlatform(effectivePlatform) {
  760. return BuildCodexModelsManifest(modelIDs)
  761. }
  762. _, catalog, err := loadCodexGroupCatalogAccounts(ctx, s.accountRepo, group.ID)
  763. if err != nil {
  764. return BuildCodexModelsManifest(modelIDs)
  765. }
  766. var compositeRoutes []CompositeModelRoute
  767. compositeRoutesAvailable := true
  768. if effectivePlatform == PlatformComposite && s.compositeResolver != nil && s.compositeResolver.repo != nil {
  769. compositeRoutes, err = s.compositeResolver.repo.ListByGroup(ctx, group.ID, false)
  770. if err != nil {
  771. compositeRoutesAvailable = false
  772. }
  773. }
  774. return buildCodexModelsManifestForAccounts(
  775. effectivePlatform,
  776. modelIDs,
  777. catalog,
  778. group,
  779. compositeRoutes,
  780. compositeRoutesAvailable,
  781. )
  782. }
  783. func buildCodexModelsManifestForAccounts(
  784. effectivePlatform string,
  785. modelIDs []string,
  786. accounts []Account,
  787. group *Group,
  788. compositeRoutes []CompositeModelRoute,
  789. compositeRoutesAvailable bool,
  790. ) ([]byte, error) {
  791. imageInputModels := make(map[string]bool, len(modelIDs))
  792. searchToolModels := make(map[string]bool, len(modelIDs))
  793. metadataModels := codexCatalogMetadataModels(
  794. effectivePlatform,
  795. modelIDs,
  796. accounts,
  797. compositeRoutes,
  798. compositeRoutesAvailable,
  799. )
  800. modelMetadata := make(map[string]codexModelMetadataOverride, len(modelIDs))
  801. for _, modelID := range modelIDs {
  802. modelID = strings.TrimSpace(modelID)
  803. if groupCodexModelSupportsImageInput(
  804. effectivePlatform,
  805. modelID,
  806. accounts,
  807. compositeRoutes,
  808. compositeRoutesAvailable,
  809. ) {
  810. imageInputModels[modelID] = true
  811. }
  812. if groupCodexModelSupportsSearchTool(
  813. effectivePlatform,
  814. modelID,
  815. accounts,
  816. compositeRoutes,
  817. compositeRoutesAvailable,
  818. ) {
  819. searchToolModels[modelID] = true
  820. }
  821. if metadata, ok := groupCodexModelMetadata(
  822. effectivePlatform,
  823. modelID,
  824. accounts,
  825. group,
  826. compositeRoutes,
  827. compositeRoutesAvailable,
  828. ); ok {
  829. modelMetadata[modelID] = metadata
  830. }
  831. }
  832. return buildCodexModelsManifest(modelIDs, imageInputModels, searchToolModels, metadataModels, modelMetadata)
  833. }
  834. func buildCodexModelsManifest(
  835. modelIDs []string,
  836. imageInputModels map[string]bool,
  837. searchToolModels map[string]bool,
  838. metadataModels map[string]string,
  839. modelMetadata map[string]codexModelMetadataOverride,
  840. ) ([]byte, error) {
  841. seen := make(map[string]struct{}, len(modelIDs))
  842. models := make([]json.RawMessage, 0, len(modelIDs))
  843. for _, modelID := range modelIDs {
  844. modelID = strings.TrimSpace(modelID)
  845. if modelID == "" {
  846. continue
  847. }
  848. if _, exists := seen[modelID]; exists {
  849. continue
  850. }
  851. metadataModelID := strings.TrimSpace(metadataModels[modelID])
  852. if metadataModelID == "" {
  853. metadataModelID = modelID
  854. }
  855. if isCodexDedicatedMediaModel(modelID) || isCodexDedicatedMediaModel(metadataModelID) {
  856. continue
  857. }
  858. seen[modelID] = struct{}{}
  859. descriptor := newConfiguredCodexModelDescriptor(metadataModelID)
  860. descriptor.Slug = modelID
  861. descriptor.SupportsSearchTool = searchToolModels[modelID]
  862. if metadata, ok := modelMetadata[modelID]; ok {
  863. applyUpstreamModelMetadataToCodexDescriptor(&descriptor, metadata)
  864. }
  865. if imageInputModels[modelID] {
  866. // Apply the capability-derived modality after upstream metadata so
  867. // a stale official Astra snapshot cannot downgrade the catalog.
  868. descriptor.InputModalities = []string{"text", "image"}
  869. }
  870. if metadataModelID != modelID {
  871. descriptor.DisplayName = modelID
  872. descriptor.Description = configuredCodexCustomDescription
  873. }
  874. encoded, err := json.Marshal(descriptor)
  875. if err != nil {
  876. return nil, err
  877. }
  878. if capabilities := modelMetadata[modelID].CodexToolCapabilities; len(capabilities) > 0 {
  879. var fields map[string]json.RawMessage
  880. if err := json.Unmarshal(encoded, &fields); err != nil {
  881. return nil, err
  882. }
  883. applyCodexToolCapabilities(fields, capabilities, true)
  884. encoded, err = json.Marshal(fields)
  885. if err != nil {
  886. return nil, err
  887. }
  888. }
  889. models = append(models, encoded)
  890. }
  891. return json.Marshal(struct {
  892. Models []json.RawMessage `json:"models"`
  893. }{Models: models})
  894. }
  895. func codexCatalogMetadataModels(
  896. platform string,
  897. modelIDs []string,
  898. accounts []Account,
  899. compositeRoutes []CompositeModelRoute,
  900. compositeRoutesAvailable bool,
  901. ) map[string]string {
  902. metadataModels := make(map[string]string, len(modelIDs))
  903. for _, modelID := range modelIDs {
  904. modelID = strings.TrimSpace(modelID)
  905. if modelID == "" {
  906. continue
  907. }
  908. metadataModelID := resolveCodexCatalogMetadataModel(
  909. platform,
  910. modelID,
  911. accounts,
  912. compositeRoutes,
  913. compositeRoutesAvailable,
  914. )
  915. if metadataModelID != "" && metadataModelID != modelID {
  916. metadataModels[modelID] = metadataModelID
  917. }
  918. }
  919. return metadataModels
  920. }
  921. func resolveCodexCatalogMetadataModel(
  922. platform string,
  923. modelID string,
  924. accounts []Account,
  925. compositeRoutes []CompositeModelRoute,
  926. compositeRoutesAvailable bool,
  927. ) string {
  928. modelID = strings.TrimSpace(modelID)
  929. if modelID == "" {
  930. return ""
  931. }
  932. if platform == PlatformComposite {
  933. if !compositeRoutesAvailable {
  934. return modelID
  935. }
  936. if route, matched := matchCompositeRoute(compositeRoutes, modelID, CompositeRouteEndpointResponses); matched {
  937. if upstreamModel := strings.TrimSpace(route.UpstreamModel); upstreamModel != "" {
  938. return upstreamModel
  939. }
  940. return modelID
  941. }
  942. if codexCompositeRouteMatchesModel(compositeRoutes, modelID) {
  943. return modelID
  944. }
  945. claimedPlatforms := make(map[string]struct{})
  946. for _, account := range accounts {
  947. accountPlatform := strings.TrimSpace(account.Platform)
  948. if !isConcreteRequestPlatform(accountPlatform) || !codexExplicitModelMappingClaims(account, modelID) {
  949. continue
  950. }
  951. claimedPlatforms[accountPlatform] = struct{}{}
  952. }
  953. if len(claimedPlatforms) > 1 {
  954. return modelID
  955. }
  956. for accountPlatform := range claimedPlatforms {
  957. return uniqueCodexMappedModel(accounts, accountPlatform, modelID)
  958. }
  959. detectedPlatform, detected := DetectModelPlatform(modelID)
  960. if !detected {
  961. return modelID
  962. }
  963. platform = detectedPlatform
  964. }
  965. return uniqueCodexMappedModel(accounts, platform, modelID)
  966. }
  967. func uniqueCodexMappedModel(accounts []Account, platform string, modelID string) string {
  968. targets := make(map[string]struct{})
  969. for i := range accounts {
  970. account := &accounts[i]
  971. if account.Platform != platform {
  972. continue
  973. }
  974. mappedModel, matched := account.ResolveMappedModel(modelID)
  975. mappedModel = strings.TrimSpace(mappedModel)
  976. if !matched || mappedModel == "" {
  977. continue
  978. }
  979. targets[mappedModel] = struct{}{}
  980. }
  981. if len(targets) != 1 {
  982. return modelID
  983. }
  984. for target := range targets {
  985. return target
  986. }
  987. return modelID
  988. }
  989. func groupCodexModelSupportsImageInput(
  990. platform string,
  991. modelID string,
  992. accounts []Account,
  993. compositeRoutes []CompositeModelRoute,
  994. compositeRoutesAvailable bool,
  995. ) bool {
  996. modelID = strings.TrimSpace(modelID)
  997. if modelID == "" {
  998. return false
  999. }
  1000. upstreamModel := modelID
  1001. if platform == PlatformComposite {
  1002. var resolved bool
  1003. platform, upstreamModel, resolved = resolveCodexCompositeModelTarget(
  1004. modelID,
  1005. accounts,
  1006. compositeRoutes,
  1007. compositeRoutesAvailable,
  1008. )
  1009. if !resolved {
  1010. return false
  1011. }
  1012. }
  1013. if platform != PlatformOpenAI && platform != PlatformGrok {
  1014. return false
  1015. }
  1016. candidates := 0
  1017. for i := range accounts {
  1018. account := &accounts[i]
  1019. if account.Platform != platform || !account.IsModelSupported(upstreamModel) {
  1020. continue
  1021. }
  1022. candidates++
  1023. if !accountCodexModelSupportsImageInput(account, account.GetMappedModel(upstreamModel)) {
  1024. return false
  1025. }
  1026. }
  1027. return candidates > 0
  1028. }
  1029. // groupCodexModelSupportsSearchTool advertises client-side tool discovery only
  1030. // when every account that may serve the model uses the gateway's Responses to
  1031. // Chat Completions bridge. Native Responses routes must declare the capability
  1032. // in their upstream Codex manifest instead of having it inferred here.
  1033. func groupCodexModelSupportsSearchTool(
  1034. platform string,
  1035. modelID string,
  1036. accounts []Account,
  1037. compositeRoutes []CompositeModelRoute,
  1038. compositeRoutesAvailable bool,
  1039. ) bool {
  1040. modelID = strings.TrimSpace(modelID)
  1041. if modelID == "" {
  1042. return false
  1043. }
  1044. upstreamModel := modelID
  1045. if platform == PlatformComposite {
  1046. var resolved bool
  1047. platform, upstreamModel, resolved = resolveCodexCompositeModelTarget(
  1048. modelID,
  1049. accounts,
  1050. compositeRoutes,
  1051. compositeRoutesAvailable,
  1052. )
  1053. if !resolved {
  1054. return false
  1055. }
  1056. }
  1057. if platform != PlatformOpenAI {
  1058. return false
  1059. }
  1060. candidates := 0
  1061. for i := range accounts {
  1062. account := &accounts[i]
  1063. if account.Platform != platform || !account.IsModelSupported(upstreamModel) {
  1064. continue
  1065. }
  1066. candidates++
  1067. if !shouldForwardOpenAIResponsesViaRawChatCompletions(account) {
  1068. return false
  1069. }
  1070. }
  1071. return candidates > 0
  1072. }
  1073. func resolveCodexCompositeModelTarget(
  1074. modelID string,
  1075. accounts []Account,
  1076. routes []CompositeModelRoute,
  1077. routesAvailable bool,
  1078. ) (string, string, bool) {
  1079. if !routesAvailable {
  1080. return "", "", false
  1081. }
  1082. if route, matched := matchCompositeRoute(routes, modelID, CompositeRouteEndpointResponses); matched {
  1083. upstreamModel := strings.TrimSpace(route.UpstreamModel)
  1084. if upstreamModel == "" {
  1085. upstreamModel = modelID
  1086. }
  1087. return route.TargetPlatform, upstreamModel, true
  1088. }
  1089. if codexCompositeRouteMatchesModel(routes, modelID) {
  1090. return "", "", false
  1091. }
  1092. claimedPlatforms := make(map[string]struct{})
  1093. for _, account := range accounts {
  1094. platform := strings.TrimSpace(account.Platform)
  1095. if !isConcreteRequestPlatform(platform) || !codexExplicitModelMappingClaims(account, modelID) {
  1096. continue
  1097. }
  1098. claimedPlatforms[platform] = struct{}{}
  1099. }
  1100. if len(claimedPlatforms) > 1 {
  1101. return "", "", false
  1102. }
  1103. for platform := range claimedPlatforms {
  1104. return platform, modelID, true
  1105. }
  1106. platform, detected := DetectModelPlatform(modelID)
  1107. if !detected {
  1108. return "", "", false
  1109. }
  1110. return platform, modelID, true
  1111. }
  1112. func codexCompositeRouteMatchesModel(routes []CompositeModelRoute, modelID string) bool {
  1113. for _, route := range routes {
  1114. publicModel := strings.TrimSpace(route.PublicModel)
  1115. if publicModel == "" {
  1116. continue
  1117. }
  1118. switch normalizeCompositeRouteMatchType(route.MatchType) {
  1119. case CompositeRouteMatchPrefix:
  1120. if strings.HasPrefix(modelID, publicModel) {
  1121. return true
  1122. }
  1123. default:
  1124. if modelID == publicModel {
  1125. return true
  1126. }
  1127. }
  1128. }
  1129. return false
  1130. }
  1131. func codexExplicitModelMappingClaims(account Account, modelID string) bool {
  1132. if account.Credentials == nil || strings.TrimSpace(modelID) == "" {
  1133. return false
  1134. }
  1135. mapped := strings.TrimSpace(account.GetModelMapping()[modelID])
  1136. return mapped != ""
  1137. }
  1138. func accountCodexModelSupportsImageInput(account *Account, upstreamModel string) bool {
  1139. if account == nil {
  1140. return false
  1141. }
  1142. switch account.Platform {
  1143. case PlatformOpenAI:
  1144. if metadata, ok := account.GetUpstreamModelMetadata(upstreamModel); ok {
  1145. if modalities := normalizeCodexInputModalities(metadata.InputModalities); len(modalities) > 0 {
  1146. // Official GPT-6 Astra metadata briefly shipped with a stale
  1147. // text-only modality list. Keep explicit provider metadata
  1148. // authoritative for compatible hosts, but repair that stale
  1149. // official snapshot at the capability boundary.
  1150. if isOpenAIGPT6AstraModel(upstreamModel) && isOfficialOpenAICodexAccount(account) {
  1151. return true
  1152. }
  1153. return stringSliceContains(modalities, "image")
  1154. }
  1155. }
  1156. if !isOpenAICodexImageInputModel(upstreamModel) {
  1157. return false
  1158. }
  1159. if account.IsOpenAIOAuth() {
  1160. return true
  1161. }
  1162. if !account.IsOpenAIApiKey() {
  1163. return false
  1164. }
  1165. // Compatible model lists often omit modalities. Preserve the known GPT
  1166. // fallback unless a synced snapshot above explicitly narrows it.
  1167. return true
  1168. case PlatformGrok:
  1169. if !isOfficialGrokCodexBaseURL(account.GetGrokBaseURL()) {
  1170. return false
  1171. }
  1172. canonical := xai.ResolveGrokTextResponsesModelID(upstreamModel)
  1173. return isGrokCodexImageInputModel(canonical)
  1174. default:
  1175. return false
  1176. }
  1177. }
  1178. func isOfficialOpenAICodexAccount(account *Account) bool {
  1179. if account == nil || account.Platform != PlatformOpenAI {
  1180. return false
  1181. }
  1182. if account.IsOpenAIOAuth() {
  1183. return true
  1184. }
  1185. return account.IsOpenAIApiKey() && isOfficialOpenAIModelsBaseURL(account.GetOpenAIBaseURL())
  1186. }
  1187. func isGrokCodexImageInputModel(model string) bool {
  1188. switch strings.ToLower(strings.TrimSpace(model)) {
  1189. case "grok-4.3",
  1190. "grok-4.5",
  1191. "grok-4.6",
  1192. "grok-build-0.1",
  1193. "grok-4.20-0309-reasoning",
  1194. "grok-4.20-0309-non-reasoning",
  1195. "grok-4.20-multi-agent-0309":
  1196. return true
  1197. default:
  1198. return false
  1199. }
  1200. }
  1201. func isOfficialGrokCodexBaseURL(raw string) bool {
  1202. parsed, err := url.Parse(strings.TrimSpace(raw))
  1203. if err != nil || parsed.Host == "" {
  1204. return false
  1205. }
  1206. return xai.IsOfficialBaseURLHost(strings.TrimSuffix(parsed.Hostname(), "."))
  1207. }
  1208. // BuildDeepSeekCodexModelsManifest preserves the historical entry point for
  1209. // callers that still use the provider-specific function name.
  1210. func BuildDeepSeekCodexModelsManifest(modelIDs []string) ([]byte, error) {
  1211. return BuildCodexModelsManifest(modelIDs)
  1212. }
  1213. func mergeConfiguredCodexModelsManifest(
  1214. body []byte,
  1215. configuredModels []string,
  1216. selectedModels []string,
  1217. filterBySelection bool,
  1218. ) ([]byte, bool, error) {
  1219. var envelope map[string]json.RawMessage
  1220. if err := json.Unmarshal(body, &envelope); err != nil {
  1221. return nil, false, err
  1222. }
  1223. var upstreamModels []json.RawMessage
  1224. if err := json.Unmarshal(envelope["models"], &upstreamModels); err != nil {
  1225. return nil, false, err
  1226. }
  1227. selected := make(map[string]struct{}, len(selectedModels))
  1228. for _, modelID := range selectedModels {
  1229. modelID = strings.TrimSpace(modelID)
  1230. if modelID != "" {
  1231. selected[modelID] = struct{}{}
  1232. }
  1233. }
  1234. // 白名单条目匹配统一走 GroupModelAllowlist.Allows(通配条目按前缀展开)。
  1235. allowlist := GroupModelAllowlist{Enabled: filterBySelection, Models: selectedModels}
  1236. seen := make(map[string]struct{}, len(upstreamModels)+len(configuredModels))
  1237. merged := make([]json.RawMessage, 0, len(upstreamModels)+len(configuredModels))
  1238. changed := false
  1239. for _, rawModel := range upstreamModels {
  1240. var descriptor struct {
  1241. Slug string `json:"slug"`
  1242. }
  1243. if err := json.Unmarshal(rawModel, &descriptor); err != nil || strings.TrimSpace(descriptor.Slug) == "" {
  1244. if filterBySelection {
  1245. changed = true
  1246. continue
  1247. }
  1248. merged = append(merged, rawModel)
  1249. continue
  1250. }
  1251. descriptor.Slug = strings.TrimSpace(descriptor.Slug)
  1252. if isCodexDedicatedMediaModel(descriptor.Slug) {
  1253. changed = true
  1254. continue
  1255. }
  1256. if filterBySelection && !allowlist.Allows(descriptor.Slug) {
  1257. changed = true
  1258. continue
  1259. }
  1260. if strings.HasPrefix(descriptor.Slug, codexAutoModelPrefix) {
  1261. _, explicitlyEnabled := selected[descriptor.Slug]
  1262. explicitlyEnabled = filterBySelection && explicitlyEnabled
  1263. if !explicitlyEnabled {
  1264. changed = true
  1265. continue
  1266. }
  1267. visibleModel, visibilityChanged, err := codexModelWithVisibility(rawModel, "list")
  1268. if err != nil {
  1269. return nil, false, err
  1270. }
  1271. rawModel = visibleModel
  1272. changed = changed || visibilityChanged
  1273. }
  1274. seen[descriptor.Slug] = struct{}{}
  1275. merged = append(merged, rawModel)
  1276. }
  1277. for _, modelID := range configuredModels {
  1278. if isCodexDedicatedMediaModel(modelID) {
  1279. continue
  1280. }
  1281. if filterBySelection && !allowlist.Allows(modelID) {
  1282. continue
  1283. }
  1284. if strings.HasPrefix(modelID, codexAutoModelPrefix) {
  1285. if _, explicitlyEnabled := selected[modelID]; !filterBySelection || !explicitlyEnabled {
  1286. continue
  1287. }
  1288. }
  1289. if _, exists := seen[modelID]; exists {
  1290. continue
  1291. }
  1292. rawModel, err := json.Marshal(newConfiguredCodexModelDescriptor(modelID))
  1293. if err != nil {
  1294. return nil, false, err
  1295. }
  1296. merged = append(merged, rawModel)
  1297. seen[modelID] = struct{}{}
  1298. changed = true
  1299. }
  1300. if !changed {
  1301. return body, false, nil
  1302. }
  1303. rawModels, err := json.Marshal(merged)
  1304. if err != nil {
  1305. return nil, false, err
  1306. }
  1307. envelope["models"] = rawModels
  1308. mergedBody, err := json.Marshal(envelope)
  1309. if err != nil {
  1310. return nil, false, err
  1311. }
  1312. return mergedBody, true, nil
  1313. }
  1314. func codexModelWithVisibility(rawModel json.RawMessage, visibility string) (json.RawMessage, bool, error) {
  1315. var fields map[string]json.RawMessage
  1316. if err := json.Unmarshal(rawModel, &fields); err != nil {
  1317. return nil, false, err
  1318. }
  1319. var current string
  1320. if rawVisibility, ok := fields["visibility"]; ok {
  1321. if err := json.Unmarshal(rawVisibility, &current); err == nil && current == visibility {
  1322. return rawModel, false, nil
  1323. }
  1324. }
  1325. rawVisibility, err := json.Marshal(visibility)
  1326. if err != nil {
  1327. return nil, false, err
  1328. }
  1329. fields["visibility"] = rawVisibility
  1330. updated, err := json.Marshal(fields)
  1331. if err != nil {
  1332. return nil, false, err
  1333. }
  1334. return updated, true, nil
  1335. }
  1336. type codexModelsManifestUpstreamError struct {
  1337. err error
  1338. retryable bool
  1339. statusCode int
  1340. headers http.Header
  1341. body []byte
  1342. }
  1343. func (e *codexModelsManifestUpstreamError) Error() string { return e.err.Error() }
  1344. func (e *codexModelsManifestUpstreamError) Unwrap() error { return e.err }
  1345. // IsRetryableCodexModelsManifestError reports whether another selected account
  1346. // may succeed without changing the request. API key upstream 404/405 responses
  1347. // mean that the selected account does not expose a model-discovery endpoint, so
  1348. // another account may still serve the manifest. Other upstream 4xx responses,
  1349. // except 429 and ChatGPT-backend 401, are intentionally not retried. A manifest
  1350. // 401 from the ChatGPT Codex backend reflects the selected OAuth account's
  1351. // upstream token rather than the client request (the client's own API key was
  1352. // already validated locally). Custom API key upstreams keep the no-failover 401
  1353. // behavior because their /models auth semantics are not authoritative for the
  1354. // account.
  1355. func IsRetryableCodexModelsManifestError(err error) bool {
  1356. var upstreamErr *codexModelsManifestUpstreamError
  1357. return errors.As(err, &upstreamErr) && upstreamErr.retryable
  1358. }
  1359. func isRetryableCodexModelsManifestStatus(statusCode int, useAPIKeyUpstream bool) bool {
  1360. return (useAPIKeyUpstream &&
  1361. (statusCode == http.StatusNotFound || statusCode == http.StatusMethodNotAllowed)) ||
  1362. (statusCode == http.StatusUnauthorized && !useAPIKeyUpstream) ||
  1363. statusCode == http.StatusTooManyRequests ||
  1364. (statusCode >= http.StatusInternalServerError && statusCode < 600)
  1365. }
  1366. func isRetryableCodexModelsManifestTransportError(err error) bool {
  1367. if err == nil || errors.Is(err, context.Canceled) {
  1368. return false
  1369. }
  1370. if errors.Is(err, context.DeadlineExceeded) ||
  1371. errors.Is(err, io.EOF) ||
  1372. errors.Is(err, io.ErrUnexpectedEOF) ||
  1373. errors.Is(err, net.ErrClosed) {
  1374. return true
  1375. }
  1376. var opErr *net.OpError
  1377. if errors.As(err, &opErr) {
  1378. return true
  1379. }
  1380. var dnsErr *net.DNSError
  1381. if errors.As(err, &dnsErr) {
  1382. return true
  1383. }
  1384. var goAwayErr http2.GoAwayError
  1385. if errors.As(err, &goAwayErr) {
  1386. return true
  1387. }
  1388. var streamErr http2.StreamError
  1389. if errors.As(err, &streamErr) {
  1390. return true
  1391. }
  1392. var connectionErr http2.ConnectionError
  1393. if errors.As(err, &connectionErr) {
  1394. return true
  1395. }
  1396. var netErr net.Error
  1397. if errors.As(err, &netErr) && netErr.Timeout() {
  1398. return true
  1399. }
  1400. // net/http uses unexported HTTP/2 error types, so typed matching is not
  1401. // possible for errors produced by the standard library transport.
  1402. message := strings.ToLower(err.Error())
  1403. if strings.Contains(message, "http2:") &&
  1404. (strings.Contains(message, "goaway") ||
  1405. strings.Contains(message, "refused_stream") ||
  1406. strings.Contains(message, "frame too large")) {
  1407. return true
  1408. }
  1409. if strings.Contains(message, "stream error: stream id ") {
  1410. return true
  1411. }
  1412. for _, code := range []http2.ErrCode{
  1413. http2.ErrCodeNo,
  1414. http2.ErrCodeProtocol,
  1415. http2.ErrCodeInternal,
  1416. http2.ErrCodeFlowControl,
  1417. http2.ErrCodeSettingsTimeout,
  1418. http2.ErrCodeStreamClosed,
  1419. http2.ErrCodeFrameSize,
  1420. http2.ErrCodeRefusedStream,
  1421. http2.ErrCodeCancel,
  1422. http2.ErrCodeCompression,
  1423. http2.ErrCodeConnect,
  1424. http2.ErrCodeEnhanceYourCalm,
  1425. http2.ErrCodeInadequateSecurity,
  1426. http2.ErrCodeHTTP11Required,
  1427. } {
  1428. if strings.Contains(message, "connection error: "+strings.ToLower(code.String())) {
  1429. return true
  1430. }
  1431. }
  1432. return false
  1433. }
  1434. type openAIModelsRequest struct {
  1435. url string
  1436. headers http.Header
  1437. proxyURL string
  1438. accountID int64
  1439. credentialAccountID int64
  1440. credentialAccount *Account
  1441. accountConcurrency int
  1442. useAPIKeyUpstream bool
  1443. // Cached bodies have already been converted to their requested format.
  1444. standardModelsList bool
  1445. }
  1446. type openAIModelsCacheEntry struct {
  1447. manifest *OpenAIModelsResponse
  1448. order uint64
  1449. expiresAt time.Time
  1450. staleUntil time.Time
  1451. }
  1452. type openAIModelsCacheState uint8
  1453. const (
  1454. openAIModelsCacheMiss openAIModelsCacheState = iota
  1455. openAIModelsCacheFresh
  1456. openAIModelsCacheStale
  1457. )
  1458. type openAIModelsCache struct {
  1459. mu sync.Mutex
  1460. entries map[string]openAIModelsCacheEntry
  1461. nextOrder uint64
  1462. refresh singleflight.Group
  1463. }
  1464. func (c *openAIModelsCache) get(key string, now time.Time) (*OpenAIModelsResponse, openAIModelsCacheState) {
  1465. c.mu.Lock()
  1466. defer c.mu.Unlock()
  1467. entry, ok := c.entries[key]
  1468. if !ok {
  1469. return nil, openAIModelsCacheMiss
  1470. }
  1471. if !now.Before(entry.staleUntil) {
  1472. delete(c.entries, key)
  1473. return nil, openAIModelsCacheMiss
  1474. }
  1475. if now.Before(entry.expiresAt) {
  1476. return entry.manifest, openAIModelsCacheFresh
  1477. }
  1478. return entry.manifest, openAIModelsCacheStale
  1479. }
  1480. func (c *openAIModelsCache) set(key string, manifest *OpenAIModelsResponse, now time.Time) {
  1481. if manifest == nil || len(manifest.Body) > openAIModelsCacheBodyLimit {
  1482. return
  1483. }
  1484. remainingBodyBudget := openAIModelsCacheBodyLimit - len(manifest.Body)
  1485. if len(manifest.upstreamSourceBody) > remainingBodyBudget {
  1486. return
  1487. }
  1488. c.mu.Lock()
  1489. defer c.mu.Unlock()
  1490. if c.entries == nil {
  1491. c.entries = make(map[string]openAIModelsCacheEntry)
  1492. }
  1493. if _, exists := c.entries[key]; !exists && len(c.entries) >= openAIModelsCacheMaxEntries {
  1494. oldestKey := ""
  1495. var oldestOrder uint64
  1496. for candidateKey, entry := range c.entries {
  1497. if !now.Before(entry.staleUntil) {
  1498. delete(c.entries, candidateKey)
  1499. continue
  1500. }
  1501. if oldestKey == "" || entry.order < oldestOrder {
  1502. oldestKey = candidateKey
  1503. oldestOrder = entry.order
  1504. }
  1505. }
  1506. if len(c.entries) >= openAIModelsCacheMaxEntries && oldestKey != "" {
  1507. delete(c.entries, oldestKey)
  1508. }
  1509. }
  1510. c.nextOrder++
  1511. c.entries[key] = openAIModelsCacheEntry{
  1512. manifest: manifest,
  1513. order: c.nextOrder,
  1514. expiresAt: now.Add(openAIModelsCacheTTL),
  1515. staleUntil: now.Add(openAIModelsCacheStaleTTL),
  1516. }
  1517. }
  1518. // FetchCodexModelsManifest fetches the live Codex models manifest from either
  1519. // the ChatGPT backend for OAuth accounts or a custom upstream for API key accounts.
  1520. //
  1521. // After validating the stable top-level envelope, OAuth response bodies are
  1522. // passed through verbatim. Custom API key manifests receive only the narrowly
  1523. // scoped compatibility adjustments required by custom-provider Codex clients.
  1524. func (s *OpenAIGatewayService) FetchCodexModelsManifest(ctx context.Context, account *Account, clientVersion, ifNoneMatch string) (*OpenAIModelsResponse, error) {
  1525. if account == nil {
  1526. return nil, infraerrors.New(http.StatusInternalServerError, "OPENAI_CODEX_MODELS_ACCOUNT_REQUIRED", "account is required")
  1527. }
  1528. credAccount, err := resolveCredentialAccount(ctx, s.accountRepo, account)
  1529. if err != nil {
  1530. return nil, infraerrors.Newf(http.StatusInternalServerError, "OPENAI_CODEX_MODELS_CREDENTIALS_FAILED", "resolve credential account: %v", err)
  1531. }
  1532. clientVersion = strings.TrimSpace(clientVersion)
  1533. if clientVersion == "" {
  1534. clientVersion = CodexCanonicalClientVersion()
  1535. }
  1536. requestEndpoint := chatgptCodexModelsURL
  1537. authToken := ""
  1538. useAPIKeyUpstream := false
  1539. appendModelsPath := false
  1540. switch {
  1541. case credAccount.IsOpenAIOAuth():
  1542. authToken = strings.TrimSpace(credAccount.GetOpenAIAccessToken())
  1543. if authToken == "" && !credAccount.IsOpenAIAgentIdentity() {
  1544. return nil, infraerrors.New(http.StatusBadGateway, "OPENAI_CODEX_MODELS_TOKEN_MISSING", "account has no Codex backend access token")
  1545. }
  1546. case credAccount.IsOpenAIApiKey():
  1547. baseURL := strings.TrimSpace(credAccount.GetOpenAIBaseURL())
  1548. authToken = strings.TrimSpace(credAccount.GetOpenAIApiKey())
  1549. if authToken == "" {
  1550. return nil, infraerrors.New(http.StatusBadGateway, "OPENAI_CODEX_MODELS_API_KEY_MISSING", "account has no API key for the Codex models upstream")
  1551. }
  1552. normalizedBaseURL, validateErr := s.validateUpstreamBaseURL(baseURL)
  1553. if validateErr != nil {
  1554. return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_API_KEY_UPSTREAM_INVALID", "invalid Codex models upstream base URL: %v", validateErr)
  1555. }
  1556. requestEndpoint = normalizedBaseURL
  1557. useAPIKeyUpstream = true
  1558. appendModelsPath = true
  1559. default:
  1560. return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_ACCOUNT_TYPE_UNSUPPORTED", "account type %q cannot fetch the Codex models manifest", credAccount.Type)
  1561. }
  1562. requestURL, err := buildCodexModelsManifestURL(requestEndpoint, appendModelsPath, clientVersion)
  1563. if err != nil {
  1564. if useAPIKeyUpstream {
  1565. return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_API_KEY_UPSTREAM_INVALID", "invalid Codex models upstream base URL: %v", err)
  1566. }
  1567. return nil, infraerrors.Newf(http.StatusInternalServerError, "OPENAI_CODEX_MODELS_REQUEST_FAILED", "parse codex models request URL: %v", err)
  1568. }
  1569. headers := make(http.Header)
  1570. if useAPIKeyUpstream {
  1571. headers.Set("Authorization", "Bearer "+authToken)
  1572. credAccount.ApplyHeaderOverrides(headers)
  1573. } else {
  1574. authHeaders, authErr := s.buildOpenAIAuthenticationHeaders(ctx, credAccount, authToken)
  1575. if authErr != nil {
  1576. return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_AUTH_FAILED", "build Codex models authentication: %v", authErr)
  1577. }
  1578. for key, values := range authHeaders {
  1579. for _, value := range values {
  1580. headers.Add(key, value)
  1581. }
  1582. }
  1583. setOpenAIChatGPTAccountHeaders(headers, credAccount)
  1584. }
  1585. headers.Set("Accept", "application/json")
  1586. overrideUA := ""
  1587. if !useAPIKeyUpstream {
  1588. overrideUA = credAccount.GetOpenAIUserAgent()
  1589. }
  1590. identity := resolveCodexOutboundIdentity(overrideUA)
  1591. headers.Set("Originator", identity.originator)
  1592. headers.Set("User-Agent", identity.userAgent)
  1593. // Version 头优先与 client_version 查询参数同源:客户端自报版本合法且不低于上游
  1594. // 门槛时原样使用;否则回退规范版本,避免陈旧 version 触发上游 404(issue #3901)。
  1595. // client_version 查询参数本身始终按客户端原值透传(内容协商语义,契约见
  1596. // TestFetchCodexModelsManifestPassthrough)。
  1597. headerVersion := NormalizeCodexClientVersion(clientVersion)
  1598. if headerVersion == "" || CompareVersions(headerVersion, codexUpstreamMinVersion) < 0 {
  1599. headerVersion = identity.version
  1600. }
  1601. headers.Set("Version", headerVersion)
  1602. proxyURL := ""
  1603. if account.ProxyID != nil && account.Proxy != nil {
  1604. proxyURL = account.Proxy.URL()
  1605. }
  1606. request := openAIModelsRequest{
  1607. url: requestURL.String(),
  1608. headers: headers,
  1609. proxyURL: proxyURL,
  1610. accountID: account.ID,
  1611. credentialAccountID: credAccount.ID,
  1612. credentialAccount: credAccount,
  1613. accountConcurrency: account.Concurrency,
  1614. useAPIKeyUpstream: useAPIKeyUpstream,
  1615. }
  1616. if useAPIKeyUpstream {
  1617. return s.fetchCachedOpenAIModels(ctx, request, s.fetchCodexModelsManifestUpstreamForRequest(request), ifNoneMatch)
  1618. }
  1619. // OAuth 账号同样经过账号级缓存;闭包保留 agent identity 任务恢复逻辑,
  1620. // 错误时仍交给 handleCodexModelsManifestAccountAuthError 处理账号状态。
  1621. oauthFetch := func(fetchCtx context.Context, ifNoneMatch string) (*OpenAIModelsResponse, error) {
  1622. manifest, fetchErr := s.fetchCodexModelsManifestUpstream(fetchCtx, request, ifNoneMatch)
  1623. if !credAccount.IsOpenAIAgentIdentity() || !isAgentIdentityTaskInvalidCodexModelsError(fetchErr) {
  1624. s.handleCodexModelsManifestAccountAuthError(fetchCtx, account, credAccount, fetchErr)
  1625. return manifest, fetchErr
  1626. }
  1627. expectedTaskID := strings.TrimSpace(credAccount.GetCredential("task_id"))
  1628. if recoverErr := s.recoverAgentIdentityTask(fetchCtx, credAccount, expectedTaskID); recoverErr != nil {
  1629. return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_AUTH_FAILED", "agent identity task recovery failed: %v", recoverErr)
  1630. }
  1631. authHeaders, authErr := s.buildOpenAIAuthenticationHeaders(fetchCtx, credAccount, "")
  1632. if authErr != nil {
  1633. return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_AUTH_FAILED", "build Codex models authentication after task recovery: %v", authErr)
  1634. }
  1635. request.headers.Del("Authorization")
  1636. request.headers.Del("ChatGPT-Account-ID")
  1637. for key, values := range authHeaders {
  1638. for _, value := range values {
  1639. request.headers.Add(key, value)
  1640. }
  1641. }
  1642. setOpenAIChatGPTAccountHeaders(request.headers, credAccount)
  1643. return s.fetchCodexModelsManifestUpstream(fetchCtx, request, ifNoneMatch)
  1644. }
  1645. return s.fetchCachedOpenAIModels(ctx, request, oauthFetch, ifNoneMatch)
  1646. }
  1647. func isAgentIdentityTaskInvalidCodexModelsError(err error) bool {
  1648. var upstreamErr *codexModelsManifestUpstreamError
  1649. return errors.As(err, &upstreamErr) &&
  1650. isAgentIdentityTaskInvalidHTTPResponse(upstreamErr.statusCode, upstreamErr.body)
  1651. }
  1652. // handleCodexModelsManifestAccountAuthError feeds manifest 401s from the
  1653. // ChatGPT Codex backend into the shared upstream-error state machinery
  1654. // (token cache invalidation, temp-unschedulable cooldown, or permanent
  1655. // disable for token_revoked/token_invalidated). Without this, an account
  1656. // whose OAuth token was revoked upstream stays active and schedulable and
  1657. // keeps being selected for every subsequent /models request (#4544).
  1658. //
  1659. // Scope is deliberately limited to plain OAuth accounts: the manifest
  1660. // endpoint authenticates with the same token as /responses forwarding, so a
  1661. // 401 is authoritative for the account. Agent Identity accounts are excluded
  1662. // because their 401s can be task-scoped and have a dedicated recovery flow,
  1663. // and API key manifests come from custom upstreams whose /models auth may
  1664. // diverge from their chat endpoints.
  1665. func (s *OpenAIGatewayService) handleCodexModelsManifestAccountAuthError(ctx context.Context, account, credAccount *Account, err error) {
  1666. if s == nil || account == nil || err == nil {
  1667. return
  1668. }
  1669. if credAccount == nil || !credAccount.IsOpenAIOAuth() || credAccount.IsOpenAIAgentIdentity() {
  1670. return
  1671. }
  1672. var upstreamErr *codexModelsManifestUpstreamError
  1673. if !errors.As(err, &upstreamErr) || upstreamErr.statusCode != http.StatusUnauthorized {
  1674. return
  1675. }
  1676. headers := upstreamErr.headers
  1677. if headers == nil {
  1678. headers = http.Header{}
  1679. }
  1680. s.handleOpenAIAccountUpstreamError(ctx, account, upstreamErr.statusCode, headers, upstreamErr.body)
  1681. }
  1682. func (s *OpenAIGatewayService) fetchCachedOpenAIModels(ctx context.Context, request openAIModelsRequest, fetch func(ctx context.Context, ifNoneMatch string) (*OpenAIModelsResponse, error), ifNoneMatch string) (*OpenAIModelsResponse, error) {
  1683. if err := ctx.Err(); err != nil {
  1684. return nil, err
  1685. }
  1686. cacheKey := buildOpenAIModelsCacheKey(request)
  1687. manifest, state := s.openAIModelsCache.get(cacheKey, time.Now())
  1688. if state == openAIModelsCacheFresh {
  1689. return openAIModelsResponseForClient(manifest, ifNoneMatch), nil
  1690. }
  1691. resultCh := s.refreshCachedOpenAIModels(cacheKey, request, fetch)
  1692. if state == openAIModelsCacheStale {
  1693. return openAIModelsResponseForClient(manifest, ifNoneMatch), nil
  1694. }
  1695. select {
  1696. case <-ctx.Done():
  1697. return nil, ctx.Err()
  1698. case result := <-resultCh:
  1699. if result.Err != nil {
  1700. return nil, result.Err
  1701. }
  1702. manifest, ok := result.Val.(*OpenAIModelsResponse)
  1703. if !ok || manifest == nil {
  1704. return nil, infraerrors.New(http.StatusInternalServerError, "OPENAI_CODEX_MODELS_REQUEST_FAILED", "invalid shared Codex models manifest result")
  1705. }
  1706. return openAIModelsResponseForClient(manifest, ifNoneMatch), nil
  1707. }
  1708. }
  1709. func (s *OpenAIGatewayService) refreshCachedOpenAIModels(cacheKey string, request openAIModelsRequest, fetch func(ctx context.Context, ifNoneMatch string) (*OpenAIModelsResponse, error)) <-chan singleflight.Result {
  1710. return s.openAIModelsCache.refresh.DoChan(cacheKey, func() (any, error) {
  1711. ctx, cancel := context.WithTimeout(context.Background(), codexModelsManifestRequestTimeout)
  1712. defer cancel()
  1713. cached, _ := s.openAIModelsCache.get(cacheKey, time.Now())
  1714. ifNoneMatch := ""
  1715. if cached != nil {
  1716. ifNoneMatch = cached.upstreamETag
  1717. }
  1718. manifest, err := fetch(ctx, ifNoneMatch)
  1719. if err != nil {
  1720. return nil, err
  1721. }
  1722. if manifest.NotModified && cached != nil {
  1723. s.openAIModelsCache.set(cacheKey, cached, time.Now())
  1724. return cached, nil
  1725. }
  1726. if !manifest.NotModified {
  1727. s.openAIModelsCache.set(cacheKey, manifest, time.Now())
  1728. }
  1729. return manifest, nil
  1730. })
  1731. }
  1732. func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstreamForRequest(request openAIModelsRequest) func(ctx context.Context, ifNoneMatch string) (*OpenAIModelsResponse, error) {
  1733. return func(ctx context.Context, ifNoneMatch string) (*OpenAIModelsResponse, error) {
  1734. return s.fetchCodexModelsManifestUpstream(ctx, request, ifNoneMatch)
  1735. }
  1736. }
  1737. func (s *OpenAIGatewayService) fetchOpenAIModelsUpstream(ctx context.Context, request openAIModelsRequest, ifNoneMatch string) (*OpenAIModelsResponse, error) {
  1738. reqCtx, cancel := context.WithTimeout(ctx, codexModelsManifestRequestTimeout)
  1739. defer cancel()
  1740. req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, request.url, nil)
  1741. if err != nil {
  1742. return nil, infraerrors.Newf(http.StatusInternalServerError, "OPENAI_CODEX_MODELS_REQUEST_FAILED", "create codex models request: %v", err)
  1743. }
  1744. req.Header = request.headers.Clone()
  1745. if ifNoneMatch = strings.TrimSpace(ifNoneMatch); ifNoneMatch != "" {
  1746. req.Header.Set("If-None-Match", ifNoneMatch)
  1747. }
  1748. var resp *http.Response
  1749. if request.useAPIKeyUpstream {
  1750. if s.httpUpstream == nil {
  1751. return nil, infraerrors.New(http.StatusInternalServerError, "OPENAI_CODEX_MODELS_UPSTREAM_NOT_CONFIGURED", "Codex models upstream HTTP client is not configured")
  1752. }
  1753. req = req.WithContext(WithHTTPUpstreamProfile(req.Context(), HTTPUpstreamProfileOpenAI))
  1754. resp, err = s.httpUpstream.Do(req, request.proxyURL, request.accountID, request.accountConcurrency)
  1755. } else {
  1756. handled := false
  1757. if s.pluginManager != nil {
  1758. resp, handled, err = s.pluginManager.RoundTripOpenAIOAuth(reqCtx, req, request.proxyURL, request.credentialAccount)
  1759. }
  1760. if !handled {
  1761. client, clientErr := httpclient.GetClient(httpclient.Options{
  1762. ProxyURL: request.proxyURL,
  1763. Timeout: codexModelsManifestRequestTimeout,
  1764. ResponseHeaderTimeout: 10 * time.Second,
  1765. })
  1766. if clientErr != nil {
  1767. return nil, infraerrors.Newf(http.StatusInternalServerError, "OPENAI_CODEX_MODELS_PROXY_INVALID", "invalid proxy configuration: %v", clientErr)
  1768. }
  1769. resp, err = client.Do(req)
  1770. }
  1771. }
  1772. if err != nil {
  1773. return nil, &codexModelsManifestUpstreamError{
  1774. err: infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_UPSTREAM_FAILED", "codex models manifest request failed: %v", err),
  1775. retryable: isRetryableCodexModelsManifestTransportError(err),
  1776. }
  1777. }
  1778. defer func() { _ = resp.Body.Close() }()
  1779. if resp.StatusCode == http.StatusNotModified {
  1780. return &OpenAIModelsResponse{ETag: resp.Header.Get("ETag"), NotModified: true}, nil
  1781. }
  1782. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  1783. body, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
  1784. body = s.redactAgentIdentitySensitiveBody(reqCtx, request.credentialAccount, body)
  1785. message := strings.TrimSpace(string(body))
  1786. if message == "" {
  1787. message = resp.Status
  1788. }
  1789. return nil, &codexModelsManifestUpstreamError{
  1790. err: infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_UPSTREAM_FAILED", "codex models manifest upstream error %d: %s", resp.StatusCode, message),
  1791. statusCode: resp.StatusCode,
  1792. headers: resp.Header.Clone(),
  1793. body: body,
  1794. retryable: isRetryableCodexModelsManifestStatus(resp.StatusCode, request.useAPIKeyUpstream),
  1795. }
  1796. }
  1797. bodyLimit := resolveModelsListReadLimit(s.cfg)
  1798. body, err := io.ReadAll(io.LimitReader(resp.Body, bodyLimit+1))
  1799. if err != nil {
  1800. return nil, &codexModelsManifestUpstreamError{
  1801. err: infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_UPSTREAM_FAILED", "read codex models manifest response: %v", err),
  1802. retryable: isRetryableCodexModelsManifestTransportError(err),
  1803. }
  1804. }
  1805. if int64(len(body)) > bodyLimit {
  1806. return nil, &codexModelsManifestUpstreamError{
  1807. err: infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_UPSTREAM_FAILED", "codex models manifest response exceeds %d bytes", bodyLimit),
  1808. retryable: true,
  1809. }
  1810. }
  1811. etag := resp.Header.Get("ETag")
  1812. return &OpenAIModelsResponse{Body: body, ETag: etag, upstreamETag: etag}, nil
  1813. }
  1814. func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstream(ctx context.Context, request openAIModelsRequest, ifNoneMatch string) (*OpenAIModelsResponse, error) {
  1815. response, err := s.fetchOpenAIModelsUpstream(ctx, request, ifNoneMatch)
  1816. if err != nil || response.NotModified {
  1817. return response, err
  1818. }
  1819. body := response.Body
  1820. upstreamBody := body
  1821. convertedFromOpenAIModelList := false
  1822. if request.useAPIKeyUpstream {
  1823. convertedBody := convertOpenAIModelListToCodexManifestForAccount(body, request.credentialAccount)
  1824. convertedFromOpenAIModelList = !bytes.Equal(convertedBody, body)
  1825. body = convertedBody
  1826. }
  1827. if err := validateCodexModelsManifestEnvelope(body); err != nil {
  1828. return nil, &codexModelsManifestUpstreamError{
  1829. err: infraerrors.Newf(
  1830. http.StatusBadGateway,
  1831. "OPENAI_CODEX_MODELS_UPSTREAM_INVALID_MANIFEST",
  1832. "codex models manifest upstream returned an invalid envelope: %v",
  1833. err,
  1834. ),
  1835. retryable: true,
  1836. }
  1837. }
  1838. if request.useAPIKeyUpstream {
  1839. body, err = completeAPIKeyCodexModelsManifestMetadata(
  1840. body,
  1841. false,
  1842. request.credentialAccount,
  1843. )
  1844. if err != nil {
  1845. return nil, &codexModelsManifestUpstreamError{
  1846. err: infraerrors.Newf(
  1847. http.StatusBadGateway,
  1848. "OPENAI_CODEX_MODELS_UPSTREAM_INVALID_MANIFEST",
  1849. "codex models manifest upstream metadata could not be completed: %v",
  1850. err,
  1851. ),
  1852. retryable: true,
  1853. }
  1854. }
  1855. body, err = adjustAPIKeyCodexModelsManifest(body, request.credentialAccount)
  1856. if err != nil {
  1857. return nil, &codexModelsManifestUpstreamError{
  1858. err: infraerrors.Newf(
  1859. http.StatusBadGateway,
  1860. "OPENAI_CODEX_MODELS_UPSTREAM_INVALID_MANIFEST",
  1861. "codex models manifest upstream could not be adjusted: %v",
  1862. err,
  1863. ),
  1864. retryable: true,
  1865. }
  1866. }
  1867. }
  1868. etag := response.upstreamETag
  1869. manifest := &OpenAIModelsResponse{
  1870. Body: body,
  1871. ETag: etag,
  1872. upstreamETag: etag,
  1873. upstreamSourceBody: append([]byte(nil), upstreamBody...),
  1874. convertedFromOpenAIModelList: convertedFromOpenAIModelList,
  1875. }
  1876. if request.useAPIKeyUpstream && !bytes.Equal(body, upstreamBody) {
  1877. manifest.ETag = codexModelsManifestBodyETag(body)
  1878. }
  1879. return manifest, nil
  1880. }
  1881. func codexModelsManifestBodyETag(body []byte) string {
  1882. sum := sha256.Sum256(body)
  1883. return fmt.Sprintf(`"%x"`, sum)
  1884. }
  1885. // CodexModelsManifestETag returns the strong ETag for a generated client
  1886. // catalog. It is based on the final JSON body after local filtering.
  1887. func CodexModelsManifestETag(body []byte) string {
  1888. return codexModelsManifestBodyETag(body)
  1889. }
  1890. var apiKeyCodexModelsWithoutResponsesLite = map[string]struct{}{
  1891. "gpt-6-astra": {},
  1892. "gpt-5.6-sol": {},
  1893. "gpt-5.6-terra": {},
  1894. "gpt-5.6-luna": {},
  1895. }
  1896. // adjustAPIKeyCodexModelsManifest prevents Codex from selecting Responses
  1897. // Lite for custom API key providers. Those clients do not install web.run in
  1898. // Lite mode, so the affected model manifests must advertise the full Responses
  1899. // path. Return the original body when no targeted true value is present.
  1900. func adjustAPIKeyCodexModelsManifest(body []byte, account *Account) ([]byte, error) {
  1901. var envelope map[string]json.RawMessage
  1902. if err := json.Unmarshal(body, &envelope); err != nil {
  1903. return nil, fmt.Errorf("decode JSON object: %w", err)
  1904. }
  1905. var models []json.RawMessage
  1906. if err := json.Unmarshal(envelope["models"], &models); err != nil {
  1907. return nil, fmt.Errorf("decode top-level models array: %w", err)
  1908. }
  1909. changed := false
  1910. for i, rawModel := range models {
  1911. var model map[string]json.RawMessage
  1912. if err := json.Unmarshal(rawModel, &model); err != nil || model == nil {
  1913. continue
  1914. }
  1915. var slug string
  1916. if err := json.Unmarshal(model["slug"], &slug); err != nil {
  1917. continue
  1918. }
  1919. target := slug
  1920. if account != nil {
  1921. target = account.GetMappedModel(slug)
  1922. }
  1923. if isOpenAIGPT6AstraModel(target) {
  1924. target = "gpt-6-astra"
  1925. }
  1926. if _, targeted := apiKeyCodexModelsWithoutResponsesLite[target]; !targeted {
  1927. continue
  1928. }
  1929. var useResponsesLite bool
  1930. if err := json.Unmarshal(model["use_responses_lite"], &useResponsesLite); err != nil || !useResponsesLite {
  1931. continue
  1932. }
  1933. model["use_responses_lite"] = json.RawMessage("false")
  1934. adjusted, err := json.Marshal(model)
  1935. if err != nil {
  1936. return nil, fmt.Errorf("encode model %q: %w", slug, err)
  1937. }
  1938. models[i] = adjusted
  1939. changed = true
  1940. }
  1941. if !changed {
  1942. return body, nil
  1943. }
  1944. adjustedModels, err := json.Marshal(models)
  1945. if err != nil {
  1946. return nil, fmt.Errorf("encode top-level models array: %w", err)
  1947. }
  1948. envelope["models"] = adjustedModels
  1949. adjusted, err := json.Marshal(envelope)
  1950. if err != nil {
  1951. return nil, fmt.Errorf("encode JSON object: %w", err)
  1952. }
  1953. return adjusted, nil
  1954. }
  1955. // convertOpenAIModelListToCodexManifest rewrites a standard OpenAI
  1956. // GET /v1/models response ({"object":"list","data":[{"id":...},...]}) into the
  1957. // same complete Codex manifest used by locally generated custom-provider
  1958. // catalogs. Bodies that already carry a top-level models field, are not the
  1959. // standard list shape, or yield no usable model IDs are returned unchanged so
  1960. // envelope validation reports the original payload.
  1961. func convertOpenAIModelListToCodexManifest(body []byte) []byte {
  1962. return convertOpenAIModelListToCodexManifestForAccount(body, nil)
  1963. }
  1964. func convertOpenAIModelListToCodexManifestForAccount(body []byte, account *Account) []byte {
  1965. var envelope map[string]json.RawMessage
  1966. if err := json.Unmarshal(body, &envelope); err != nil || envelope == nil {
  1967. return body
  1968. }
  1969. if _, ok := envelope["models"]; ok {
  1970. return body
  1971. }
  1972. data, ok := envelope["data"]
  1973. if !ok {
  1974. return body
  1975. }
  1976. var entries []map[string]json.RawMessage
  1977. if err := json.Unmarshal(data, &entries); err != nil {
  1978. return body
  1979. }
  1980. modelIDs := make([]string, 0, len(entries))
  1981. modelMetadata := make(map[string]codexModelMetadataOverride, len(entries))
  1982. metadataModels := make(map[string]string, len(entries))
  1983. for _, entry := range entries {
  1984. var id string
  1985. if err := json.Unmarshal(entry["id"], &id); err != nil {
  1986. continue
  1987. }
  1988. id = strings.TrimSpace(id)
  1989. if id == "" {
  1990. continue
  1991. }
  1992. modelIDs = append(modelIDs, id)
  1993. capabilityModel := id
  1994. if account != nil {
  1995. capabilityModel = account.GetMappedModel(id)
  1996. }
  1997. metadataModels[id] = capabilityModel
  1998. capabilities := accountCodexToolCapabilities(account, capabilityModel)
  1999. applyCodexToolCapabilities(capabilities, entry, true)
  2000. modelMetadata[id] = codexModelMetadataOverride{UpstreamModelMetadata: UpstreamModelMetadata{
  2001. CodexToolCapabilities: capabilities,
  2002. }}
  2003. }
  2004. if len(modelIDs) == 0 {
  2005. return body
  2006. }
  2007. imageInputModels := make(map[string]bool, len(modelIDs))
  2008. for _, modelID := range modelIDs {
  2009. if accountCodexModelSupportsImageInput(account, modelID) {
  2010. imageInputModels[modelID] = true
  2011. }
  2012. }
  2013. searchToolModels := make(map[string]bool, len(modelIDs))
  2014. if shouldForwardOpenAIResponsesViaRawChatCompletions(account) {
  2015. for _, modelID := range modelIDs {
  2016. searchToolModels[modelID] = true
  2017. }
  2018. }
  2019. converted, err := buildCodexModelsManifest(modelIDs, imageInputModels, searchToolModels, metadataModels, modelMetadata)
  2020. if err != nil {
  2021. return body
  2022. }
  2023. return converted
  2024. }
  2025. // completeAPIKeyCodexModelsManifestMetadata fills fields omitted by standard
  2026. // OpenAI-compatible /models endpoints. Existing provider metadata always wins;
  2027. // only absent or null values are synthesized.
  2028. // CompleteAPIKeyCodexModelsManifestForClient fills the complete ModelInfo
  2029. // contract immediately before a group-specific API key manifest is returned.
  2030. // The shared upstream cache remains independent from local group policy.
  2031. func (s *OpenAIGatewayService) CompleteAPIKeyCodexModelsManifestForClient(manifest *OpenAIModelsResponse, account *Account) error {
  2032. if manifest == nil || account == nil || !account.IsOpenAIApiKey() || manifest.NotModified || len(manifest.Body) == 0 {
  2033. return nil
  2034. }
  2035. body := manifest.Body
  2036. if len(manifest.upstreamSourceBody) > 0 {
  2037. body = append([]byte(nil), manifest.upstreamSourceBody...)
  2038. if manifest.convertedFromOpenAIModelList {
  2039. body = convertOpenAIModelListToCodexManifestForAccount(body, account)
  2040. }
  2041. }
  2042. var err error
  2043. body, err = applySyncedAPIKeyCodexModelMetadata(body, account, manifest.convertedFromOpenAIModelList)
  2044. if err != nil {
  2045. return err
  2046. }
  2047. body, err = completeAPIKeyCodexModelsManifestMetadata(
  2048. body,
  2049. true,
  2050. account,
  2051. )
  2052. if err != nil {
  2053. return err
  2054. }
  2055. body, err = adjustAPIKeyCodexModelsManifest(body, account)
  2056. if err != nil {
  2057. return err
  2058. }
  2059. manifest.Body = body
  2060. manifest.ETag = codexModelsManifestBodyETag(manifest.Body)
  2061. return nil
  2062. }
  2063. func applySyncedAPIKeyCodexModelMetadata(body []byte, account *Account, overwriteLocalDefaults bool) ([]byte, error) {
  2064. snapshot := account.GetUpstreamModelMetadataSnapshot()
  2065. if snapshot == nil || len(snapshot.Models) == 0 {
  2066. return body, nil
  2067. }
  2068. var envelope map[string]json.RawMessage
  2069. if err := json.Unmarshal(body, &envelope); err != nil {
  2070. return nil, fmt.Errorf("decode JSON object: %w", err)
  2071. }
  2072. var models []json.RawMessage
  2073. if err := json.Unmarshal(envelope["models"], &models); err != nil {
  2074. return nil, fmt.Errorf("decode top-level models array: %w", err)
  2075. }
  2076. changed := false
  2077. for i, rawModel := range models {
  2078. var model map[string]json.RawMessage
  2079. if err := json.Unmarshal(rawModel, &model); err != nil || model == nil {
  2080. continue
  2081. }
  2082. var slug string
  2083. if err := json.Unmarshal(model["slug"], &slug); err != nil {
  2084. continue
  2085. }
  2086. slug = strings.TrimSpace(slug)
  2087. lookupModel := account.GetMappedModel(slug)
  2088. metadata, ok := snapshot.Models[lookupModel]
  2089. if !ok {
  2090. continue
  2091. }
  2092. if lookupModel != slug {
  2093. metadata.DisplayName = ""
  2094. metadata.Description = ""
  2095. }
  2096. descriptor := newConfiguredCodexModelDescriptor(slug)
  2097. applyUpstreamModelMetadataToCodexDescriptor(
  2098. &descriptor,
  2099. codexModelMetadataOverride{UpstreamModelMetadata: metadata},
  2100. )
  2101. descriptorBody, err := json.Marshal(descriptor)
  2102. if err != nil {
  2103. return nil, fmt.Errorf("encode synced model %q: %w", slug, err)
  2104. }
  2105. var syncedFields map[string]json.RawMessage
  2106. if err := json.Unmarshal(descriptorBody, &syncedFields); err != nil {
  2107. return nil, fmt.Errorf("decode synced model %q: %w", slug, err)
  2108. }
  2109. fields := make([]string, 0, 7)
  2110. if strings.TrimSpace(metadata.DisplayName) != "" {
  2111. fields = append(fields, "display_name")
  2112. }
  2113. if strings.TrimSpace(metadata.Description) != "" {
  2114. fields = append(fields, "description")
  2115. }
  2116. if metadata.Reasoning != nil {
  2117. fields = append(fields, "default_reasoning_level", "supported_reasoning_levels")
  2118. }
  2119. if len(normalizeCodexInputModalities(metadata.InputModalities)) > 0 {
  2120. fields = append(fields, "input_modalities")
  2121. }
  2122. if metadata.ContextWindow > 0 {
  2123. fields = append(fields, "context_window", "max_context_window")
  2124. }
  2125. // List conversion has already applied live fields over account capabilities.
  2126. modelChanged := applyCodexToolCapabilities(model, metadata.CodexToolCapabilities, false)
  2127. for _, field := range fields {
  2128. value, exists := syncedFields[field]
  2129. if !exists {
  2130. continue
  2131. }
  2132. current, currentExists := model[field]
  2133. current = bytes.TrimSpace(current)
  2134. if !overwriteLocalDefaults && currentExists && len(current) > 0 && !bytes.Equal(current, []byte("null")) {
  2135. continue
  2136. }
  2137. if bytes.Equal(current, bytes.TrimSpace(value)) {
  2138. continue
  2139. }
  2140. model[field] = value
  2141. modelChanged = true
  2142. }
  2143. if !modelChanged {
  2144. continue
  2145. }
  2146. encoded, err := json.Marshal(model)
  2147. if err != nil {
  2148. return nil, fmt.Errorf("encode model %q with synced metadata: %w", slug, err)
  2149. }
  2150. models[i] = encoded
  2151. changed = true
  2152. }
  2153. if !changed {
  2154. return body, nil
  2155. }
  2156. encodedModels, err := json.Marshal(models)
  2157. if err != nil {
  2158. return nil, fmt.Errorf("encode models with synced metadata: %w", err)
  2159. }
  2160. envelope["models"] = encodedModels
  2161. updated, err := json.Marshal(envelope)
  2162. if err != nil {
  2163. return nil, fmt.Errorf("encode manifest with synced metadata: %w", err)
  2164. }
  2165. return updated, nil
  2166. }
  2167. func completeAPIKeyCodexModelsManifestMetadata(body []byte, completeAll bool, account *Account) ([]byte, error) {
  2168. var envelope map[string]json.RawMessage
  2169. if err := json.Unmarshal(body, &envelope); err != nil {
  2170. return nil, fmt.Errorf("decode JSON object: %w", err)
  2171. }
  2172. var models []json.RawMessage
  2173. if err := json.Unmarshal(envelope["models"], &models); err != nil {
  2174. return nil, fmt.Errorf("decode top-level models array: %w", err)
  2175. }
  2176. officialOpenAI := account != nil && isOfficialOpenAIModelsBaseURL(account.GetOpenAIBaseURL())
  2177. changed := false
  2178. if officialOpenAI {
  2179. filtered := make([]json.RawMessage, 0, len(models))
  2180. for _, rawModel := range models {
  2181. var model struct {
  2182. Slug string `json:"slug"`
  2183. }
  2184. if err := json.Unmarshal(rawModel, &model); err != nil || strings.TrimSpace(model.Slug) == "" {
  2185. filtered = append(filtered, rawModel)
  2186. continue
  2187. }
  2188. if !isOfficialOpenAICodexCatalogModel(model.Slug) {
  2189. changed = true
  2190. continue
  2191. }
  2192. filtered = append(filtered, rawModel)
  2193. }
  2194. models = filtered
  2195. }
  2196. for i, rawModel := range models {
  2197. var model map[string]json.RawMessage
  2198. if err := json.Unmarshal(rawModel, &model); err != nil || model == nil {
  2199. continue
  2200. }
  2201. var slug string
  2202. if err := json.Unmarshal(model["slug"], &slug); err != nil {
  2203. continue
  2204. }
  2205. slug = strings.TrimSpace(slug)
  2206. if slug == "" {
  2207. continue
  2208. }
  2209. completeDescriptor := completeAll || isDeepSeekCodexModel(slug)
  2210. forceOfficialImage := officialOpenAI && isOpenAICodexImageInputModel(slug)
  2211. if !completeDescriptor && !forceOfficialImage {
  2212. continue
  2213. }
  2214. descriptor := newConfiguredCodexModelDescriptor(slug)
  2215. descriptor.SupportsSearchTool = shouldForwardOpenAIResponsesViaRawChatCompletions(account)
  2216. if accountCodexModelSupportsImageInput(account, slug) {
  2217. descriptor.InputModalities = []string{"text", "image"}
  2218. }
  2219. if forceOfficialImage {
  2220. descriptor.InputModalities = []string{"text", "image"}
  2221. descriptor.SupportsImageDetailOriginal = true
  2222. }
  2223. defaultBody, err := json.Marshal(descriptor)
  2224. if err != nil {
  2225. return nil, fmt.Errorf("encode default model %q: %w", slug, err)
  2226. }
  2227. var defaults map[string]json.RawMessage
  2228. if err := json.Unmarshal(defaultBody, &defaults); err != nil {
  2229. return nil, fmt.Errorf("decode default model %q: %w", slug, err)
  2230. }
  2231. capabilityModel := slug
  2232. if account != nil {
  2233. capabilityModel = account.GetMappedModel(slug)
  2234. }
  2235. capabilities := accountCodexToolCapabilities(account, capabilityModel)
  2236. modelChanged := applyCodexToolCapabilities(model, capabilities, false)
  2237. if completeDescriptor {
  2238. merged, err := mergeMissingCodexModelFields(model, defaults)
  2239. if err != nil {
  2240. return nil, fmt.Errorf("complete model %q: %w", slug, err)
  2241. }
  2242. modelChanged = merged || modelChanged
  2243. }
  2244. if forceOfficialImage {
  2245. modalities, err := json.Marshal([]string{"text", "image"})
  2246. if err != nil {
  2247. return nil, fmt.Errorf("encode input modalities for model %q: %w", slug, err)
  2248. }
  2249. if !bytes.Equal(bytes.TrimSpace(model["input_modalities"]), modalities) {
  2250. model["input_modalities"] = modalities
  2251. modelChanged = true
  2252. }
  2253. imageDetailOriginal := json.RawMessage("true")
  2254. if !bytes.Equal(bytes.TrimSpace(model["supports_image_detail_original"]), imageDetailOriginal) {
  2255. model["supports_image_detail_original"] = imageDetailOriginal
  2256. modelChanged = true
  2257. }
  2258. }
  2259. if !modelChanged {
  2260. continue
  2261. }
  2262. encoded, err := json.Marshal(model)
  2263. if err != nil {
  2264. return nil, fmt.Errorf("encode completed model %q: %w", slug, err)
  2265. }
  2266. models[i] = encoded
  2267. changed = true
  2268. }
  2269. if !changed {
  2270. return body, nil
  2271. }
  2272. encodedModels, err := json.Marshal(models)
  2273. if err != nil {
  2274. return nil, fmt.Errorf("encode top-level models array: %w", err)
  2275. }
  2276. envelope["models"] = encodedModels
  2277. completed, err := json.Marshal(envelope)
  2278. if err != nil {
  2279. return nil, fmt.Errorf("encode JSON object: %w", err)
  2280. }
  2281. return completed, nil
  2282. }
  2283. func mergeMissingCodexModelFields(current, defaults map[string]json.RawMessage) (bool, error) {
  2284. changed := false
  2285. for key, defaultValue := range defaults {
  2286. currentValue, exists := current[key]
  2287. if exists && stringSliceContains(codexToolCapabilityFields, key) {
  2288. continue
  2289. }
  2290. if !exists || (bytes.Equal(bytes.TrimSpace(currentValue), []byte("null")) &&
  2291. !bytes.Equal(bytes.TrimSpace(defaultValue), []byte("null"))) {
  2292. current[key] = defaultValue
  2293. changed = true
  2294. continue
  2295. }
  2296. var currentObject map[string]json.RawMessage
  2297. var defaultObject map[string]json.RawMessage
  2298. if err := json.Unmarshal(currentValue, &currentObject); err != nil || currentObject == nil {
  2299. continue
  2300. }
  2301. if err := json.Unmarshal(defaultValue, &defaultObject); err != nil || defaultObject == nil {
  2302. continue
  2303. }
  2304. nestedChanged, err := mergeMissingCodexModelFields(currentObject, defaultObject)
  2305. if err != nil {
  2306. return false, err
  2307. }
  2308. if !nestedChanged {
  2309. continue
  2310. }
  2311. mergedValue, err := json.Marshal(currentObject)
  2312. if err != nil {
  2313. return false, fmt.Errorf("encode field %q: %w", key, err)
  2314. }
  2315. current[key] = mergedValue
  2316. changed = true
  2317. }
  2318. return changed, nil
  2319. }
  2320. func validateCodexModelsManifestEnvelope(body []byte) error {
  2321. var envelope map[string]json.RawMessage
  2322. if err := json.Unmarshal(body, &envelope); err != nil {
  2323. return fmt.Errorf("decode JSON object: %w", err)
  2324. }
  2325. if envelope == nil {
  2326. return errors.New("expected a JSON object")
  2327. }
  2328. models, ok := envelope["models"]
  2329. if !ok {
  2330. return errors.New("missing top-level models array")
  2331. }
  2332. models = bytes.TrimSpace(models)
  2333. var entries []json.RawMessage
  2334. if len(models) == 0 || models[0] != '[' {
  2335. return errors.New("top-level models field is not an array")
  2336. }
  2337. if err := json.Unmarshal(models, &entries); err != nil {
  2338. return fmt.Errorf("decode top-level models array: %w", err)
  2339. }
  2340. return nil
  2341. }
  2342. func buildOpenAIModelsCacheKey(request openAIModelsRequest) string {
  2343. hasher := sha256.New()
  2344. _, _ = fmt.Fprintf(hasher, "%d\n%d\n%t\n%s\n%s\n", request.accountID, request.credentialAccountID, request.standardModelsList, request.proxyURL, request.url)
  2345. headerNames := make([]string, 0, len(request.headers))
  2346. for name := range request.headers {
  2347. headerNames = append(headerNames, name)
  2348. }
  2349. sort.Strings(headerNames)
  2350. for _, name := range headerNames {
  2351. _, _ = fmt.Fprintf(hasher, "%s\n", strings.ToLower(name))
  2352. for _, value := range request.headers[name] {
  2353. _, _ = fmt.Fprintf(hasher, "%s\n", value)
  2354. }
  2355. }
  2356. return fmt.Sprintf("%x", hasher.Sum(nil))
  2357. }
  2358. func cloneOpenAIModelsResponse(manifest *OpenAIModelsResponse) *OpenAIModelsResponse {
  2359. if manifest == nil {
  2360. return nil
  2361. }
  2362. cloned := *manifest
  2363. if manifest.Body != nil {
  2364. cloned.Body = append([]byte(nil), manifest.Body...)
  2365. }
  2366. if manifest.upstreamSourceBody != nil {
  2367. cloned.upstreamSourceBody = append([]byte(nil), manifest.upstreamSourceBody...)
  2368. }
  2369. return &cloned
  2370. }
  2371. func openAIModelsResponseForClient(manifest *OpenAIModelsResponse, ifNoneMatch string) *OpenAIModelsResponse {
  2372. if manifest == nil {
  2373. return nil
  2374. }
  2375. if codexModelsManifestETagMatches(ifNoneMatch, manifest.ETag) {
  2376. return &OpenAIModelsResponse{ETag: manifest.ETag, NotModified: true}
  2377. }
  2378. return cloneOpenAIModelsResponse(manifest)
  2379. }
  2380. func codexModelsManifestETagMatches(ifNoneMatch, etag string) bool {
  2381. etag = strings.TrimSpace(etag)
  2382. if etag == "" {
  2383. return false
  2384. }
  2385. normalize := func(value string) string {
  2386. value = strings.TrimSpace(value)
  2387. if len(value) >= 2 && strings.EqualFold(value[:2], "W/") {
  2388. value = strings.TrimSpace(value[2:])
  2389. }
  2390. return value
  2391. }
  2392. want := normalize(etag)
  2393. for _, candidate := range strings.Split(ifNoneMatch, ",") {
  2394. candidate = strings.TrimSpace(candidate)
  2395. if candidate == "*" || normalize(candidate) == want {
  2396. return true
  2397. }
  2398. }
  2399. return false
  2400. }
  2401. // CodexModelsManifestETagMatches applies If-None-Match semantics to a Codex
  2402. // catalog ETag, including weak and comma-separated validators.
  2403. func CodexModelsManifestETagMatches(ifNoneMatch, etag string) bool {
  2404. return codexModelsManifestETagMatches(ifNoneMatch, etag)
  2405. }
  2406. func isOfficialOpenAIModelsBaseURL(raw string) bool {
  2407. parsed, err := url.Parse(strings.TrimSpace(raw))
  2408. if err != nil {
  2409. return false
  2410. }
  2411. hostname := strings.TrimSuffix(parsed.Hostname(), ".")
  2412. return strings.EqualFold(hostname, "api.openai.com")
  2413. }
  2414. func buildCodexModelsManifestURL(endpoint string, appendModelsPath bool, clientVersion string) (*url.URL, error) {
  2415. requestURL, err := url.Parse(endpoint)
  2416. if err != nil {
  2417. return nil, err
  2418. }
  2419. if requestURL.Fragment != "" {
  2420. return nil, fmt.Errorf("URL fragments are not supported")
  2421. }
  2422. query := requestURL.Query()
  2423. requestURL.RawQuery = ""
  2424. requestURL.ForceQuery = false
  2425. if appendModelsPath {
  2426. requestURL, err = url.Parse(buildOpenAIModelsURL(requestURL.String()))
  2427. if err != nil {
  2428. return nil, err
  2429. }
  2430. }
  2431. query.Set("client_version", clientVersion)
  2432. requestURL.RawQuery = query.Encode()
  2433. return requestURL, nil
  2434. }