From 200de9c989b40c0c63cf89ae0cf38a211c14d158 Mon Sep 17 00:00:00 2001 From: Jobs Date: Fri, 25 Sep 2026 14:54:05 +0800 Subject: [PATCH 1/2] feat(bps): add OpenAI BPS support for 1.1.5 Add the dedicated OpenAI BPS platform with manual access tokens, account-bound Redis state, Codex tool translation, compaction and validated structured output. Integrate model catalogs, scheduling, quotas and monitoring, cover protocol regressions, and prepare the 1.1.5 changelog. --- .gitignore | 2 + backend/cmd/server/VERSION | 2 +- backend/ent/channelmonitor/channelmonitor.go | 3 +- .../channelmonitorrequesttemplate.go | 3 +- backend/ent/migrate/schema.go | 4 +- backend/ent/schema/channel_monitor.go | 2 +- .../channel_monitor_request_template.go | 2 +- backend/ent/schema/user_platform_quota.go | 2 +- backend/go.mod | 1 + backend/go.sum | 2 + backend/internal/domain/constants.go | 1 + .../internal/handler/admin/account_handler.go | 23 + .../handler/admin/channel_monitor_handler.go | 4 +- .../admin/channel_monitor_template_handler.go | 2 +- .../internal/handler/admin/group_handler.go | 6 +- .../handler/dto/account_mapper_redact_test.go | 12 + backend/internal/handler/gateway_handler.go | 57 +- .../handler/openai_bps_models_test.go | 191 ++++++ .../handler/openai_gateway_handler.go | 40 +- .../internal/repository/gateway_cache_bps.go | 37 ++ .../repository/gateway_cache_bps_test.go | 69 ++ .../internal/repository/scheduler_cache.go | 4 +- backend/internal/server/routes/gateway.go | 7 +- .../routes/gateway_model_allowlist_test.go | 4 +- backend/internal/server/routes/openai_bps.go | 27 + .../internal/server/routes/openai_bps_test.go | 34 + backend/internal/service/account.go | 8 +- backend/internal/service/account_service.go | 3 + .../internal/service/account_test_service.go | 3 + backend/internal/service/admin_account.go | 54 +- backend/internal/service/admin_group.go | 2 + .../service/channel_monitor_checker.go | 14 +- .../internal/service/channel_monitor_const.go | 7 +- .../service/channel_monitor_validate.go | 11 + backend/internal/service/channel_service.go | 2 +- .../internal/service/channel_service_test.go | 2 +- .../internal/service/composite_platform.go | 2 +- .../service/composite_platform_test.go | 2 +- backend/internal/service/domain_constants.go | 2 + backend/internal/service/gateway_service.go | 2 +- .../service/openai_account_scheduler.go | 3 + .../service/openai_bps_alignment_test.go | 320 +++++++++ .../internal/service/openai_bps_catalog.go | 40 ++ .../service/openai_bps_composite_catalog.go | 106 +++ .../service/openai_bps_credentials.go | 101 +++ .../service/openai_bps_custom_transport.go | 33 + .../internal/service/openai_bps_envelope.go | 248 +++++++ .../internal/service/openai_bps_gateway.go | 562 ++++++++++++++++ .../internal/service/openai_bps_protocol.go | 613 +++++++++++++++++ backend/internal/service/openai_bps_state.go | 230 +++++++ .../internal/service/openai_bps_structured.go | 159 +++++ .../service/openai_bps_structured_test.go | 184 ++++++ backend/internal/service/openai_bps_test.go | 623 ++++++++++++++++++ .../service/openai_bps_test_connection.go | 62 ++ backend/internal/service/openai_bps_turn.go | 51 ++ .../service/openai_codex_models_service.go | 26 +- .../service/openai_gateway_forward.go | 3 + .../service/openai_gateway_scheduling.go | 8 +- .../service/openai_gateway_service.go | 2 +- .../service/scheduler_snapshot_service.go | 6 +- .../migrations/245_openai_bps_platform.sql | 17 + .../openai_bps_platform_migration_test.go | 22 + changelog/1.1.5/CHANGELOG.md | 23 + docs/openai-bps-sources.md | 9 + docs/openai-bps.md | 78 +++ frontend/src/api/admin/channelMonitor.ts | 1 + frontend/src/api/admin/settings.ts | 4 +- frontend/src/api/admin/users.ts | 2 +- .../components/account/AccountUsageCell.vue | 9 +- .../components/account/CreateAccountModal.vue | 28 + .../components/account/EditAccountModal.vue | 21 + .../account/OpenAIBPSAccountFields.vue | 34 + .../__tests__/CreateAccountModal.spec.ts | 20 + .../__tests__/EditAccountModal.spec.ts | 15 + .../__tests__/OpenAIBPSAccountFields.spec.ts | 40 ++ .../admin/account/AccountActionMenu.vue | 2 +- .../admin/account/AccountTestModal.vue | 3 +- .../admin/monitor/MonitorFormDialog.vue | 16 +- .../monitor/MonitorTemplateManagerDialog.vue | 9 +- .../__tests__/UserPlatformQuotaModal.spec.ts | 16 +- .../src/components/common/PlatformIcon.vue | 2 +- .../components/common/PlatformTypeBadge.vue | 1 + frontend/src/components/keys/UseKeyModal.vue | 5 + .../keys/__tests__/UseKeyModal.spec.ts | 16 + .../components/user/UserPlatformQuotaCell.vue | 2 +- .../user/dashboard/UserDashboardStats.vue | 3 +- .../components/user/monitor/ProviderIcon.vue | 4 +- .../composables/useChannelMonitorFormat.ts | 1 + .../src/constants/__tests__/platforms.spec.ts | 1 + frontend/src/constants/channelMonitor.ts | 2 + frontend/src/constants/platforms.ts | 1 + .../src/i18n/locales/en/admin/accounts.ts | 13 + .../src/i18n/locales/zh/admin/accounts.ts | 13 + frontend/src/types/index.ts | 4 +- frontend/src/utils/keyGroupProviders.ts | 1 + frontend/src/utils/openaiBps.ts | 24 + frontend/src/utils/platformColors.ts | 16 + frontend/src/views/admin/AccountsView.vue | 4 +- frontend/src/views/admin/ChannelsView.vue | 4 +- frontend/src/views/admin/SettingsView.vue | 4 +- .../__tests__/ChannelMonitorView.grok.spec.ts | 2 +- 101 files changed, 4417 insertions(+), 110 deletions(-) create mode 100644 backend/internal/handler/openai_bps_models_test.go create mode 100644 backend/internal/repository/gateway_cache_bps.go create mode 100644 backend/internal/repository/gateway_cache_bps_test.go create mode 100644 backend/internal/server/routes/openai_bps.go create mode 100644 backend/internal/server/routes/openai_bps_test.go create mode 100644 backend/internal/service/openai_bps_alignment_test.go create mode 100644 backend/internal/service/openai_bps_catalog.go create mode 100644 backend/internal/service/openai_bps_composite_catalog.go create mode 100644 backend/internal/service/openai_bps_credentials.go create mode 100644 backend/internal/service/openai_bps_custom_transport.go create mode 100644 backend/internal/service/openai_bps_envelope.go create mode 100644 backend/internal/service/openai_bps_gateway.go create mode 100644 backend/internal/service/openai_bps_protocol.go create mode 100644 backend/internal/service/openai_bps_state.go create mode 100644 backend/internal/service/openai_bps_structured.go create mode 100644 backend/internal/service/openai_bps_structured_test.go create mode 100644 backend/internal/service/openai_bps_test.go create mode 100644 backend/internal/service/openai_bps_test_connection.go create mode 100644 backend/internal/service/openai_bps_turn.go create mode 100644 backend/migrations/245_openai_bps_platform.sql create mode 100644 backend/migrations/openai_bps_platform_migration_test.go create mode 100644 changelog/1.1.5/CHANGELOG.md create mode 100644 docs/openai-bps-sources.md create mode 100644 docs/openai-bps.md create mode 100644 frontend/src/components/account/OpenAIBPSAccountFields.vue create mode 100644 frontend/src/components/account/__tests__/OpenAIBPSAccountFields.spec.ts create mode 100644 frontend/src/utils/openaiBps.ts diff --git a/.gitignore b/.gitignore index b576f07e3..ea3076a05 100644 --- a/.gitignore +++ b/.gitignore @@ -139,6 +139,8 @@ docs/* !docs/ASYNC_IMAGE_TASKS.md !docs/BATCH_IMAGE_MVP.md !docs/COMPOSITE_GROUPS.md +!docs/openai-bps.md +!docs/openai-bps-sources.md !docs/PLUGIN_DEVELOPMENT.md !docs/channel-monitor-v2-safe-defaults.md !docs/CODEX_PROBE_TEMPLATE.md diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 65087b4f5..e25d8d9f3 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -1.1.4 +1.1.5 diff --git a/backend/ent/channelmonitor/channelmonitor.go b/backend/ent/channelmonitor/channelmonitor.go index 5fa6966c4..e9c8327cf 100644 --- a/backend/ent/channelmonitor/channelmonitor.go +++ b/backend/ent/channelmonitor/channelmonitor.go @@ -184,6 +184,7 @@ const ( ProviderDeepseek Provider = "deepseek" ProviderMinimax Provider = "minimax" ProviderOpencodeGo Provider = "opencode_go" + ProviderOpenaiBps Provider = "openai_bps" ) func (pr Provider) String() string { @@ -193,7 +194,7 @@ func (pr Provider) String() string { // ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save. func ProviderValidator(pr Provider) error { switch pr { - case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo: + case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo, ProviderOpenaiBps: return nil default: return fmt.Errorf("channelmonitor: invalid enum value for provider field: %q", pr) diff --git a/backend/ent/channelmonitorrequesttemplate/channelmonitorrequesttemplate.go b/backend/ent/channelmonitorrequesttemplate/channelmonitorrequesttemplate.go index d5ce2cc89..22cf8a869 100644 --- a/backend/ent/channelmonitorrequesttemplate/channelmonitorrequesttemplate.go +++ b/backend/ent/channelmonitorrequesttemplate/channelmonitorrequesttemplate.go @@ -110,6 +110,7 @@ const ( ProviderDeepseek Provider = "deepseek" ProviderMinimax Provider = "minimax" ProviderOpencodeGo Provider = "opencode_go" + ProviderOpenaiBps Provider = "openai_bps" ) func (pr Provider) String() string { @@ -119,7 +120,7 @@ func (pr Provider) String() string { // ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save. func ProviderValidator(pr Provider) error { switch pr { - case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo: + case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo, ProviderOpenaiBps: return nil default: return fmt.Errorf("channelmonitorrequesttemplate: invalid enum value for provider field: %q", pr) diff --git a/backend/ent/migrate/schema.go b/backend/ent/migrate/schema.go index ceefcc684..22caddf4f 100644 --- a/backend/ent/migrate/schema.go +++ b/backend/ent/migrate/schema.go @@ -623,7 +623,7 @@ var ( {Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "name", Type: field.TypeString, Size: 100}, - {Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"}}, + {Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "openai_bps"}}, {Name: "check_mode", Type: field.TypeString, Size: 32, Default: "probe"}, {Name: "account_id", Type: field.TypeInt64, Nullable: true}, {Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"}, @@ -776,7 +776,7 @@ var ( {Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "name", Type: field.TypeString, Size: 100}, - {Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"}}, + {Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "openai_bps"}}, {Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"}, {Name: "description", Type: field.TypeString, Nullable: true, Size: 500, Default: ""}, {Name: "extra_headers", Type: field.TypeJSON}, diff --git a/backend/ent/schema/channel_monitor.go b/backend/ent/schema/channel_monitor.go index 5c7dc29fe..4dc8825a2 100644 --- a/backend/ent/schema/channel_monitor.go +++ b/backend/ent/schema/channel_monitor.go @@ -36,7 +36,7 @@ func (ChannelMonitor) Fields() []ent.Field { MaxLen(100), field.Enum("provider"). Values("openai", "anthropic", "gemini", "grok", - "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"), + "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "openai_bps"), // check_mode: 'probe' | 'quota' | 'quota_probe' // probe - LLM 探活(默认,原有行为) // quota - 仅查关联账号的用量/余额(零 LLM 成本;endpoint/api_key 可空) diff --git a/backend/ent/schema/channel_monitor_request_template.go b/backend/ent/schema/channel_monitor_request_template.go index 7970dacb3..2b1926b7a 100644 --- a/backend/ent/schema/channel_monitor_request_template.go +++ b/backend/ent/schema/channel_monitor_request_template.go @@ -40,7 +40,7 @@ func (ChannelMonitorRequestTemplate) Fields() []ent.Field { MaxLen(100), field.Enum("provider"). Values("openai", "anthropic", "gemini", "grok", - "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"), + "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "openai_bps"), field.String("api_mode"). Default("chat_completions"). MaxLen(32). diff --git a/backend/ent/schema/user_platform_quota.go b/backend/ent/schema/user_platform_quota.go index f8e42a0cd..9c30a8976 100644 --- a/backend/ent/schema/user_platform_quota.go +++ b/backend/ent/schema/user_platform_quota.go @@ -42,7 +42,7 @@ func (UserPlatformQuota) Fields() []ent.Field { // 此处为 ent 构建期约束,需与 service.AllowedQuotaPlatforms 保持同步。 switch s { case "anthropic", "openai", "gemini", "antigravity", "grok", - "kimi", "zhipu", "deepseek", "minimax", "opencode_go": + "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "openai_bps": return nil default: return fmt.Errorf("platform %q is not allowed", s) diff --git a/backend/go.mod b/backend/go.mod index 5510b5250..11861909c 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -34,6 +34,7 @@ require ( github.com/redis/go-redis/v9 v9.22.0 github.com/refraction-networking/utls v1.8.2 github.com/robfig/cron/v3 v3.0.1 + github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 github.com/shirou/gopsutil/v4 v4.25.6 github.com/shopspring/decimal v1.4.0 github.com/smartwalle/alipay/v3 v3.2.29 diff --git a/backend/go.sum b/backend/go.sum index caf01c3b6..191db3cc5 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -405,6 +405,8 @@ github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6ke github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 h1:lZUw3E0/J3roVtGQ+SCrUrg3ON6NgVqpn3+iol9aGu4= +github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY= github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= github.com/shirou/gopsutil/v4 v4.25.6 h1:kLysI2JsKorfaFPcYmcJqbzROzsBWEOAtw6A7dIfqXs= diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go index e82c1df1d..40028c68d 100644 --- a/backend/internal/domain/constants.go +++ b/backend/internal/domain/constants.go @@ -20,6 +20,7 @@ const ( const ( PlatformAnthropic = "anthropic" PlatformOpenAI = "openai" + PlatformOpenAIBPS = "openai_bps" PlatformGemini = "gemini" PlatformAntigravity = "antigravity" PlatformGrok = "grok" diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index 50b7b68c0..1277c9949 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -1452,6 +1452,9 @@ func (h *AccountHandler) PreviewFromCRS(c *gin.Context) { // refreshSingleAccount refreshes credentials for a single OAuth account. // Returns (updatedAccount, warning, error) where warning is used for Antigravity ProjectIDMissing scenario. func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *service.Account) (*service.Account, string, error) { + if account.IsOpenAIBPS() { + return nil, "", infraerrors.BadRequest("BPS_MANUAL_TOKEN_ONLY", "Replace access_token in the BPS account settings; automatic refresh is unsupported") + } if !account.IsOAuth() { return nil, "", infraerrors.BadRequest("NOT_OAUTH", "cannot refresh non-OAuth account") } @@ -1666,6 +1669,10 @@ func (h *AccountHandler) ApplyOAuthCredentials(c *gin.Context) { response.NotFound(c, "Account not found") return } + if existing.IsOpenAIBPS() { + response.BadRequest(c, "Replace access_token through the BPS account editor") + return + } if !existing.IsOAuth() { response.ErrorFrom(c, infraerrors.BadRequest("NOT_OAUTH", "cannot apply oauth credentials to non-OAuth account")) return @@ -2853,6 +2860,22 @@ func (h *AccountHandler) GetAvailableModels(c *gin.Context) { return } + if account.IsOpenAIBPS() { + ids := service.OpenAIBPSDefaultModels() + if mapping := account.GetModelMapping(); len(mapping) > 0 { + ids = make([]string, 0, len(mapping)) + for id := range mapping { + ids = append(ids, id) + } + } + sort.Strings(ids) + models := make([]openai.Model, 0, len(ids)) + for _, id := range ids { + models = append(models, openai.Model{ID: id, Object: "model", Type: "model", DisplayName: id}) + } + response.Success(c, models) + return + } // Handle OpenAI accounts if account.IsOpenAI() { // Prefer the shared, account-keyed upstream catalog. If discovery fails, diff --git a/backend/internal/handler/admin/channel_monitor_handler.go b/backend/internal/handler/admin/channel_monitor_handler.go index e4728345e..df4a9b654 100644 --- a/backend/internal/handler/admin/channel_monitor_handler.go +++ b/backend/internal/handler/admin/channel_monitor_handler.go @@ -40,7 +40,7 @@ func NewChannelMonitorHandler(monitorService *service.ChannelMonitorService) *Ch type channelMonitorCreateRequest struct { Name string `json:"name" binding:"required,max=100"` - Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go"` + Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go openai_bps"` APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"` Endpoint string `json:"endpoint" binding:"omitempty,max=500"` APIKey string `json:"api_key" binding:"omitempty,max=2000"` @@ -64,7 +64,7 @@ type channelMonitorCreateRequest struct { type channelMonitorUpdateRequest struct { Name *string `json:"name" binding:"omitempty,max=100"` - Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go"` + Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go openai_bps"` APIMode *string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"` Endpoint *string `json:"endpoint" binding:"omitempty,max=500"` APIKey *string `json:"api_key" binding:"omitempty,max=2000"` diff --git a/backend/internal/handler/admin/channel_monitor_template_handler.go b/backend/internal/handler/admin/channel_monitor_template_handler.go index 62d8bfbbe..54e440adb 100644 --- a/backend/internal/handler/admin/channel_monitor_template_handler.go +++ b/backend/internal/handler/admin/channel_monitor_template_handler.go @@ -26,7 +26,7 @@ func NewChannelMonitorRequestTemplateHandler(templateService *service.ChannelMon type channelMonitorTemplateCreateRequest struct { Name string `json:"name" binding:"required,max=100"` - Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok"` + Provider string `json:"provider" binding:"required,oneof=openai openai_bps anthropic gemini grok"` APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"` Description string `json:"description" binding:"max=500"` ExtraHeaders map[string]string `json:"extra_headers"` diff --git a/backend/internal/handler/admin/group_handler.go b/backend/internal/handler/admin/group_handler.go index d15ac9fb1..2d0cffcd2 100644 --- a/backend/internal/handler/admin/group_handler.go +++ b/backend/internal/handler/admin/group_handler.go @@ -184,7 +184,7 @@ func sanitizeUpdateGroupRequestForSimpleMode(req *UpdateGroupRequest) { type CreateGroupRequest struct { Name string `json:"name" binding:"required"` Description string `json:"description"` - Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go composite"` + Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go openai_bps composite"` RateMultiplier float64 `json:"rate_multiplier"` IsExclusive bool `json:"is_exclusive"` SubscriptionType string `json:"subscription_type" binding:"omitempty,oneof=standard subscription"` @@ -258,7 +258,7 @@ type CreateGroupRequest struct { type UpdateGroupRequest struct { Name string `json:"name"` Description *string `json:"description"` - Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go composite"` + Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go openai_bps composite"` RateMultiplier *float64 `json:"rate_multiplier"` IsExclusive *bool `json:"is_exclusive"` Status string `json:"status" binding:"omitempty,oneof=active inactive"` @@ -332,7 +332,7 @@ type UpdateGroupRequest struct { type CompositeRouteRequest struct { PublicModel string `json:"public_model" binding:"required"` MatchType string `json:"match_type" binding:"omitempty,oneof=exact prefix"` - TargetPlatform string `json:"target_platform" binding:"required,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go"` + TargetPlatform string `json:"target_platform" binding:"required,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go openai_bps"` UpstreamModel string `json:"upstream_model"` Endpoint string `json:"endpoint" binding:"omitempty,oneof=any messages count_tokens responses chat_completions embeddings images gemini"` Priority int `json:"priority"` diff --git a/backend/internal/handler/dto/account_mapper_redact_test.go b/backend/internal/handler/dto/account_mapper_redact_test.go index e3cbf2fbd..affa69307 100644 --- a/backend/internal/handler/dto/account_mapper_redact_test.go +++ b/backend/internal/handler/dto/account_mapper_redact_test.go @@ -128,3 +128,15 @@ func TestAccountFromServiceShallow_NilCredentialsOmitsStatus(t *testing.T) { require.Nil(t, got.Credentials) require.Nil(t, got.CredentialsStatus) } + +func TestOpenAIBPSAccountDTORedactsTokenKeepsExpiry(t *testing.T) { + src := &service.Account{ID: 42, Platform: service.PlatformOpenAIBPS, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": "bps-test-secret", "chatgpt_account_id": "workspace", "expires_at": "2026-10-01T00:00:00Z"}} + dto := AccountFromServiceShallow(src) + require.NotContains(t, dto.Credentials, "access_token") + require.True(t, dto.CredentialsStatus["has_access_token"]) + require.Equal(t, "workspace", dto.Credentials["chatgpt_account_id"]) + require.Equal(t, "2026-10-01T00:00:00Z", dto.Credentials["expires_at"]) + data, err := json.Marshal(dto) + require.NoError(t, err) + require.NotContains(t, string(data), "bps-test-secret") +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 6a522c577..70d6f95c8 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -1141,16 +1141,20 @@ func (h *GatewayHandler) Models(c *gin.Context) { } if platform == service.PlatformComposite { - availableModels := h.compositeAvailableModels(c.Request.Context(), groupID) + availableModels, err := h.compositeAvailableModels(c.Request.Context(), groupID) + if err != nil { + h.errorResponse(c, http.StatusInternalServerError, "api_error", "Failed to load composite model catalog") + return + } if apiKey != nil && apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() { source := availableModels - if len(source) == 0 { + if source == nil { source = defaultModelIDsForPlatform(service.PlatformComposite) } writeAllowlistedModelsList(c, service.PlatformComposite, apiKey.Group.ModelAllowlist.FilterForListing(source)) return } - if len(availableModels) > 0 { + if availableModels != nil { writeModelsList(c, service.PlatformComposite, availableModels) return } @@ -1171,6 +1175,10 @@ func (h *GatewayHandler) Models(c *gin.Context) { return } + if platform == service.PlatformOpenAIBPS { + writeModelsList(c, platform, service.OpenAIBPSDefaultModels()) + return + } // Fallback to default models if platform == service.PlatformOpenAI { writeModelsListResponse(c, openai.DefaultModels) @@ -1203,7 +1211,11 @@ func (h *GatewayHandler) CodexModels(c *gin.Context) { if value, exists := middleware2.GetForcePlatformFromContext(c); exists { forcedPlatform = strings.TrimSpace(value) } - modelIDs := h.codexModelIDsForGroup(c.Request.Context(), apiKey.Group, forcedPlatform) + modelIDs, err := h.codexModelIDsForGroup(c.Request.Context(), apiKey.Group, forcedPlatform) + if err != nil { + h.errorResponse(c, http.StatusInternalServerError, "api_error", "Failed to load composite model catalog") + return + } modelIDs = service.FilterCodexModelIDsForGroup(modelIDs, apiKey.Group) body, err := h.gatewayService.BuildCodexModelsManifestForGroup( c.Request.Context(), @@ -1225,9 +1237,9 @@ func (h *GatewayHandler) CodexModels(c *gin.Context) { c.Data(http.StatusOK, "application/json", body) } -func (h *GatewayHandler) codexModelIDsForGroup(ctx context.Context, group *service.Group, platformOverride string) []string { +func (h *GatewayHandler) codexModelIDsForGroup(ctx context.Context, group *service.Group, platformOverride string) ([]string, error) { if h == nil || h.gatewayService == nil || group == nil { - return nil + return nil, nil } groupID := &group.ID @@ -1236,35 +1248,38 @@ func (h *GatewayHandler) codexModelIDsForGroup(ctx context.Context, group *servi platform = group.Platform } if platform == service.PlatformComposite { - availableModels := h.compositeAvailableModels(ctx, groupID) + availableModels, err := h.compositeAvailableModels(ctx, groupID) + if err != nil { + return nil, err + } fallbackModels := defaultCodexModelIDsForPlatform(service.PlatformComposite) if group.ModelAllowlistEnabled() { source := availableModels - if len(source) == 0 { + if source == nil { source = fallbackModels } - return group.ModelAllowlist.FilterForListing(source) + return group.ModelAllowlist.FilterForListing(source), nil } - if len(availableModels) > 0 { - return availableModels + if availableModels != nil { + return availableModels, nil } - return fallbackModels + return fallbackModels, nil } availableModels := h.gatewayService.GetAvailableModels(ctx, groupID, platform) fallbackModels := defaultCodexModelIDsForPlatform(platform) if group.ModelAllowlistEnabled() { - return group.ModelAllowlist.FilterForListing(modelListingSource(platform, availableModels, fallbackModels)) + return group.ModelAllowlist.FilterForListing(modelListingSource(platform, availableModels, fallbackModels)), nil } if len(availableModels) > 0 { - return availableModels + return availableModels, nil } - return fallbackModels + return fallbackModels, nil } -func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID *int64) []string { +func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID *int64) ([]string, error) { if h == nil || h.gatewayService == nil { - return nil + return nil, nil } seen := make(map[string]struct{}) models := make([]string, 0) @@ -1290,11 +1305,11 @@ func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID * models = append(models, model) } } - return models + return h.gatewayService.CompleteCompositeBPSModelCatalog(ctx, groupID, models) } func writeModelsList(c *gin.Context, platform string, modelIDs []string) { - if platform == service.PlatformOpenAI { + if platform == service.PlatformOpenAI || platform == service.PlatformOpenAIBPS { writeOpenAIModelsList(c, modelIDs) return } @@ -1315,7 +1330,7 @@ func writeModelsList(c *gin.Context, platform string, modelIDs []string) { } func writeAllowlistedModelsList(c *gin.Context, platform string, modelIDs []string) { - if platform == service.PlatformOpenAI { + if platform == service.PlatformOpenAI || platform == service.PlatformOpenAIBPS { writeOpenAIModelsList(c, modelIDs) return } @@ -1432,6 +1447,8 @@ func defaultCodexModelIDsForPlatform(platform string) []string { func defaultModelIDsForPlatform(platform string) []string { switch platform { + case service.PlatformOpenAIBPS: + return service.OpenAIBPSDefaultModels() case service.PlatformOpenAI: return openai.DefaultModelIDs() case service.PlatformGemini: diff --git a/backend/internal/handler/openai_bps_models_test.go b/backend/internal/handler/openai_bps_models_test.go new file mode 100644 index 000000000..193b75126 --- /dev/null +++ b/backend/internal/handler/openai_bps_models_test.go @@ -0,0 +1,191 @@ +package handler + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type bpsCatalogRouteRepo struct { + service.CompositeModelRouteRepository + routes []service.CompositeModelRoute + err error +} + +func (r bpsCatalogRouteRepo) ListByGroup(_ context.Context, _ int64, all bool) ([]service.CompositeModelRoute, error) { + if r.err != nil { + return nil, r.err + } + var result []service.CompositeModelRoute + for _, route := range r.routes { + if all || route.Enabled { + result = append(result, route) + } + } + return result, nil +} +func bpsCatalogAccount() service.Account { + return service.Account{ID: 1, Platform: service.PlatformOpenAIBPS, Type: service.AccountTypeOAuth, Status: service.StatusActive, Schedulable: true, Credentials: map[string]any{"access_token": "test-token", "chatgpt_account_id": "workspace", "model_mapping": map[string]any{"gpt-6-astra": "gpt-6-astra", "gpt-5.6-sol": "gpt-5.6-sol", "bps-prefix": "gpt-6-astra"}}} +} +func bpsCatalogHandler(accounts []service.Account, routes bpsCatalogRouteRepo) *GatewayHandler { + repo := &gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{91: accounts}} + resolver := service.NewCompositeRouteResolver(routes) + return &GatewayHandler{gatewayService: service.NewGatewayService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, resolver, nil, nil)} +} +func bpsCatalogContext(group *service.Group, path string) (*gin.Context, *httptest.ResponseRecorder) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, path, nil) + c.Set("api_key", &service.APIKey{Group: group}) + return c, rec +} +func bpsCatalogRoute() service.CompositeModelRoute { + return service.CompositeModelRoute{ID: 1, GroupID: 91, PublicModel: "bps-astra", MatchType: service.CompositeRouteMatchExact, TargetPlatform: service.PlatformOpenAIBPS, UpstreamModel: "gpt-6-astra", Endpoint: service.CompositeRouteEndpointResponses, Enabled: true} +} +func TestOpenAIBPSModelsExplicitCompositeAlias(t *testing.T) { + account := bpsCatalogAccount() + route := bpsCatalogRoute() + h := bpsCatalogHandler([]service.Account{account}, bpsCatalogRouteRepo{routes: []service.CompositeModelRoute{route}}) + group := &service.Group{ID: 91, Platform: service.PlatformComposite} + ids, err := h.codexModelIDsForGroup(context.Background(), group, "") + require.NoError(t, err) + require.Equal(t, []string{"bps-astra"}, ids) + c, rec := bpsCatalogContext(group, "/v1/models") + h.Models(c) + require.Equal(t, 200, rec.Code) + require.Equal(t, "bps-astra", gjson.Get(rec.Body.String(), "data.0.id").String()) + require.Len(t, gjson.Get(rec.Body.String(), "data").Array(), 1) + c, rec = bpsCatalogContext(group, "/models?client_version=0.147.0") + h.CodexModels(c) + require.Equal(t, 200, rec.Code) + require.Equal(t, "bps-astra", gjson.Get(rec.Body.String(), "models.0.slug").String()) + require.False(t, gjson.Get(rec.Body.String(), "models.0.supports_parallel_tool_calls").Bool()) + require.False(t, gjson.Get(rec.Body.String(), "models.0.prefer_websockets").Bool()) + require.Len(t, gjson.Get(rec.Body.String(), "models.0.supported_reasoning_levels").Array(), 4) + group.ModelAllowlist = service.GroupModelAllowlist{Enabled: true, Models: []string{"missing"}} + c, rec = bpsCatalogContext(group, "/v1/models") + h.Models(c) + require.Empty(t, gjson.Get(rec.Body.String(), "data").Array()) +} + +func TestOpenAIBPSModelsEmptyCompositeStaysEmpty(t *testing.T) { + for _, mode := range []string{"disabled account", "expired token", "disabled route", "no route", "wrong endpoint", "model denied", "no account"} { + t.Run(mode, func(t *testing.T) { + a := bpsCatalogAccount() + route := bpsCatalogRoute() + accounts := []service.Account{a} + routes := []service.CompositeModelRoute{route} + switch mode { + case "disabled account": + accounts[0].Status = "disabled" + case "expired token": + accounts[0].Credentials["expires_at"] = time.Now().Add(-time.Hour).Format(time.RFC3339) + case "disabled route": + routes[0].Enabled = false + case "no route": + routes = nil + case "wrong endpoint": + routes[0].Endpoint = service.CompositeRouteEndpointChatCompletions + case "model denied": + routes[0].UpstreamModel = "unavailable-model" + case "no account": + accounts = nil + } + h := bpsCatalogHandler(accounts, bpsCatalogRouteRepo{routes: routes}) + group := &service.Group{ID: 91, Platform: service.PlatformComposite} + for _, allowlist := range []bool{false, true} { + group.ModelAllowlist = service.GroupModelAllowlist{Enabled: allowlist, Models: []string{"gpt-*", "claude-*", "bps-*"}} + c, rec := bpsCatalogContext(group, "/v1/models") + h.Models(c) + require.Equal(t, 200, rec.Code) + require.Empty(t, gjson.Get(rec.Body.String(), "data").Array()) + c, rec = bpsCatalogContext(group, "/models?client_version=0.147.0") + h.CodexModels(c) + require.Equal(t, 200, rec.Code) + require.Empty(t, gjson.Get(rec.Body.String(), "models").Array()) + } + }) + } +} + +func TestOpenAIBPSModelsPrefixPrecedenceAndCatalogErrors(t *testing.T) { + route := bpsCatalogRoute() + route.MatchType = service.CompositeRouteMatchPrefix + route.PublicModel = "bps-" + route.UpstreamModel = "" + exact := bpsCatalogRoute() + exact.PublicModel = "bps-prefix" + exact.UpstreamModel = "not-supported" + h := bpsCatalogHandler([]service.Account{bpsCatalogAccount()}, bpsCatalogRouteRepo{routes: []service.CompositeModelRoute{route}}) + group := &service.Group{ID: 91, Platform: service.PlatformComposite} + ids, err := h.codexModelIDsForGroup(context.Background(), group, "") + require.NoError(t, err) + require.Equal(t, []string{"bps-prefix"}, ids) + h = bpsCatalogHandler([]service.Account{bpsCatalogAccount()}, bpsCatalogRouteRepo{routes: []service.CompositeModelRoute{route, exact}}) + ids, err = h.codexModelIDsForGroup(context.Background(), group, "") + require.NoError(t, err) + require.Empty(t, ids) + h = bpsCatalogHandler([]service.Account{bpsCatalogAccount()}, bpsCatalogRouteRepo{err: errors.New("database unavailable")}) + c, rec := bpsCatalogContext(group, "/v1/models") + h.Models(c) + require.Equal(t, 500, rec.Code) + require.NotContains(t, rec.Body.String(), "claude-") +} + +func TestOpenAIBPSModelsOpenAIShape(t *testing.T) { + for _, mode := range []string{"default", "mapped", "allowlist", "retrieve"} { + t.Run(mode, func(t *testing.T) { + a := bpsCatalogAccount() + a.Credentials["model_mapping"] = map[string]any{"my-astra": "gpt-6-astra"} + accounts := []service.Account{a} + if mode == "default" { + accounts = nil + } + h := bpsCatalogHandler(accounts, bpsCatalogRouteRepo{}) + group := &service.Group{ID: 91, Platform: service.PlatformOpenAIBPS} + if mode == "allowlist" { + group.ModelAllowlist = service.GroupModelAllowlist{Enabled: true, Models: []string{"my-astra"}} + } + c, rec := bpsCatalogContext(group, "/v1/models") + if mode == "retrieve" { + c.Params = gin.Params{{Key: "model", Value: "my-astra"}} + } + h.Models(c) + require.Equal(t, 200, rec.Code) + var data map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &data)) + var item map[string]any + if mode == "retrieve" { + item = data + } else { + item = data["data"].([]any)[0].(map[string]any) + } + require.Equal(t, "model", item["object"]) + require.NotEmpty(t, item["owned_by"]) + require.NotZero(t, item["created"]) + require.NotContains(t, item, "created_at") + }) + } +} + +func TestOpenAIBPSModelsDeduplicateNormalizedAliases(t *testing.T) { + first := bpsCatalogRoute() + second := first + second.ID = 2 + second.PublicModel = " bps-astra " + h := bpsCatalogHandler([]service.Account{bpsCatalogAccount()}, bpsCatalogRouteRepo{routes: []service.CompositeModelRoute{first, second}}) + group := &service.Group{ID: 91, Platform: service.PlatformComposite} + ids, err := h.codexModelIDsForGroup(context.Background(), group, "") + require.NoError(t, err) + require.Equal(t, []string{"bps-astra"}, ids) +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 8b59d134f..9dff5d8ff 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -288,7 +288,7 @@ func openAIResponsesRequiredCapability(imageIntent bool, platform string) servic // required by an image or Responses request. needsResponses includes both the // legacy /responses/compact endpoint and native remote compaction v2. func openAIResponsesRequiredCapabilityForRequest(imageIntent bool, needsResponses bool, platform string) service.OpenAIEndpointCapability { - if needsResponses && platform == service.PlatformOpenAI { + if platform == service.PlatformOpenAIBPS || (needsResponses && platform == service.PlatformOpenAI) { return service.OpenAIEndpointCapabilityResponses } return openAIResponsesRequiredCapability(imageIntent, platform) @@ -323,7 +323,7 @@ func openAICompatibleTextTargetAllowed(c *gin.Context, apiKey *service.APIKey, m return compositeTargetPlatformAllowed(c, apiKey, model, service.PlatformOpenAI, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, - service.PlatformMiniMax, service.PlatformOpenCodeGo) + service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOpenAIBPS) } // isResponsesWebSocketCompositePlatform 限定 composite 分组在 Responses WebSocket @@ -428,9 +428,11 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { setOpsRequestContext(c, "", false) sessionHashBody := body - body, ok = h.normalizeOpenAIResponsesCompactRequest(c, reqLog, body) - if !ok { - return + if openAICompatibleRequestPlatform(c.Request.Context(), apiKey) != service.PlatformOpenAIBPS { + body, ok = h.normalizeOpenAIResponsesCompactRequest(c, reqLog, body) + if !ok { + return + } } legacyCompact := service.IsOpenAIResponsesCompactPath(c) nativeV2 := isBareOpenAIResponsesPath(c) && isOpenAIRemoteCompactionV2Request(body) @@ -464,11 +466,13 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups") return } - if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil { - respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse) - return - } else if changed { - body = cappedBody + if openAICompatibleRequestPlatform(c.Request.Context(), apiKey) != service.PlatformOpenAIBPS { + if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil { + respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse) + return + } else if changed { + body = cappedBody + } } if normalizedBody, changed := normalizeCodexAutomationBootstrap(body); changed { body = normalizedBody @@ -494,6 +498,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { } reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream)) previousResponseID := strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) + if previousResponseID != "" && openAICompatibleRequestPlatform(c.Request.Context(), apiKey) == service.PlatformOpenAIBPS { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "BPS requires complete input history; previous_response_id is not supported") + return + } if previousResponseID != "" { previousResponseIDKind := service.ClassifyOpenAIPreviousResponseIDKind(previousResponseID) reqLog = reqLog.With( @@ -570,7 +578,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { )) // 提前校验 function_call_output 是否具备可关联上下文,避免上游 400。 - if !h.validateFunctionCallOutputRequest(c, body, reqLog) { + if openAICompatibleRequestPlatform(c.Request.Context(), apiKey) != service.PlatformOpenAIBPS && !h.validateFunctionCallOutputRequest(c, body, reqLog) { return } @@ -582,6 +590,12 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // Get subscription info (may be nil) subscription, _ := middleware2.GetSubscriptionFromContext(c) requestPlatform := openAICompatibleRequestPlatform(c.Request.Context(), apiKey) + if requestPlatform == service.PlatformOpenAIBPS { + if err := h.gatewayService.PrepareOpenAIBPSRouting(c, sessionHashBody); err != nil { + service.WriteOpenAIBPSError(c, err) + return + } + } service.SetOpsLatencyMs(c, service.OpsAuthLatencyMsKey, time.Since(requestStart).Milliseconds()) routingStart := time.Now() @@ -673,6 +687,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { zap.Error(openAICompatibleSelectionErrorForLog(err, requestPlatform)), zap.Int("excluded_account_count", len(failedAccountIDs)), ) + if requestPlatform == service.PlatformOpenAIBPS && service.OpenAIBPSHasBinding(c.Request.Context()) { + service.WriteOpenAIBPSAccountUnavailable(c) + return + } if len(failedAccountIDs) == 0 { if legacyCompact && errors.Is(err, service.ErrNoAvailableCompactAccounts) { markOpsRoutingCapacityLimitedIfNoAvailable(c, err) diff --git a/backend/internal/repository/gateway_cache_bps.go b/backend/internal/repository/gateway_cache_bps.go new file mode 100644 index 000000000..4411735be --- /dev/null +++ b/backend/internal/repository/gateway_cache_bps.go @@ -0,0 +1,37 @@ +package repository + +import ( + "context" + "errors" + + "github.com/MACOS-DO/sub4api/internal/service" + "github.com/redis/go-redis/v9" +) + +var _ service.OpenAIBPSStateStore = (*gatewayCache)(nil) + +func (c *gatewayCache) BPSGet(ctx context.Context, key string) ([]byte, error) { + data, err := c.rdb.GetEx(ctx, key, service.OpenAIBPSStateTTL).Bytes() + if errors.Is(err, redis.Nil) { + return nil, nil + } + return data, err +} +func (c *gatewayCache) BPSPut(ctx context.Context, key string, data []byte) error { + return c.rdb.Set(ctx, key, data, service.OpenAIBPSStateTTL).Err() +} + +var bpsBindScript = redis.NewScript(` +local current=redis.call('GET',KEYS[1]) +if not current then + redis.call('SET',KEYS[1],ARGV[1],'PX',ARGV[2]) + return ARGV[1] +end +redis.call('PEXPIRE',KEYS[1],ARGV[2]) +return current +`) + +func (c *gatewayCache) BPSBind(ctx context.Context, key string, data []byte) ([]byte, error) { + v, e := bpsBindScript.Run(ctx, c.rdb, []string{key}, data, service.OpenAIBPSStateTTL.Milliseconds()).Text() + return []byte(v), e +} diff --git a/backend/internal/repository/gateway_cache_bps_test.go b/backend/internal/repository/gateway_cache_bps_test.go new file mode 100644 index 000000000..8b5e8fd4c --- /dev/null +++ b/backend/internal/repository/gateway_cache_bps_test.go @@ -0,0 +1,69 @@ +package repository + +import ( + "context" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/internal/service" + "github.com/alicebob/miniredis/v2" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +func TestOpenAIBPSRedisCrossInstanceAndExpiry(t *testing.T) { + server := miniredis.RunT(t) + ctx := context.Background() + connect := func() *gatewayCache { + client := redis.NewClient(&redis.Options{Addr: server.Addr()}) + t.Cleanup(func() { _ = client.Close() }) + return &gatewayCache{rdb: client} + } + first := connect() + second := connect() + key := "openai_bps:tenant-session:session" + binding := []byte(`{"account_id":42,"identity":"workspace"}`) + got, err := first.BPSBind(ctx, key, binding) + require.NoError(t, err) + require.Equal(t, binding, got) + got, err = second.BPSBind(ctx, key, []byte(`{"account_id":99}`)) + require.NoError(t, err) + require.Equal(t, binding, got) + require.NoError(t, first.BPSPut(ctx, key+":call:1", []byte(`{"arguments":"original OfficeJS envelope"}`))) + // Reconnect simulates a fresh process with no local state. + restarted := connect() + got, err = restarted.BPSGet(ctx, key+":call:1") + require.NoError(t, err) + require.Contains(t, string(got), "original OfficeJS envelope") + got, err = second.BPSGet(ctx, "openai_bps:another-tenant:session") + require.NoError(t, err) + require.Empty(t, got) + server.FastForward(service.OpenAIBPSStateTTL - time.Hour) + _, err = restarted.BPSGet(ctx, key) + require.NoError(t, err) + server.FastForward(2 * time.Hour) + got, err = second.BPSGet(ctx, key) + require.NoError(t, err) + require.Equal(t, binding, got) + got, err = second.BPSGet(ctx, key+":call:1") + require.NoError(t, err) + require.Empty(t, got) + server.FastForward(service.OpenAIBPSStateTTL + time.Second) + got, err = first.BPSGet(ctx, key) + require.NoError(t, err) + require.Empty(t, got) +} + +func TestOpenAIBPSSchedulerMetadataKeepsBindingAndExpiry(t *testing.T) { + expiry := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + account := service.Account{ID: 42, Platform: service.PlatformOpenAIBPS, Type: service.AccountTypeOAuth, Status: service.StatusActive, Schedulable: true, Credentials: map[string]any{"access_token": "private-token", "refresh_token": "unused-private-token", "chatgpt_account_id": "workspace-42", "expires_at": expiry, "model_mapping": map[string]any{"gpt-6-astra": "gpt-6-astra"}}} + metadata := buildSchedulerMetadataAccount(account) + require.Equal(t, "workspace-42", metadata.GetCredential("chatgpt_account_id")) + require.Equal(t, expiry, metadata.GetCredential("expires_at")) + require.True(t, metadata.IsSchedulable()) + require.NotContains(t, metadata.Credentials, "access_token") + require.NotContains(t, metadata.Credentials, "refresh_token") + account.Credentials["expires_at"] = time.Now().Add(-time.Hour).UTC().Format(time.RFC3339) + expiredMetadata := buildSchedulerMetadataAccount(account) + require.False(t, expiredMetadata.IsSchedulable()) +} diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index de72dff86..757cb5cf8 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -997,7 +997,9 @@ func filterSchedulerCredentials(credentials map[string]any) map[string]any { } // Candidate-list admission evaluates the account override before hydrating // the full account. Dropping it silently falls back to the platform threshold. - keys := []string{"model_mapping", "compact_model_mapping", "api_key", "project_id", "oauth_type", "plan_type", "account_scheduling_threshold"} + // BPS admission also needs workspace identity and JWT expiry before hydration; + // neither access_token nor refresh_token belongs in this metadata projection. + keys := []string{"model_mapping", "compact_model_mapping", "api_key", "project_id", "oauth_type", "plan_type", "account_scheduling_threshold", "chatgpt_account_id", "expires_at"} filtered := make(map[string]any) for _, key := range keys { if value, ok := credentials[key]; ok && value != nil { diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 2760bd44b..6b779c3ab 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -47,7 +47,7 @@ func RegisterGatewayRoutes( isOpenAIResponsesCompatibleGatewayPlatform := func(c *gin.Context) bool { switch getGroupPlatform(c) { - case service.PlatformOpenAI, service.PlatformGrok, + case service.PlatformOpenAI, service.PlatformOpenAIBPS, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo: // 国产 OpenAI 兼容供应商与 openai/grok 一样经 OpenAI 网关转发。 @@ -192,6 +192,7 @@ func RegisterGatewayRoutes( gateway.GET("/sub2api/billing", h.Gateway.KeyBillingInfo) gateway.Use(groupModelAllowlist) gateway.Use(compositeTarget) + gateway.Use(openAIBPSEndpointGuard) gateway.Use(requireGroupAnthropic) { // /v1/messages: auto-route based on group platform @@ -366,7 +367,7 @@ func RegisterGatewayRoutes( // 根路径别名共用中间件链:白名单准入在 apiKeyAuth 之后、compositeTarget // 之前,避免逐条路由手工维护链导致漏挂。 rootRoute := func(method, path string, limit gin.HandlerFunc, handler gin.HandlerFunc) { - r.Handle(method, path, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, requireGroupAnthropic, handler) + r.Handle(method, path, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, openAIBPSEndpointGuard, requireGroupAnthropic, handler) } for _, prefix := range []string{"/api/v3", "/v3", "/v1", ""} { rootRoute(http.MethodPost, prefix+"/contents/generations/tasks", bodyLimit, h.OpenAIGateway.SeedanceTasks) @@ -383,7 +384,7 @@ func RegisterGatewayRoutes( rootRoute(http.MethodGet, "/models/:model", bodyLimit, h.Gateway.Models) rootRoute(http.MethodPost, "/messages/count_tokens", bodyLimit, countTokensHandler) codexDirect := r.Group("/backend-api/codex") - codexDirect.Use(bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, requireGroupAnthropic) + codexDirect.Use(bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, openAIBPSEndpointGuard, requireGroupAnthropic) { codexDirect.POST("/realtime/calls", h.OpenAIGateway.Live) codexDirect.GET("/:call_id", h.OpenAIGateway.LiveSideband) diff --git a/backend/internal/server/routes/gateway_model_allowlist_test.go b/backend/internal/server/routes/gateway_model_allowlist_test.go index 2fb025bb1..a00b6022c 100644 --- a/backend/internal/server/routes/gateway_model_allowlist_test.go +++ b/backend/internal/server/routes/gateway_model_allowlist_test.go @@ -69,7 +69,7 @@ func TestGatewayRoutesGroupModelAllowlistMountedOnEveryGatewayRoute(t *testing.T source := string(routeSource) // rootRoute helper:apiKeyAuth 之后、compositeTarget 之前。 - rootHelper := regexp.MustCompile(regexp.QuoteMeta(`r.Handle(method, path, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, requireGroupAnthropic, handler)`)) + rootHelper := regexp.MustCompile(regexp.QuoteMeta(`r.Handle(method, path, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, openAIBPSEndpointGuard, requireGroupAnthropic, handler)`)) require.Regexp(t, rootHelper, source, "root alias helper must place the allowlist between apiKeyAuth and compositeTarget") @@ -94,7 +94,7 @@ func TestGatewayRoutesGroupModelAllowlistMountedOnEveryGatewayRoute(t *testing.T } // codexDirect 链是一条 Use 调用,直接断言顺序。 - codexDirect := regexp.MustCompile(regexp.QuoteMeta(`codexDirect.Use(bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, requireGroupAnthropic)`)) + codexDirect := regexp.MustCompile(regexp.QuoteMeta(`codexDirect.Use(bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, openAIBPSEndpointGuard, requireGroupAnthropic)`)) require.Regexp(t, codexDirect, source, "codexDirect chain must mount the allowlist after auth and before compositeTarget") // 所有带 apiKeyAuth 的根路径路由必须收敛到 rootRoute,避免漏挂。 diff --git a/backend/internal/server/routes/openai_bps.go b/backend/internal/server/routes/openai_bps.go new file mode 100644 index 000000000..69392df76 --- /dev/null +++ b/backend/internal/server/routes/openai_bps.go @@ -0,0 +1,27 @@ +package routes + +import ( + "net/http" + "strings" + + "github.com/MACOS-DO/sub4api/internal/service" + "github.com/gin-gonic/gin" +) + +// Applied after composite resolution so an explicit BPS route has the same +// endpoint boundary as a standalone BPS group. +func openAIBPSEndpointGuard(c *gin.Context) { + if getGroupPlatform(c) != service.PlatformOpenAIBPS { + c.Next() + return + } + path := strings.TrimSuffix(c.Request.URL.Path, "/") + allowed := c.Request.Method == http.MethodPost && (strings.HasSuffix(path, "/responses") || strings.HasSuffix(path, "/responses/compact")) + allowed = allowed || (c.Request.Method == http.MethodGet && (strings.HasSuffix(path, "/models") || strings.Contains(path, "/models/") || path == "/v1/usage")) + if allowed { + c.Next() + return + } + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate) + c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": gin.H{"type": "invalid_request_error", "code": "bps_unsupported_endpoint", "message": "OpenAI BPS supports HTTP Responses, compaction and model discovery only"}}) +} diff --git a/backend/internal/server/routes/openai_bps_test.go b/backend/internal/server/routes/openai_bps_test.go new file mode 100644 index 000000000..aab6a2711 --- /dev/null +++ b/backend/internal/server/routes/openai_bps_test.go @@ -0,0 +1,34 @@ +package routes + +import ( + "net/http/httptest" + "testing" + + "github.com/MACOS-DO/sub4api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestOpenAIBPSEndpointBoundary(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + method, path string + allowed bool + }{{"POST", "/v1/responses", true}, {"POST", "/responses/compact", true}, {"POST", "/backend-api/codex/responses", true}, {"GET", "/v1/models", true}, {"GET", "/responses", false}, {"POST", "/v1/chat/completions", false}, {"POST", "/v1/messages", false}, {"POST", "/v1/responses/input_tokens", false}, {"POST", "/v1/images/generations", false}} { + t.Run(tc.method+tc.path, func(t *testing.T) { + r := gin.New() + r.Use(func(c *gin.Context) { + c.Set("api_key", &service.APIKey{Group: &service.Group{Platform: service.PlatformOpenAIBPS}}) + }, openAIBPSEndpointGuard) + r.Handle(tc.method, tc.path, func(c *gin.Context) { c.Status(204) }) + rec := httptest.NewRecorder() + r.ServeHTTP(rec, httptest.NewRequest(tc.method, tc.path, nil)) + if tc.allowed { + require.Equal(t, 204, rec.Code) + } else { + require.Equal(t, 400, rec.Code) + require.Contains(t, rec.Body.String(), "bps_unsupported_endpoint") + } + }) + } +} diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index fa48fb511..9dc2ecdd0 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -180,6 +180,9 @@ func (a *Account) EffectiveLoadFactor() int { } func (a *Account) IsSchedulable() bool { + if a.IsOpenAIBPS() && a.bpsTokenExpired() { + return false + } if !a.IsActive() || !a.Schedulable { return false } @@ -299,7 +302,7 @@ func (a *Account) IsCNProvider() bool { // openai/grok 原生走 OpenAI 网关;国产供应商同为 OpenAI Chat Completions // 兼容上游,也经 OpenAI 网关转发。OpenCode 同样经 OpenAI 网关按模型分流。 func (a *Account) IsOpenAICompatible() bool { - return a != nil && (a.Platform == PlatformOpenAI || a.Platform == PlatformGrok || a.IsCNProvider() || a.IsOpenCodeGo()) + return a != nil && (a.Platform == PlatformOpenAI || a.Platform == PlatformOpenAIBPS || a.Platform == PlatformGrok || a.IsCNProvider() || a.IsOpenCodeGo()) } func (a *Account) GeminiOAuthType() string { @@ -1840,6 +1843,9 @@ func (a *Account) SupportsOpenAIEndpointCapability(capability OpenAIEndpointCapa if !a.IsOpenAICompatible() { return false } + if a.Platform == PlatformOpenAIBPS { + return capability == OpenAIEndpointCapabilityResponses + } if a.IsGrok() { switch capability { case OpenAIEndpointCapabilityChatCompletions: diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 42cc07bdf..539d6aad5 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -515,6 +515,9 @@ func (s *AccountService) TestCredentials(ctx context.Context, id int64) error { case PlatformGrok: // Grok OAuth credentials are validated via token exchange/refresh and request-path probes. return nil + case PlatformOpenAIBPS: + _, err := NormalizeOpenAIBPSCredentials(account.Type, account.Credentials, nil) + return err case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: // 国产 OpenAI 兼容供应商与 OpenCode:凭证为 API Key,实际可用性经余额/额度探测与转发路径验证。 return nil diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 806ac345e..107ca6593 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -396,6 +396,9 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int } } + if account.IsOpenAIBPS() { + return s.testOpenAIBPSAccountConnection(c, account, modelID, prompt, mode) + } if account.IsOpenAI() { return s.testOpenAIAccountConnection(c, account, modelID, prompt, normalizeAccountTestMode(mode)) } diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index 93d73684f..b95ab07a0 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -411,6 +411,14 @@ func normalizeOpenAILongContextBillingUpdateExtra(account *Account, input *Updat // Grok media eligibility helpers live in account_grok_media_eligibility.go. func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]any) (*Account, error) { + if input.Platform == PlatformOpenAIBPS { + creds, err := NormalizeOpenAIBPSCredentials(input.Type, input.Credentials, nil) + if err != nil { + return nil, err + } + input.Credentials = creds + } + accountExtra = MergeOpenAICodexTicketExtra(accountExtra, nil) // Probe/session state is system-managed. New accounts always start with automatic refresh disabled. delete(accountExtra, UpstreamBillingProbeEnabledExtraKey) @@ -536,6 +544,9 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou if err := s.ValidateAccountGroupBindings(ctx, groupIDs); err != nil { return nil, err } + if err := s.validateBPSGroupBindings(ctx, account.Platform, groupIDs); err != nil { + return nil, err + } if err := s.accountRepo.Create(ctx, account); err != nil { return nil, err } @@ -637,6 +648,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if input.Name != "" { account.Name = input.Name } + if account.IsOpenAIBPS() && input.Type != "" && input.Type != AccountTypeOAuth { + return nil, infraerrors.BadRequest("BPS_INVALID_ACCOUNT_TYPE", "OpenAI BPS requires an Access Token account") + } if input.Type != "" { account.Type = input.Type } @@ -648,7 +662,28 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U } else if len(input.Credentials) > 0 { // 敏感子键采用"incoming 没提供就保留"的合并语义:前端响应已脱敏, // 全对象 PUT 编辑时不会再带回 token,避免覆盖时清空已有凭证。 - account.Credentials = MergePreservingSensitiveCreds(account.Credentials, input.Credentials) + if account.IsOpenAIBPS() { + oldToken := account.GetCredential("access_token") + creds, err := NormalizeOpenAIBPSCredentials(account.Type, input.Credentials, account.Credentials) + if err != nil { + return nil, err + } + input.Credentials = creds + if oldToken != stringValue(creds["access_token"]) && account.Status == StatusError && strings.HasPrefix(account.ErrorMessage, "BPS ") { + account.Status = StatusActive + account.ErrorMessage = "" + // The edit form echoes the old automatic error status. A token + // replacement recovers it while preserving explicit disablement. + if input.Status == StatusError { + input.Status = StatusActive + } + } + } + if account.IsOpenAIBPS() { + account.Credentials = input.Credentials + } else { + account.Credentials = MergePreservingSensitiveCreds(account.Credentials, input.Credentials) + } // 校验并规范化请求头覆写配置(header 名小写化、格式检查) if err := NormalizeHeaderOverrideCredentials(account.Credentials); err != nil { return nil, err @@ -851,6 +886,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if err := s.validateGroupIDsExist(ctx, *input.GroupIDs); err != nil { return nil, err } + if err := s.validateBPSGroupBindings(ctx, account.Platform, *input.GroupIDs); err != nil { + return nil, err + } if err := s.ValidateAccountGroupBindings(ctx, *input.GroupIDs); err != nil { return nil, err } @@ -1004,7 +1042,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp // 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查共用,避免多次 DB 查询。 var cachedTargets []*Account - if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil { + if len(input.Credentials) > 0 || input.ProxyID != nil || input.GroupIDs != nil || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil { loaded, err := s.accountRepo.GetByIDs(ctx, input.AccountIDs) if err != nil { return nil, err @@ -1039,6 +1077,9 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp // UpdateAccount 守卫对齐)。覆盖显式 IDs 与 filter 解析出的 IDs(此处 AccountIDs 已解析完成)。 if len(input.Credentials) > 0 { for _, acc := range cachedTargets { + if acc != nil && acc.IsOpenAIBPS() { + return nil, infraerrors.BadRequest("BPS_BULK_CREDENTIALS_UNSUPPORTED", "Edit BPS credentials individually so workspace and expiry metadata are validated per account") + } if acc != nil && acc.IsCredentialShadow() { return nil, infraerrors.Newf(http.StatusBadRequest, "SPARK_SHADOW_NO_CREDENTIALS", "spark shadow account %d cannot hold credentials; manage credentials on the parent account", acc.ID) @@ -1058,6 +1099,15 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp } } + if input.GroupIDs != nil { + for _, a := range cachedTargets { + if a != nil { + if err := s.validateBPSGroupBindings(ctx, a.Platform, *input.GroupIDs); err != nil { + return nil, err + } + } + } + } // 预加载账号平台信息(混合渠道检查需要)。 platformByID := map[int64]string{} if needMixedChannelCheck { diff --git a/backend/internal/service/admin_group.go b/backend/internal/service/admin_group.go index 24a513226..dd627cfae 100644 --- a/backend/internal/service/admin_group.go +++ b/backend/internal/service/admin_group.go @@ -277,6 +277,8 @@ func compositeRouteFromInput(groupID int64, input CompositeRouteInput) (*Composi func defaultModelsListCandidateIDs(platform string) []string { switch platform { + case PlatformOpenAIBPS: + return OpenAIBPSDefaultModels() case PlatformOpenAI: return openai.DefaultModelIDs() case PlatformGemini: diff --git a/backend/internal/service/channel_monitor_checker.go b/backend/internal/service/channel_monitor_checker.go index 63c42a049..61c7af20a 100644 --- a/backend/internal/service/channel_monitor_checker.go +++ b/backend/internal/service/channel_monitor_checker.go @@ -268,7 +268,7 @@ var providerOpenAIResponsesAdapter = providerAdapter{ // providerAdapterFor 按 provider + api_mode 选择具体 adapter。 func providerAdapterFor(provider, apiMode string) (providerAdapter, string, bool) { - if provider == MonitorProviderOpenAI && defaultAPIMode(apiMode) == MonitorAPIModeResponses { + if (provider == MonitorProviderOpenAI || provider == MonitorProviderOpenAIBPS) && defaultAPIMode(apiMode) == MonitorAPIModeResponses { return providerOpenAIResponsesAdapter, MonitorAPIModeResponses, true } adapter, ok := providerAdapters[provider] @@ -292,6 +292,11 @@ func callProvider(ctx context.Context, provider, endpoint, apiKey, model, prompt if !ok { return "", "", 0, fmt.Errorf("unsupported provider %q", provider) } + if provider == MonitorProviderOpenAIBPS { + adapter.buildBody = func(model, prompt string) ([]byte, error) { + return json.Marshal(map[string]any{"model": model, "input": prompt, "stream": false}) + } + } body, err := buildRequestBody(adapter, provider, apiMode, model, prompt, opts) if err != nil { return "", "", 0, err @@ -302,7 +307,7 @@ func callProvider(ctx context.Context, provider, endpoint, apiKey, model, prompt if err != nil { return "", "", status, err } - if provider == MonitorProviderOpenAI && apiMode == MonitorAPIModeResponses { + if (provider == MonitorProviderOpenAI || provider == MonitorProviderOpenAIBPS) && apiMode == MonitorAPIModeResponses { return extractOpenAIResponsesText(respBytes), string(respBytes), status, nil } return extractMonitorResponseText(adapter, respBytes), string(respBytes), status, nil @@ -454,6 +459,7 @@ func buildRequestBody(adapter providerAdapter, provider, apiMode, model, prompt //nolint:gochecknoglobals // 静态查表,初始化后不变。 var bodyMergeKeyDenyList = map[string]map[string]bool{ MonitorProviderOpenAI + ":" + MonitorAPIModeChatCompletions: {"model": true, "messages": true, "stream": true}, + MonitorProviderOpenAIBPS + ":" + MonitorAPIModeResponses: {"model": true, "instructions": true, "input": true, "stream": true}, MonitorProviderOpenAI + ":" + MonitorAPIModeResponses: {"model": true, "instructions": true, "input": true, "stream": true}, MonitorProviderGrok: {"model": true, "messages": true, "stream": true}, MonitorProviderAnthropic: {"model": true, "messages": true}, @@ -473,7 +479,7 @@ func checkAPIMode(opts *CheckOptions) string { } func bodyMergeDenyKey(provider, apiMode string) string { - if provider == MonitorProviderOpenAI { + if provider == MonitorProviderOpenAI || provider == MonitorProviderOpenAIBPS { return provider + ":" + defaultAPIMode(apiMode) } return provider @@ -483,7 +489,7 @@ func bodyMergeDenyKey(provider, apiMode string) string { // Completions 同构(replace 模式的 body 校验按 messages 必填处理)。 func isOpenAICompatibleChatProvider(provider string) bool { switch provider { - case MonitorProviderOpenAI, MonitorProviderGrok, + case MonitorProviderOpenAI, MonitorProviderOpenAIBPS, MonitorProviderGrok, MonitorProviderKimi, MonitorProviderZhipu, MonitorProviderDeepseek, MonitorProviderMiniMax: return true default: diff --git a/backend/internal/service/channel_monitor_const.go b/backend/internal/service/channel_monitor_const.go index d7768e431..95aeab735 100644 --- a/backend/internal/service/channel_monitor_const.go +++ b/backend/internal/service/channel_monitor_const.go @@ -62,6 +62,7 @@ const ( // 后 4 个 provider(antigravity/kimi/zhipu/deepseek)为配额模式引入: // antigravity 无探活 adapter(仅配额),其余 3 个复用 OpenAI 兼容探活。 MonitorProviderOpenAI = "openai" + MonitorProviderOpenAIBPS = "openai_bps" MonitorProviderAnthropic = "anthropic" MonitorProviderGemini = "gemini" MonitorProviderGrok = "grok" @@ -152,10 +153,10 @@ var ( "CHANNEL_MONITOR_NOT_FOUND", "channel monitor not found", ) ErrChannelMonitorInvalidProvider = infraerrors.BadRequest( - "CHANNEL_MONITOR_INVALID_PROVIDER", "provider must be one of openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax", + "CHANNEL_MONITOR_INVALID_PROVIDER", "provider must be one of openai/openai_bps/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax", ) ErrChannelMonitorInvalidCheckMode = infraerrors.BadRequest( - "CHANNEL_MONITOR_INVALID_CHECK_MODE", "check_mode must be one of probe/quota/quota_probe; antigravity only supports quota", + "CHANNEL_MONITOR_INVALID_CHECK_MODE", "check_mode must be one of probe/quota/quota_probe; antigravity only supports quota; openai_bps only supports probe", ) ErrChannelMonitorAccountRequired = infraerrors.BadRequest( "CHANNEL_MONITOR_ACCOUNT_REQUIRED", "account_id is required for quota-based check_mode", @@ -167,7 +168,7 @@ var ( "CHANNEL_MONITOR_ACCOUNT_NOT_SUPPORTABLE", "linked account cannot serve as a quota data source (cn coding plan must be kimi/zhipu/minimax, cn payg must be kimi/deepseek, openai requires an oauth account, anthropic requires oauth or setup-token)", ) ErrChannelMonitorInvalidAPIMode = infraerrors.BadRequest( - "CHANNEL_MONITOR_INVALID_API_MODE", "api_mode must be chat_completions or responses; responses is only supported for openai", + "CHANNEL_MONITOR_INVALID_API_MODE", "api_mode must be chat_completions or responses; responses is supported for openai and openai_bps", ) ErrChannelMonitorInvalidRequestBody = infraerrors.BadRequest( "CHANNEL_MONITOR_INVALID_REQUEST_BODY", "openai-compatible replace-mode body_override must include non-empty messages for chat_completions or non-empty instructions and input for responses", diff --git a/backend/internal/service/channel_monitor_validate.go b/backend/internal/service/channel_monitor_validate.go index 0aa1c248d..df47b946b 100644 --- a/backend/internal/service/channel_monitor_validate.go +++ b/backend/internal/service/channel_monitor_validate.go @@ -14,6 +14,7 @@ import ( // //nolint:gochecknoglobals // 静态查表,初始化后不变。 var monitorProviders = map[string]struct{}{ + MonitorProviderOpenAIBPS: {}, MonitorProviderOpenAI: {}, MonitorProviderAnthropic: {}, MonitorProviderGemini: {}, @@ -30,6 +31,7 @@ var monitorProviders = map[string]struct{}{ // //nolint:gochecknoglobals // 静态查表,初始化后不变。 var probeCapableProviders = map[string]struct{}{ + MonitorProviderOpenAIBPS: {}, MonitorProviderOpenAI: {}, MonitorProviderAnthropic: {}, MonitorProviderGemini: {}, @@ -75,6 +77,9 @@ func monitorCheckModeUsesQuota(checkMode string) bool { // antigravity(无 adapter)| N | Y | N func validateCheckMode(provider, checkMode string) error { checkMode = defaultCheckMode(checkMode) + if provider == MonitorProviderOpenAIBPS && checkMode != MonitorCheckModeProbe { + return ErrChannelMonitorInvalidCheckMode + } switch checkMode { case MonitorCheckModeProbe, MonitorCheckModeQuota, MonitorCheckModeQuotaProbe: default: @@ -90,6 +95,12 @@ func validateCheckMode(provider, checkMode string) error { // responses 只对 OpenAI 有意义;其它 provider 使用 chat_completions 作为默认占位。 func validateAPIMode(provider, apiMode string) error { apiMode = defaultAPIMode(apiMode) + if provider == MonitorProviderOpenAIBPS { + if apiMode == MonitorAPIModeResponses { + return nil + } + return ErrChannelMonitorInvalidAPIMode + } switch apiMode { case MonitorAPIModeChatCompletions: return nil diff --git a/backend/internal/service/channel_service.go b/backend/internal/service/channel_service.go index dbc7ae3eb..e88ca8003 100644 --- a/backend/internal/service/channel_service.go +++ b/backend/internal/service/channel_service.go @@ -368,7 +368,7 @@ func isPlatformPricingMatch(groupPlatform, pricingPlatform string) bool { // fallback used before a request target has been resolved. func matchingPlatforms(groupPlatform string) []string { if groupPlatform == PlatformComposite { - return []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} + return []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS} } return []string{groupPlatform} } diff --git a/backend/internal/service/channel_service_test.go b/backend/internal/service/channel_service_test.go index 2f57f46df..f683e278d 100644 --- a/backend/internal/service/channel_service_test.go +++ b/backend/internal/service/channel_service_test.go @@ -2127,7 +2127,7 @@ func TestMatchingPlatforms(t *testing.T) { {"anthropic returns itself", PlatformAnthropic, []string{PlatformAnthropic}}, {"gemini returns itself", PlatformGemini, []string{PlatformGemini}}, {"openai returns itself", PlatformOpenAI, []string{PlatformOpenAI}}, - {"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo}}, + {"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS}}, } for _, tt := range tests { diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index b28b09704..b1007a68b 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -202,7 +202,7 @@ func (s *GatewayService) resolveCompositeRouteDecision(ctx context.Context, grou func isConcreteRequestPlatform(platform string) bool { switch platform { case PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok, - PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS: return true default: return false diff --git a/backend/internal/service/composite_platform_test.go b/backend/internal/service/composite_platform_test.go index 94262c16a..3c9e6ed04 100644 --- a/backend/internal/service/composite_platform_test.go +++ b/backend/internal/service/composite_platform_test.go @@ -216,7 +216,7 @@ func TestCompositeGroupSchedulerHasAllCanonicalPlatformBuckets(t *testing.T) { platforms = append(platforms, platform) } require.ElementsMatch(t, - []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo}, + []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS}, platforms, ) } diff --git a/backend/internal/service/domain_constants.go b/backend/internal/service/domain_constants.go index 96a7ec189..2efcdcc9c 100644 --- a/backend/internal/service/domain_constants.go +++ b/backend/internal/service/domain_constants.go @@ -40,6 +40,7 @@ const ( const ( PlatformAnthropic = domain.PlatformAnthropic PlatformOpenAI = domain.PlatformOpenAI + PlatformOpenAIBPS = domain.PlatformOpenAIBPS PlatformGemini = domain.PlatformGemini PlatformAntigravity = domain.PlatformAntigravity PlatformGrok = domain.PlatformGrok @@ -125,6 +126,7 @@ func IsMultiProtocolAPIKeyProvider(platform string) bool { // ent/schema/user_platform_quota.go 的 Validate 函数独立维护(构建期约束), // 若新增平台需同步修改该 schema。 var AllowedQuotaPlatforms = []string{ + PlatformOpenAIBPS, PlatformAnthropic, PlatformOpenAI, PlatformGemini, diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 214a019dc..04b40aac8 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -1507,7 +1507,7 @@ func (s *GatewayService) resolveCompositeModelOwnership(ctx context.Context, gro platforms := make(map[string]struct{}) for _, account := range accounts { platform := strings.TrimSpace(account.Platform) - if !isConcreteRequestPlatform(platform) || !explicitModelMappingClaims(account, model) { + if platform == PlatformOpenAIBPS || !isConcreteRequestPlatform(platform) || !explicitModelMappingClaims(account, model) { continue } platforms[platform] = struct{}{} diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index 3ebdfa5e6..7b7a856d9 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -1773,6 +1773,9 @@ func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatible(ctx context.C // openAISelectionFilterStats so that "no available accounts" errors state why // each candidate was dropped instead of failing silently (#4599). func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatibleReason(ctx context.Context, account *Account, req OpenAIAccountScheduleRequest) (bool, string) { + if account != nil && !bpsBoundAccountAllowed(ctx, account) { + return false, "bps_account_binding" + } if account == nil { return false, "account_nil" } diff --git a/backend/internal/service/openai_bps_alignment_test.go b/backend/internal/service/openai_bps_alignment_test.go new file mode 100644 index 000000000..6de475543 --- /dev/null +++ b/backend/internal/service/openai_bps_alignment_test.go @@ -0,0 +1,320 @@ +package service + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestOpenAIBPSReferenceEnvelopes(t *testing.T) { + tools := map[string]bpsTool{} + var catalog []any + require.NoError(t, bpsCollectTools([]any{bpsFunction("exec"), map[string]any{"type": "custom", "name": "apply_patch"}}, "functions", tools, &catalog, 0)) + r := &bpsRequest{Tools: tools} + envelope := `{"tool":"functions.exec","args":{"command":"pwd"}}` + for name, code := range map[string]any{ + "aliases": envelope, + "double JSON": bpsJSON(envelope), + "fenced JSON": "```json\n" + envelope + "\n```", + "nested transport": bpsJSON(map[string]any{"name": "run_officejs", "arguments": map[string]any{"code": envelope}}), + "raw newline": "{\"name\":\"functions.exec\",\"arguments\":{\"command\":\"pwd\nls\"}}", + } { + t.Run(name, func(t *testing.T) { + native := bpsNative("call_envelope", "functions.exec", nil) + native["arguments"] = bpsJSON(map[string]any{"code": code}) + result, err := bpsConvertTool(native, r) + require.NoError(t, err) + require.Equal(t, "exec", result["name"]) + require.Equal(t, "functions", result["namespace"]) + require.NotEmpty(t, result["arguments"]) + }) + } + for _, code := range []any{ + `{"tool":"functions.exec","name":"other","args":{"command":"pwd"}}`, + `{"name":"functions.exec","args":{},"arguments":{}}`, + `{"name":"functions.exec","arguments":{"command":2}}`, + `{"name":"functions.exec","arguments":{"command":"pwd"}}; alert(1)`, + `[{"name":"functions.exec","arguments":{"command":"pwd"}}]`, + `{"name":"not-declared","arguments":{}}`, + strings.Repeat("x", bpsMaxEnvelopeBytes+1), + } { + native := bpsNative("invalid", "functions.exec", nil) + native["arguments"] = bpsJSON(map[string]any{"code": code}) + _, err := bpsConvertTool(native, r) + require.Error(t, err) + } + patch := " *** Begin Patch\n" + strings.Repeat("+value \\\"\t\n", 1000) + "*** End Patch\n " + native := bpsNative("patch", "functions.apply_patch", nil) + native["arguments"] = bpsJSON(map[string]any{"summary": "codex2api.custom/functions.apply_patch", "code": patch, "references": []any{}}) + result, err := bpsConvertTool(native, r) + require.NoError(t, err) + require.Equal(t, patch, result["input"]) + native["arguments"] = bpsJSON(map[string]any{"code": bpsJSON(map[string]any{"tool": "functions.apply_patch", "args": patch})}) + result, err = bpsConvertTool(native, r) + require.NoError(t, err) + require.Equal(t, patch, result["input"]) + native["arguments"] = bpsJSON(map[string]any{"summary": "codex2api.custom/functions.exec", "code": "pwd"}) + _, err = bpsConvertTool(native, r) + require.Error(t, err) +} + +func TestOpenAIBPSAdditionalToolsAndReplay(t *testing.T) { + s, a := bpsFixture() + c, _ := bpsContext(1, "/responses") + source := map[string]any{"model": "gpt-6-astra", "tools": []any{bpsFunction("exec")}, "input": []any{bpsMessage("user", "inspect"), map[string]any{"type": "additional_tools", "tools": []any{bpsFunction("exec"), map[string]any{"type": "namespace", "name": "functions", "tools": []any{map[string]any{"type": "custom", "name": "apply_patch"}}}}}}} + prepared, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, []byte(bpsJSON(source))) + require.NoError(t, err) + require.Len(t, prepared.Tools, 2) + require.NotContains(t, string(prepared.Body), "additional_tools") + native := bpsNative("call_custom", "functions.apply_patch", nil) + native["arguments"] = bpsJSON(map[string]any{"summary": "codex2api.custom/functions.apply_patch", "extended_summary": "preserve this", "references": []any{"native-reference"}, "code": "*** Begin Patch\n*** End Patch"}) + original := bpsJSON(native) + response, err := s.bpsTransformResponse(c.Request.Context(), a, prepared, bpsResponse(native)) + require.NoError(t, err) + call := response["output"].([]any)[0] + input := source["input"].([]any) + source["input"] = append(input, map[string]any{"type": "reasoning", "id": "rs_original", "summary": []any{"not-replayed"}, "encrypted_content": "opaque-ciphertext"}, call, map[string]any{"type": "custom_tool_call_output", "id": "ctco_client", "call_id": "call_custom", "output": "applied"}) + replay, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, []byte(bpsJSON(source))) + require.NoError(t, err) + var wire map[string]any + require.NoError(t, bpsDecode(replay.Body, &wire)) + items := wire["input"].([]any) + reasoning := items[len(items)-3].(map[string]any) + require.Equal(t, map[string]any{"type": "reasoning", "summary": []any{}, "encrypted_content": "opaque-ciphertext"}, reasoning) + require.JSONEq(t, original, bpsJSON(items[len(items)-2])) + result := items[len(items)-1].(map[string]any) + require.Equal(t, "function_call_output", result["type"]) + require.Equal(t, "fc_call_custom", result["id"]) + require.Equal(t, "applied", result["output"]) + require.Equal(t, prepared.TurnID, replay.TurnID) + require.Equal(t, 2, replay.AgentIteration) + // A conflicting late declaration cannot silently change the schema. + source["input"] = []any{bpsMessage("user", "inspect"), map[string]any{"type": "additional_tools", "tools": []any{map[string]any{"type": "function", "name": "exec", "parameters": map[string]any{"type": "object"}}}}} + _, err = s.prepareOpenAIBPS(c.Request.Context(), c, a, []byte(bpsJSON(source))) + require.ErrorContains(t, err, "Conflicting") + require.Equal(t, "fc_short", bpsFunctionOutputID("short")) + long := strings.Repeat("c", 100) + require.Len(t, bpsFunctionOutputID(long), 64) + require.Equal(t, "fc_"+bpsDigest(long)[:61], bpsFunctionOutputID(long)) +} + +func TestOpenAIBPSCompactedTurnLineage(t *testing.T) { + for _, retainedUser := range []bool{false, true} { + t.Run(fmt.Sprint(retainedUser), func(t *testing.T) { + s, a := bpsFixture() + c, _ := bpsContext(1, "/responses") + user := bpsMessage("user", "complete pending work") + source := map[string]any{"model": "gpt-6-astra", "input": []any{user}, "tools": []any{bpsFunction("exec")}} + prepare := func(ctxPath string, src map[string]any) *bpsRequest { + t.Helper() + cx, _ := bpsContext(1, ctxPath) + r, e := s.prepareOpenAIBPS(cx.Request.Context(), cx, a, []byte(bpsJSON(src))) + require.NoError(t, e) + return r + } + before := prepare("/responses", source) + response, err := s.bpsTransformResponse(c.Request.Context(), a, before, bpsResponse(bpsNative("before", "exec", map[string]any{"command": "pwd"}))) + require.NoError(t, err) + source["input"] = append(source["input"].([]any), response["output"].([]any)[0], map[string]any{"type": "function_call_output", "call_id": "before", "output": "workspace"}) + compactRequest := prepare("/responses/compact", source) + require.Equal(t, before.TurnID, compactRequest.TurnID) + require.Equal(t, 2, compactRequest.AgentIteration) + compactResponse, err := s.bpsTransformResponse(c.Request.Context(), a, compactRequest, bpsResponse(bpsText("The work is pending."))) + require.NoError(t, err) + ref := compactResponse["output"].([]any)[0] + input := []any{ref} + if retainedUser { + input = []any{user, ref} + } + source["input"] = input + // A new service uses the same shared store, with no in-process turn counters. + s = &OpenAIGatewayService{cache: s.cache} + after := prepare("/responses", source) + require.Equal(t, before.TurnID, after.TurnID) + require.Equal(t, 2, after.AgentIteration) + for i := 0; i < 3; i++ { + id := fmt.Sprintf("after_%d", i) + result, e := s.bpsTransformResponse(c.Request.Context(), a, after, bpsResponse(bpsNative(id, "exec", map[string]any{"command": "ls"}))) + require.NoError(t, e) + source["input"] = append(source["input"].([]any), result["output"].([]any)[0], map[string]any{"type": "function_call_output", "call_id": id, "output": "files"}) + after = prepare("/responses", source) + require.Equal(t, before.TurnID, after.TurnID) + require.Equal(t, 3+i, after.AgentIteration) + require.Equal(t, after.Body, prepare("/responses", source).Body) + } + // Consecutive compactions retain the accumulated iteration baseline. + secondCompact := prepare("/responses/compact", source) + compactResponse, err = s.bpsTransformResponse(c.Request.Context(), a, secondCompact, bpsResponse(bpsText("Updated summary."))) + require.NoError(t, err) + source["input"] = compactResponse["output"] + after = prepare("/responses", source) + require.Equal(t, before.TurnID, after.TurnID) + require.Equal(t, 5, after.AgentIteration) + source["input"] = append(source["input"].([]any), bpsMessage("user", "new request")) + next := prepare("/responses", source) + require.NotEqual(t, before.TurnID, next.TurnID) + require.Equal(t, 1, next.AgentIteration) + }) + } +} + +func TestOpenAIBPSLegacyCompactStateAndStableRetry(t *testing.T) { + s, a := bpsFixture() + c, _ := bpsContext(1, "/responses") + ref := bpsCompactPrefix + "legacy" + source := map[string]any{"model": "gpt-6-astra", "input": []any{map[string]any{"type": "compaction", "encrypted_content": ref}}, "tools": []any{bpsFunction("exec")}} + body := []byte(bpsJSON(source)) + scope := s.bpsScope(c, body) + require.NoError(t, s.bpsPut(c.Request.Context(), bpsStateKey(scope, a, "compact", ref), map[string]any{"summary": "old record"})) + first, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, body) + require.NoError(t, err) + response, err := s.bpsTransformResponse(c.Request.Context(), a, first, bpsResponse(bpsNative("legacy_call", "exec", map[string]any{"command": "pwd"}))) + require.NoError(t, err) + source["input"] = append(source["input"].([]any), response["output"].([]any)[0], map[string]any{"type": "function_call_output", "call_id": "legacy_call", "output": "done"}) + second, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, []byte(bpsJSON(source))) + require.NoError(t, err) + require.Equal(t, first.TurnID, second.TurnID) + require.Equal(t, 2, second.AgentIteration) +} + +func TestOpenAIBPSNativePlanAliasesAndFailureReplay(t *testing.T) { + s, a := bpsFixture() + c, _ := bpsContext(1, "/responses") + schema := map[string]any{"type": "object", "properties": map[string]any{"plan": map[string]any{"type": "array"}}, "required": []any{"plan"}} + source := map[string]any{"model": "gpt-6-astra", "input": []any{bpsMessage("user", "plan")}, "tools": []any{map[string]any{"type": "function", "name": "update_plan", "parameters": schema}}} + prepared, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, []byte(bpsJSON(source))) + require.NoError(t, err) + native := map[string]any{"type": "function_call", "id": "fc_plan", "call_id": "plan", "name": "functions.update_plan", "arguments": `{"summary":"next","plan":[{"title":"inspect","status":"active"}]}`} + response, err := s.bpsTransformResponse(c.Request.Context(), a, prepared, bpsResponse(native)) + require.NoError(t, err) + call := response["output"].([]any)[0].(map[string]any) + require.Equal(t, "in_progress", gjson.Get(stringValue(call["arguments"]), "plan.0.status").String()) + for _, output := range []string{"Plan updated", "Plan update failed: rejected"} { + source["input"] = []any{bpsMessage("user", "plan"), call, map[string]any{"type": "function_call_output", "call_id": "plan", "output": output}} + replay, e := s.prepareOpenAIBPS(c.Request.Context(), c, a, []byte(bpsJSON(source))) + require.NoError(t, e) + items := gjson.GetBytes(replay.Body, "input").Array() + got := items[len(items)-1].Get("output").String() + if output == "Plan updated" { + require.JSONEq(t, `{"status":"ok"}`, got) + } else { + require.Equal(t, output, got) + } + } + native["arguments"] = `{"plan":[{"title":"a","step":"b","status":"done"}]}` + _, err = bpsConvertTool(native, prepared) + require.Error(t, err) + native["arguments"] = `{"plan":[{"title":"a","status":"mystery"}]}` + _, err = bpsConvertTool(native, prepared) + require.Error(t, err) +} + +func TestOpenAIBPSModelPermissionCode(t *testing.T) { + for _, code := range []string{"basispoints_model_access_changed", "model_not_allowed"} { + s, a := bpsFixture() + repo := &bpsFailureRepo{} + s.accountRepo = repo + c, rec := bpsContext(1, "/responses") + a.Credentials["model_mapping"] = map[string]any{"alias": "gpt-6-astra"} + s.httpUpstream = &bpsHTTPStub{status: http.StatusForbidden, contentType: "application/json", body: bpsJSON(map[string]any{"error": map[string]any{"code": code, "message": "model permission changed"}})} + _, err := s.Forward(c.Request.Context(), c, a, []byte(`{"model":"alias","input":"hello"}`)) + require.Error(t, err) + require.Equal(t, "bps_model_not_allowed", gjson.Get(rec.Body.String(), "error.code").String()) + require.Equal(t, []string{"gpt-6-astra"}, repo.limitedModels) + require.Empty(t, repo.authErrors) + } + // JSON numbers must remain exact through envelope decoding and schema checking. + var args map[string]any + require.NoError(t, bpsDecode([]byte(`{"n":9007199254740993}`), &args)) + require.Equal(t, json.Number("9007199254740993"), args["n"]) +} + +func TestOpenAIBPSMissingTerminalToolIsNotSuccessful(t *testing.T) { + for _, stream := range []bool{false, true} { + s, a := bpsFixture() + c, rec := bpsContext(1, "/responses") + native := bpsNative("lost", "exec", map[string]any{"command": "pwd"}) + s.httpUpstream = &bpsHTTPStub{contentType: "text/event-stream", body: bpsEvent("response.output_item.done", map[string]any{"item": native, "output_index": 0}) + bpsEvent("response.completed", map[string]any{"response": bpsResponse()})} + body := []byte(bpsJSON(map[string]any{"model": "gpt-6-astra", "input": "inspect", "stream": stream, "tools": []any{bpsFunction("exec")}})) + result, err := s.Forward(c.Request.Context(), c, a, body) + require.Error(t, err) + require.Equal(t, 100, result.Usage.InputTokens) + require.Contains(t, rec.Body.String(), "bps_invalid_tool_call") + require.NotContains(t, rec.Body.String(), "event: response.completed") + require.NotContains(t, rec.Body.String(), "response.function_call_arguments.done") + } +} + +// Exercise the public forwarding service through the whole client-tool loop, +// compaction and a structured final answer, without bypassing routing/binding. +func TestOpenAIBPSForwardToolsCompactStructuredContinuation(t *testing.T) { + for _, model := range OpenAIBPSDefaultModels() { + t.Run(model, func(t *testing.T) { + s, a := bpsFixture() + tools := []any{bpsFunction("exec"), map[string]any{"type": "custom", "name": "apply_patch"}, map[string]any{"type": "function", "name": "update_plan", "parameters": map[string]any{"type": "object", "properties": map[string]any{"plan": map[string]any{"type": "array"}}, "required": []any{"plan"}}}} + source := bpsTestStructuredRequest(bpsTestStructuredFormat(true), false) + source["model"], source["input"], source["tools"] = model, []any{bpsMessage("user", "inspect, plan, patch, and finish")}, tools + invoke := func(path string, output ...any) (map[string]any, map[string]any) { + t.Helper() + up := &bpsHTTPStub{contentType: "application/json", body: bpsJSON(bpsResponse(output...))} + s.httpUpstream = up + c, rec := bpsContext(71, path) + _, err := s.Forward(c.Request.Context(), c, a, []byte(bpsJSON(source))) + require.NoError(t, err) + require.Equal(t, 200, rec.Code) + var response, wire map[string]any + require.NoError(t, bpsDecode(rec.Body.Bytes(), &response)) + require.NoError(t, bpsDecode(up.requestBody, &wire)) + require.Equal(t, model, wire["model"]) + require.NotContains(t, wire, "tools") + require.NotContains(t, wire, "text") + return response, wire + } + appendResult := func(response map[string]any, text string) { + t.Helper() + output := response["output"].([]any) + source["input"] = append(source["input"].([]any), output...) + for _, raw := range output { + call := raw.(map[string]any) + kind := stringValue(call["type"]) + if kind == "function_call" || kind == "custom_tool_call" { + source["input"] = append(source["input"].([]any), map[string]any{"type": kind + "_output", "call_id": call["call_id"], "output": text}) + } + } + } + response, wire := invoke("/responses", map[string]any{"type": "reasoning", "id": "rs_1", "summary": []any{}, "encrypted_content": "ciphertext"}, bpsNative("inspect", "exec", map[string]any{"command": "pwd"})) + turn := wire["metadata"].(map[string]any)["turn_id"] + appendResult(response, "/workspace") + response, wire = invoke("/responses", map[string]any{"type": "function_call", "id": "fc_plan", "call_id": "plan", "name": "functions.update_plan", "arguments": `{"plan":[{"description":"patch","status":"active"}]}`}) + require.Equal(t, turn, wire["metadata"].(map[string]any)["turn_id"]) + require.Contains(t, bpsJSON(wire), "ciphertext") + require.Contains(t, bpsJSON(wire), "fc_inspect") + appendResult(response, "Plan updated") + native := bpsNative("patch", "apply_patch", nil) + native["arguments"] = bpsJSON(map[string]any{"summary": "codex2api.custom/apply_patch", "code": "*** Begin Patch\n*** End Patch", "references": []any{}, "extended_summary": "original wrapper"}) + response, wire = invoke("/responses", native) + require.Equal(t, turn, wire["metadata"].(map[string]any)["turn_id"]) + require.Contains(t, bpsJSON(wire), `status\":\"ok`) + appendResult(response, "patch applied") + compact, wire := invoke("/responses/compact", bpsText("Patch applied. Verify and return the final result.")) + require.Equal(t, "4", wire["metadata"].(map[string]any)["agent_iteration"]) + require.Equal(t, turn, wire["metadata"].(map[string]any)["turn_id"]) + source["input"] = compact["output"] + s = &OpenAIGatewayService{cache: s.cache} + response, wire = invoke("/responses", bpsNative("verify", "exec", map[string]any{"command": "test -f file"})) + require.NotContains(t, bpsJSON(wire), bpsCompactPrefix) + require.Equal(t, "4", wire["metadata"].(map[string]any)["agent_iteration"]) + require.Equal(t, turn, wire["metadata"].(map[string]any)["turn_id"]) + appendResult(response, "verified") + response, wire = invoke("/responses", bpsText(`{"ok":true}`)) + require.Equal(t, "5", wire["metadata"].(map[string]any)["agent_iteration"]) + require.Equal(t, turn, wire["metadata"].(map[string]any)["turn_id"]) + require.Equal(t, "json_schema", response["text"].(map[string]any)["format"].(map[string]any)["type"]) + }) + } +} diff --git a/backend/internal/service/openai_bps_catalog.go b/backend/internal/service/openai_bps_catalog.go new file mode 100644 index 000000000..178317e1d --- /dev/null +++ b/backend/internal/service/openai_bps_catalog.go @@ -0,0 +1,40 @@ +package service + +import "encoding/json" + +func buildOpenAIBPSCodexModelsManifest(modelIDs []string) ([]byte, error) { + body, err := BuildCodexModelsManifest(modelIDs) + if err != nil { + return nil, err + } + var catalog struct { + Models []map[string]any `json:"models"` + } + if err = json.Unmarshal(body, &catalog); err != nil { + return nil, err + } + for _, model := range catalog.Models { + applyOpenAIBPSModelCapabilities(model) + } + return json.Marshal(catalog) +} + +func applyOpenAIBPSModelCapabilities(model map[string]any) { + model["default_reasoning_level"] = "medium" + model["multi_agent_reasoning_effort"] = "medium" + model["supported_reasoning_levels"] = []configuredCodexReasoningLevel{{"low", "Low"}, {"medium", "Medium"}, {"high", "High"}, {"xhigh", "Extra high"}} + model["supports_parallel_tool_calls"] = false + model["prefer_websockets"] = false + model["supports_reasoning_summary_parameter"] = false + model["support_verbosity"] = false + model["input_modalities"] = []string{"text"} + model["supports_image_detail_original"] = false + model["supports_search_tool"] = false + model["additional_speed_tiers"] = []string{} + model["service_tiers"] = []any{} + model["default_service_tier"] = nil + // Conservative local compaction policy, not a claim about upstream limits. + model["context_window"] = 200000 + model["max_context_window"] = 200000 + model["auto_compact_token_limit"] = 160000 +} diff --git a/backend/internal/service/openai_bps_composite_catalog.go b/backend/internal/service/openai_bps_composite_catalog.go new file mode 100644 index 000000000..e7eb162d0 --- /dev/null +++ b/backend/internal/service/openai_bps_composite_catalog.go @@ -0,0 +1,106 @@ +package service + +import ( + "context" + "fmt" + "sort" + "strings" +) + +// CompleteCompositeBPSModelCatalog adds only explicitly routed BPS models to +// the shared HTTP/Codex catalog. A non-nil empty slice disables static fallback +// when this group has configured BPS accounts or routes but no usable models. +func (s *GatewayService) CompleteCompositeBPSModelCatalog(ctx context.Context, groupID *int64, existing []string) ([]string, error) { + if groupID == nil || s == nil || s.accountRepo == nil { + if len(existing) == 0 { + return nil, nil + } + return existing, nil + } + accounts, err := s.accountRepo.ListByGroup(ctx, *groupID) + if err != nil { + return nil, fmt.Errorf("load composite catalog accounts: %w", err) + } + configured := false + candidates := map[string]bool{} + addCandidate := func(model string, alreadyListed bool) { + model = strings.TrimSpace(model) + if model != "" { + candidates[model] = candidates[model] || alreadyListed + } + } + for _, model := range existing { + addCandidate(model, true) + } + for _, account := range accounts { + if !account.IsOpenAIBPS() { + continue + } + configured = true + mapping := account.GetModelMapping() + if len(mapping) == 0 { + for _, model := range OpenAIBPSDefaultModels() { + addCandidate(model, false) + } + } + for model := range mapping { + if strings.ContainsAny(model, "*?") { + continue + } + addCandidate(model, false) + } + } + var routes []CompositeModelRoute + if s.compositeResolver != nil && s.compositeResolver.repo != nil { + all, err := s.compositeResolver.repo.ListByGroup(ctx, *groupID, true) + if err != nil { + return nil, fmt.Errorf("load composite catalog routes: %w", err) + } + for _, route := range all { + if route.TargetPlatform == PlatformOpenAIBPS { + configured = true + } + if !route.Enabled { + continue + } + routes = append(routes, route) + endpoint := normalizeCompositeRouteEndpoint(route.Endpoint) + if route.TargetPlatform == PlatformOpenAIBPS && normalizeCompositeRouteMatchType(route.MatchType) == CompositeRouteMatchExact && (endpoint == CompositeRouteEndpointAny || endpoint == CompositeRouteEndpointResponses) { + addCandidate(route.PublicModel, false) + } + } + } + if !configured { + if len(existing) == 0 { + return nil, nil + } + return existing, nil + } + models := make([]string, 0, len(candidates)) + for model, wasListed := range candidates { + model = strings.TrimSpace(model) + if model == "" { + continue + } + route, matched := matchCompositeRoute(routes, model, CompositeRouteEndpointResponses) + if !matched || route.TargetPlatform != PlatformOpenAIBPS { + if wasListed { + models = append(models, model) + } + continue + } + target := strings.TrimSpace(route.UpstreamModel) + if target == "" { + target = model + } + for i := range accounts { + a := &accounts[i] + if a.Type == AccountTypeOAuth && isOpenAICompatibleAccountEligibleForRequestBeforeProfit(ctx, a, PlatformOpenAIBPS, target, false, OpenAIEndpointCapabilityResponses) { + models = append(models, model) + break + } + } + } + sort.Strings(models) + return models, nil +} diff --git a/backend/internal/service/openai_bps_credentials.go b/backend/internal/service/openai_bps_credentials.go new file mode 100644 index 000000000..b6cd1850e --- /dev/null +++ b/backend/internal/service/openai_bps_credentials.go @@ -0,0 +1,101 @@ +package service + +import ( + "context" + "encoding/base64" + "encoding/json" + "strings" + "time" + + infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors" +) + +const OpenAIBPSResponsesURL = "https://bps.openai.com/basispoints/api/responses" + +func OpenAIBPSDefaultModels() []string { return []string{"gpt-6-astra", "gpt-5.6-sol"} } + +// NormalizeOpenAIBPSCredentials extracts JWT metadata, not proof of authentication. +// Only the BPS upstream can establish whether the supplied credential is usable. +func NormalizeOpenAIBPSCredentials(accountType string, incoming, existing map[string]any) (map[string]any, error) { + if accountType != AccountTypeOAuth { + return nil, infraerrors.BadRequest("BPS_INVALID_ACCOUNT_TYPE", "OpenAI BPS requires an Access Token account") + } + creds := make(map[string]any, len(existing)+len(incoming)) + for k, v := range existing { + creds[k] = v + } + for k, v := range incoming { + if k == "access_token" && strings.TrimSpace(stringValue(v)) == "" { + continue + } + creds[k] = v + } + token := strings.TrimSpace(stringValue(creds["access_token"])) + token = strings.TrimSpace(strings.TrimPrefix(token, "Bearer ")) + if token == "" || strings.ContainsAny(token, "\r\n") { + return nil, infraerrors.BadRequest("BPS_TOKEN_REQUIRED", "A valid access_token is required") + } + creds["access_token"] = token + var claims map[string]any + parts := strings.Split(token, ".") + if len(parts) == 3 { + if data, err := base64.RawURLEncoding.DecodeString(parts[1]); err == nil { + _ = json.Unmarshal(data, &claims) + } + } + if token != stringValue(existing["access_token"]) { + delete(creds, "expires_at") + } + if exp, ok := claims["exp"].(float64); ok && exp >= -62135596800 && exp < 253402300800 { + creds["expires_at"] = time.Unix(int64(exp), 0).UTC().Format(time.RFC3339) + } + id := strings.TrimSpace(stringValue(creds["chatgpt_account_id"])) + // Explicit operator selection takes precedence over the token's default workspace. + if id == "" { + if auth, ok := claims["https://api.openai.com/auth"].(map[string]any); ok { + id = strings.TrimSpace(stringValue(auth["chatgpt_account_id"])) + } + } + if id == "" || len(id) > 200 || strings.ContainsAny(id, "\r\n") { + return nil, infraerrors.BadRequest("BPS_ACCOUNT_ID_REQUIRED", "chatgpt_account_id is required when it cannot be extracted from the token") + } + creds["chatgpt_account_id"] = id + delete(creds, "refresh_token") + delete(creds, "base_url") + delete(creds, "header_overrides") + if _, ok := creds["model_mapping"]; !ok { + models := map[string]any{} + for _, m := range OpenAIBPSDefaultModels() { + models[m] = m + } + creds["model_mapping"] = models + } + return creds, nil +} + +func (a *Account) IsOpenAIBPS() bool { return a != nil && a.Platform == PlatformOpenAIBPS } +func (a *Account) bpsTokenExpired() bool { + t := a.GetCredentialAsTime("expires_at") + return t != nil && !t.After(time.Now()) +} + +// A BPS account can be bound only to its own platform or a Composite group. +// Scheduling also independently checks the concrete target platform. +func (s *adminServiceImpl) validateBPSGroupBindings(ctx context.Context, platform string, groupIDs []int64) error { + if platform != PlatformOpenAIBPS || len(groupIDs) == 0 { + return nil + } + if s.groupRepo == nil { + return infraerrors.BadRequest("BPS_GROUP_REQUIRED", "Group repository is unavailable") + } + for _, id := range groupIDs { + group, err := s.groupRepo.GetByIDLite(ctx, id) + if err != nil { + return err + } + if group == nil || (group.Platform != PlatformOpenAIBPS && group.Platform != PlatformComposite) { + return infraerrors.BadRequest("BPS_GROUP_MISMATCH", "BPS accounts require an OpenAI BPS or Composite group") + } + } + return nil +} diff --git a/backend/internal/service/openai_bps_custom_transport.go b/backend/internal/service/openai_bps_custom_transport.go new file mode 100644 index 000000000..c01859b01 --- /dev/null +++ b/backend/internal/service/openai_bps_custom_transport.go @@ -0,0 +1,33 @@ +// Adapted from ranxi2001/sub2api at 055a1cd1470b3b866d04aad8d1514bd34cac73ab. +// Protocol provenance and licenses are recorded in docs/openai-bps-sources.md. +package service + +import ( + "fmt" + "strings" + "unicode" +) + +const bpsCustomTransportPrefix = "codex2api.custom/" + +// customTransportEnvelope recognizes only the explicitly tagged raw custom-tool +// transport. The caller must still check the exact catalog name, custom kind and +// call identity. Ordinary run_officejs calls continue through the JSON decoder. +func bpsCustomTransportEnvelope(arguments map[string]any) (map[string]any, bool, error) { + summary, ok := arguments["summary"].(string) + if !ok || !strings.HasPrefix(summary, bpsCustomTransportPrefix) { + return nil, false, nil + } + name := strings.TrimPrefix(summary, bpsCustomTransportPrefix) + if name == "" || strings.ContainsAny(name, "/\\") || strings.IndexFunc(name, unicode.IsSpace) >= 0 || strings.IndexFunc(name, unicode.IsControl) >= 0 { + return nil, true, fmt.Errorf("basispoints raw custom transport requires an exact nonempty catalog tool name in summary") + } + input, ok := arguments["code"].(string) + if !ok { + return nil, true, fmt.Errorf("basispoints raw custom transport code must be a string") + } + if len(input) > bpsMaxEnvelopeBytes { + return nil, true, fmt.Errorf("basispoints raw custom transport code exceeds the size limit") + } + return map[string]any{"name": name, "input": input}, true, nil +} diff --git a/backend/internal/service/openai_bps_envelope.go b/backend/internal/service/openai_bps_envelope.go new file mode 100644 index 000000000..c5d298bab --- /dev/null +++ b/backend/internal/service/openai_bps_envelope.go @@ -0,0 +1,248 @@ +// Adapted from ranxi2001/sub2api at 055a1cd1470b3b866d04aad8d1514bd34cac73ab. +// Protocol provenance and licenses are recorded in docs/openai-bps-sources.md. +package service + +import ( + "encoding/json" + "errors" + "fmt" + "strings" +) + +const bpsMaxEnvelopeBytes = 1 << 20 + +// decodeTransportCode unwraps common model formatting without evaluating code. +// Each layer must contain one complete JSON value; ambiguous batches are rejected. +func bpsDecodeTransportCode(value any) (map[string]any, error) { + original := value + for depth := 0; depth < 4; depth++ { + if item, ok := value.(map[string]any); ok && item != nil { + if len(bpsJSON(item)) > bpsMaxEnvelopeBytes { + break + } + return item, nil + } + raw, ok := value.(string) + if !ok || len(raw) > bpsMaxEnvelopeBytes { + break + } + raw = strings.TrimSpace(raw) + if raw == "" { + break + } + if decoded, ok := bpsDecodeEnvelopeValue(raw); ok { + value = decoded + continue + } + // Strip a complete Markdown fence, optionally preceded by a short prose label. + if start := strings.Index(raw, "```"); start >= 0 && bpsProsePrefix(raw[:start]) { + fenced := raw[start:] + newline := strings.IndexByte(fenced, '\n') + if newline >= 0 && strings.HasSuffix(fenced, "```") { + language := strings.TrimSpace(fenced[3:newline]) + if language == "" || strings.EqualFold(language, "json") { + value = strings.TrimSpace(fenced[newline+1 : len(fenced)-3]) + continue + } + } + } + if start := strings.IndexByte(raw, '{'); start > 0 && bpsProsePrefix(raw[:start]) { + if decoded, ok := bpsDecodeEnvelopeValue(raw[start:]); ok { + value = decoded + continue + } + } + break + } + return nil, fmt.Errorf("basispoints tool transport code must contain one JSON client-tool envelope; OfficeJS and multiple calls are unsupported (%s)", bpsTransportShape(original)) +} + +// Report only structural facts, never client code, prompts or tool arguments. +func bpsTransportShape(value any) string { + raw, ok := value.(string) + if !ok { + if value == nil { + return "format=missing" + } + return fmt.Sprintf("format=non_string_%T", value) + } + trimmed := strings.TrimSpace(raw) + format := "text_or_code" + switch { + case trimmed == "": + format = "empty" + case strings.HasPrefix(trimmed, "```"): + format = "markdown" + case strings.HasPrefix(trimmed, "{"): + format = "json_object" + case strings.HasPrefix(trimmed, "["): + format = "json_array" + case strings.HasPrefix(trimmed, `"`): + format = "json_string" + } + detail := fmt.Sprintf("format=%s; bytes=%d", format, len(raw)) + var syntax *json.SyntaxError + var decoded any + if err := json.Unmarshal([]byte(raw), &decoded); errors.As(err, &syntax) { + detail += fmt.Sprintf("; json_offset=%d; json_failure=%s", syntax.Offset, bpsJsonFailureKind(raw, syntax)) + } + return detail +} + +// Classify the parser's structural context without returning its message, which +// can contain a byte from the caller's code. Offsets use the original wire text. +func bpsJsonFailureKind(raw string, syntax *json.SyntaxError) string { + if syntax == nil { + return "unknown" + } + message := syntax.Error() + if syntax.Offset > 0 && syntax.Offset <= int64(len(raw)) && raw[syntax.Offset-1] < 0x20 { + return "raw_control" + } + if syntax.Offset > 1 && raw[syntax.Offset-2] == '\\' { + return "invalid_escape" + } + if syntax.Offset > 5 && raw[syntax.Offset-6] == '\\' && raw[syntax.Offset-5] == 'u' { + return "invalid_escape" + } + switch { + case strings.Contains(message, "unexpected end of JSON input"): + return "unexpected_eof" + case strings.Contains(message, "after top-level value"): + return "trailing_data" + case strings.Contains(message, "in string escape code"), strings.Contains(message, "in \\u hexadecimal character escape"): + return "invalid_escape" + case strings.Contains(message, "in string literal"): + if syntax.Offset > 0 && syntax.Offset <= int64(len(raw)) && raw[syntax.Offset-1] < 0x20 { + return "raw_control" + } + return "invalid_string" + case strings.Contains(message, "after object key"), strings.Contains(message, "after array element"): + return "missing_separator" + default: + return "unexpected_token" + } +} + +func bpsDecodeTransportEnvelope(value any) (map[string]any, error) { + for depth := 0; depth < 3; depth++ { + envelope, err := bpsDecodeTransportCode(value) + if err != nil { + return nil, err + } + name, err := bpsEnvelopeName(envelope) + if err != nil { + return nil, err + } + if name != "run_officejs" && name != "functions.run_officejs" { + return envelope, nil + } + args, err := bpsEnvelopeArguments(envelope) + if err != nil { + return nil, err + } + if raw, ok := args.(string); ok { + var parsed map[string]any + if bpsDecode([]byte(raw), &parsed) != nil { + return nil, fmt.Errorf("basispoints nested transport arguments must be one JSON object") + } + args = parsed + } + outer, ok := args.(map[string]any) + if !ok { + return nil, fmt.Errorf("basispoints nested transport arguments must be an object") + } + value = outer["code"] + } + return nil, fmt.Errorf("basispoints tool transport exceeds two nested wrappers") +} + +func bpsEnvelopeName(envelope map[string]any) (string, error) { + name := stringValue(envelope["name"]) + alias := stringValue(envelope["tool"]) + if name != "" && alias != "" && name != alias { + return "", fmt.Errorf("basispoints tool envelope contains conflicting names") + } + if name == "" { + name = alias + } + return name, nil +} + +func bpsEnvelopeArguments(envelope map[string]any) (any, error) { + args, exists := envelope["arguments"] + alias, hasAlias := envelope["args"] + if exists && hasAlias { + return nil, fmt.Errorf("basispoints tool envelope contains conflicting argument fields") + } + if !exists { + args = alias + } + return args, nil +} + +func bpsProsePrefix(prefix string) bool { + return len(prefix) <= 512 && !strings.ContainsAny(prefix, "{}[]();=`\"") +} + +func bpsDecodeEnvelopeValue(raw string) (any, bool) { + var value any + if bpsDecode([]byte(raw), &value) == nil { + return value, true + } + // Escape raw line breaks and tabs inside strings, preserving those exact + // characters, and repair illegal backslash escapes only after strict decoding + // fails. Never infer missing quotes, separators, closing delimiters or values. + fixed := bpsRepairTransportJSONStrings(raw) + if fixed != raw && bpsDecode([]byte(fixed), &value) == nil { + return value, true + } + return nil, false +} + +func bpsRepairTransportJSONStrings(raw string) string { + var out strings.Builder + out.Grow(len(raw)) + quoted := false + for i := 0; i < len(raw); i++ { + ch := raw[i] + if ch == '"' { + quoted = !quoted + } + if quoted { + switch ch { + case '\n': + _, _ = out.WriteString(`\n`) + continue + case '\r': + _, _ = out.WriteString(`\r`) + continue + case '\t': + _, _ = out.WriteString(`\t`) + continue + } + } + if ch != '\\' || !quoted || i+1 >= len(raw) { + _ = out.WriteByte(ch) + continue + } + next := raw[i+1] + valid := strings.ContainsRune(`"\/bfnrt`, rune(next)) + if next == 'u' && i+5 < len(raw) { + valid = true + for _, digit := range raw[i+2 : i+6] { + if !strings.ContainsRune("0123456789abcdefABCDEF", digit) { + valid = false + } + } + } + _ = out.WriteByte('\\') + if valid { + _ = out.WriteByte(next) + i++ + } else { + _ = out.WriteByte('\\') + } + } + return out.String() +} diff --git a/backend/internal/service/openai_bps_gateway.go b/backend/internal/service/openai_bps_gateway.go new file mode 100644 index 000000000..6d78b0d43 --- /dev/null +++ b/backend/internal/service/openai_bps_gateway.go @@ -0,0 +1,562 @@ +package service + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "sync/atomic" + "time" + + "github.com/gin-gonic/gin" +) + +// WriteOpenAIBPSError preserves an already-started SSE stream's protocol. +func WriteOpenAIBPSError(c *gin.Context, err error) { + failure := &bpsError{502, "bps_upstream_error", "BPS upstream request failed"} + var typed *bpsError + if errors.As(err, &typed) { + failure = typed + } + setOpsUpstreamError(c, failure.Status, failure.Message, "") + payload := gin.H{"type": "server_error", "code": failure.Code, "message": failure.Message} + if failure.Status == 400 || failure.Status == 409 { + payload["type"] = "invalid_request_error" + } + if c.Writer.Written() && strings.Contains(c.Writer.Header().Get("Content-Type"), "text/event-stream") { + MarkOpsStreamError(c, failure.Code, failure.Message, failure.Status) + sequence := c.GetInt("bps_sequence") + responseID := c.GetString("bps_response_id") + if responseID == "" { + responseID = "resp_bps_error" + } + data, _ := json.Marshal(gin.H{"type": "response.failed", "sequence_number": sequence, "response": gin.H{"id": responseID, "object": "response", "status": "failed", "error": payload}}) + _, _ = fmt.Fprintf(c.Writer, "event: response.failed\ndata: %s\n\n", data) + c.Writer.Flush() + return + } + c.JSON(failure.Status, gin.H{"error": payload}) +} + +func buildOpenAIBPSRequest(ctx context.Context, account *Account, body []byte) (*http.Request, error) { + if account.Type != AccountTypeOAuth || !account.IsOpenAIBPS() { + return nil, bpsInvalid("Invalid BPS account") + } + token := strings.TrimSpace(account.GetCredential("access_token")) + id := strings.TrimSpace(account.GetCredential("chatgpt_account_id")) + if token == "" || id == "" || strings.ContainsAny(token+id, "\r\n") { + return nil, &bpsError{401, "bps_invalid_credentials", "BPS credentials are incomplete"} + } + if account.bpsTokenExpired() { + return nil, &bpsError{401, "bps_token_expired", "BPS access token has expired; replace it in the account settings"} + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, OpenAIBPSResponsesURL, bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("chatgpt-account-id", id) + req.Header.Set("x-openai-account-id", id) + req.Header.Set("x-basispoints-auth-mode", "chatgpt") + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "text/event-stream") + req.Header.Set("Accept-Encoding", "identity") + req.Header.Set("Origin", "https://bps.openai.com") + for k, v := range map[string]string{"client-agent-profile": "excel", "client-editor": "excel", "client-host": "office", "client-platform": "excel", "client-platform-class": "PC", "client-product": "basispoints-excel-plugin", "client-runtime": "desktop", "office-host": "Excel", "office-platform": "PC"} { + req.Header.Set("x-openai-internal-basispoints-"+k, v) + } + return req, nil +} + +func (s *OpenAIGatewayService) bpsHTTPError(ctx context.Context, c *gin.Context, account *Account, resp *http.Response, model string) error { + data, _ := io.ReadAll(io.LimitReader(resp.Body, openAIUpstreamErrorBodyReadLimit)) + message := sanitizeUpstreamErrorMessage(extractUpstreamErrorMessage(data)) + message = strings.ReplaceAll(message, account.GetCredential("access_token"), "[REDACTED]") + if message == "" { + message = fmt.Sprintf("BPS returned HTTP %d", resp.StatusCode) + } + var upstreamError struct { + Error struct { + Code string `json:"code"` + } `json:"error"` + } + _ = json.Unmarshal(data, &upstreamError) + upstreamCode := strings.ToLower(strings.TrimSpace(upstreamError.Error.Code)) + diagnosticCode := strings.ReplaceAll(sanitizeUpstreamErrorMessage(strings.TrimSpace(upstreamError.Error.Code)), account.GetCredential("access_token"), "[REDACTED]") + if len(diagnosticCode) > 128 { + diagnosticCode = diagnosticCode[:128] + } + code := "bps_upstream_error" + switch resp.StatusCode { + case 401: + code = "bps_invalid_credentials" + if s.accountRepo != nil { + _ = s.accountRepo.SetError(ctx, account.ID, "BPS authentication failed; replace access_token") + } + case 403: + if upstreamCode == "model_not_allowed" || upstreamCode == "basispoints_model_access_changed" { + code = "bps_model_not_allowed" + if s.accountRepo != nil { + _ = s.accountRepo.SetModelRateLimit(ctx, account.ID, model, time.Now().Add(30*time.Minute), "BPS model is not permitted: "+upstreamCode) + } + } else { + // A workspace, policy or model entitlement 403 does not prove + // that this access token is invalid for all models. + code = "bps_access_denied" + } + case 429: + delay := time.Minute + if n, e := strconv.Atoi(resp.Header.Get("Retry-After")); e == nil && n > 0 { + delay = time.Duration(n) * time.Second + } else if until, e := http.ParseTime(resp.Header.Get("Retry-After")); e == nil && until.After(time.Now()) { + delay = time.Until(until) + } + if s.accountRepo != nil { + _ = s.accountRepo.SetRateLimited(ctx, account.ID, time.Now().Add(delay)) + } + } + if value := resp.Header.Get("Retry-After"); value != "" { + c.Header("Retry-After", value) + } + appendOpsUpstreamError(c, OpsUpstreamErrorEvent{AccountID: account.ID, AccountName: account.Name, Platform: account.Platform, UpstreamStatusCode: resp.StatusCode, Kind: "http_error", Message: message, Detail: diagnosticCode}) + if !bpsHasBinding(ctx) && (resp.StatusCode == 429 || resp.StatusCode >= 500) { + return &UpstreamFailoverError{StatusCode: resp.StatusCode, ResponseBody: []byte(bpsJSON(map[string]any{"error": map[string]any{"message": message}})), ClientMessage: message} + } + return &bpsError{resp.StatusCode, code, message} +} + +// readBPSEvents accepts SSE (including multi-line data) and unary JSON without +// converting an EOF into response.completed. Each event has a bounded size. +func readBPSEvents(resp *http.Response, maxSize int, consume func(string, map[string]any) error) error { + if maxSize <= 0 { + maxSize = 16 << 20 + } + if !strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") { + data, e := io.ReadAll(io.LimitReader(resp.Body, int64(maxSize)+1)) + if e != nil { + return e + } + if len(data) > maxSize { + return fmt.Errorf("BPS response exceeds maximum size") + } + var response map[string]any + if e = bpsDecode(data, &response); e != nil { + return e + } + event := "response.completed" + if response["status"] != "completed" { + event = "response.failed" + } + return consume(event, map[string]any{"type": event, "response": response}) + } + scanner := bufio.NewScanner(resp.Body) + scanner.Buffer(make([]byte, 64<<10), maxSize) + event := "" + terminal := false + var data strings.Builder + dispatch := func() error { + if data.Len() == 0 { + event = "" + return nil + } + text := strings.TrimSpace(data.String()) + data.Reset() + if text == "[DONE]" { + event = "" + return nil + } + var payload map[string]any + if e := bpsDecode([]byte(text), &payload); e != nil || payload == nil { + return fmt.Errorf("Malformed BPS SSE event") + } + typ := stringValue(payload["type"]) + if typ == "" { + typ = event + } + event = "" + terminal = typ == "response.completed" || typ == "response.done" || typ == "response.failed" || typ == "response.incomplete" || typ == "error" + return consume(typ, payload) + } + for scanner.Scan() { + line := scanner.Text() + if line == "" { + if e := dispatch(); e != nil { + return e + } + if terminal { + return nil + } + continue + } + if strings.HasPrefix(line, "event:") { + event = strings.TrimSpace(strings.TrimPrefix(line, "event:")) + } + if strings.HasPrefix(line, "data:") { + if data.Len() > 0 { + data.WriteByte('\n') + } + data.WriteString(strings.TrimPrefix(strings.TrimPrefix(line, "data:"), " ")) + if data.Len() > maxSize { + return fmt.Errorf("BPS event exceeds maximum size") + } + } + } + if e := scanner.Err(); e != nil { + return e + } + return dispatch() +} + +func bpsReadUsage(response map[string]any) OpenAIUsage { + data, _ := json.Marshal(response["usage"]) + var usage struct { + Input int `json:"input_tokens"` + Output int `json:"output_tokens"` + Details struct { + Cached int `json:"cached_tokens"` + Written int `json:"cache_write_tokens"` + } `json:"input_tokens_details"` + } + _ = json.Unmarshal(data, &usage) + return OpenAIUsage{InputTokens: usage.Input, OutputTokens: usage.Output, CacheReadInputTokens: usage.Details.Cached, CacheCreationInputTokens: usage.Details.Written} +} + +func (s *OpenAIGatewayService) forwardOpenAIBPS(ctx context.Context, c *gin.Context, account *Account, body []byte) (result *OpenAIForwardResult, err error) { + started := time.Now() + defer func() { + if err != nil { + var failover *UpstreamFailoverError + if !errors.As(err, &failover) { + WriteOpenAIBPSError(c, err) + } + } + }() + if _, ok := ctx.Value(bpsRoutingContextKey{}).(bpsRoutingContext); !ok { + if err = s.PrepareOpenAIBPSRouting(c, body); err != nil { + return nil, err + } + ctx = c.Request.Context() + } + if !bpsBoundAccountAllowed(ctx, account) { + return nil, &bpsError{409, "bps_account_unavailable", "The account bound to this BPS conversation is unavailable"} + } + r, err := s.prepareOpenAIBPS(ctx, c, account, body) + if err != nil { + return nil, err + } + req, err := buildOpenAIBPSRequest(ctx, account, r.Body) + if err != nil { + if s.accountRepo != nil && account.bpsTokenExpired() { + _ = s.accountRepo.SetError(ctx, account.ID, "BPS access token expired; replace it manually") + } + return nil, err + } + proxyURL := "" + if account.ProxyID != nil && account.Proxy != nil { + proxyURL = account.Proxy.URL() + } + SetActualOpenAIUpstreamEndpoint(c, "/basispoints/api/responses") + resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency) + if err != nil { + if !bpsHasBinding(ctx) && ctx.Err() == nil { + return nil, &UpstreamFailoverError{StatusCode: 502, ClientMessage: "BPS upstream is temporarily unavailable"} + } + return nil, err + } + defer resp.Body.Close() + // Bound silent upstream stalls. The timer only closes the reader; all + // downstream writes and stream state remain on this goroutine. + var timedOut atomic.Bool + idle := 5 * time.Minute + if s.cfg != nil && s.cfg.Gateway.StreamDataIntervalTimeout > 0 { + idle = time.Duration(s.cfg.Gateway.StreamDataIntervalTimeout) * time.Second + } + timer := time.AfterFunc(idle, func() { timedOut.Store(true); _ = resp.Body.Close() }) + defer timer.Stop() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, s.bpsHTTPError(ctx, c, account, resp, r.Model) + } + if err = s.bpsBind(ctx, r.Scope, account); err != nil { + return nil, err + } + result = &OpenAIForwardResult{Model: stringValue(r.Source["model"]), UpstreamModel: r.Model, BillingModel: r.Model, Stream: r.Stream, RequestID: resp.Header.Get("x-request-id"), UpstreamHeaders: resp.Header.Clone(), UpstreamEndpoint: "/basispoints/api/responses", ReasoningEffort: &r.Effort} + sequence := 0 + created := false + completed := false + seenItems := map[string]bool{} + pendingTools := map[string]bool{} + emit := func(event string, payload map[string]any) error { + if !r.Stream { + return nil + } + if !c.Writer.Written() { + c.Header("Content-Type", "text/event-stream") + c.Header("Cache-Control", "no-cache") + c.Header("X-Accel-Buffering", "no") + } + payload["type"] = event + payload["sequence_number"] = sequence + sequence++ + c.Set("bps_sequence", sequence) + if response, ok := payload["response"].(map[string]any); ok { + c.Set("bps_response_id", response["id"]) + } + data, _ := json.Marshal(payload) + if _, e := fmt.Fprintf(c.Writer, "event: %s\ndata: %s\n\n", event, data); e != nil { + return e + } + c.Writer.Flush() + if result.FirstTokenMs == nil && (event == "response.output_text.delta" || event == "response.output_item.done") { + ms := int(time.Since(started).Milliseconds()) + result.FirstTokenMs = &ms + } + return nil + } + maxSize := 16 << 20 + if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { + maxSize = s.cfg.Gateway.MaxLineSize + } + err = readBPSEvents(resp, maxSize, func(typ string, payload map[string]any) error { + timer.Reset(idle) + if completed { + return nil + } + if typ == "response.failed" || typ == "response.incomplete" || typ == "error" { + if v, ok := payload["response"].(map[string]any); ok { + result.Usage = bpsReadUsage(v) + } + return &bpsError{502, "bps_response_failed", "BPS failed to complete the response"} + } + if typ == "response.completed" || typ == "response.done" { + response, ok := payload["response"].(map[string]any) + if !ok || response["status"] != "completed" { + return &bpsError{502, "bps_invalid_response", "BPS terminal event is not a completed response"} + } + result.Usage = bpsReadUsage(response) + result.ResponseID = stringValue(response["id"]) + result.UpstreamResponseModel = stringValue(response["model"]) + output, _ := response["output"].([]any) + for _, raw := range output { + item, _ := raw.(map[string]any) + if item["type"] == "function_call" || item["type"] == "custom_tool_call" { + delete(pendingTools, stringValue(item["id"])+"\x00"+stringValue(item["call_id"])) + } + } + if len(pendingTools) > 0 { + return &bpsError{502, "bps_invalid_tool_call", "BPS completed response omitted an original tool item"} + } + transformed, e := s.bpsTransformResponse(ctx, account, r, response) + if e != nil { + return e + } + if !r.Stream { + if r.Compact && isOpenAIResponsesCompactPath(c) { + transformed["object"] = "response.compaction" + } + c.JSON(http.StatusOK, transformed) + completed = true + return nil + } + if !created { + initial := map[string]any{} + for k, v := range transformed { + initial[k] = v + } + initial["output"] = []any{} + initial["status"] = "in_progress" + if e = emit("response.created", map[string]any{"response": initial}); e != nil { + return e + } + created = true + } + output, _ = transformed["output"].([]any) + for i, raw := range output { + item, ok := raw.(map[string]any) + if !ok { + continue + } + kind := stringValue(item["type"]) + if kind != "function_call" && kind != "custom_tool_call" && kind != "compaction" { + if seenItems[stringValue(item["id"])] { + continue + } + if e = bpsEmitBufferedItem(i, item, emit); e != nil { + return e + } + continue + } + added := map[string]any{} + for k, v := range item { + added[k] = v + } + added["status"] = "in_progress" + if kind == "function_call" { + added["arguments"] = "" + } + if kind == "custom_tool_call" { + added["input"] = "" + } + if e = emit("response.output_item.added", map[string]any{"output_index": i, "item": added}); e != nil { + return e + } + if kind == "function_call" || kind == "custom_tool_call" { + prefix := "response.function_call_arguments" + field := "arguments" + if kind == "custom_tool_call" { + prefix = "response.custom_tool_call_input" + field = "input" + } + if e = emit(prefix+".delta", map[string]any{"item_id": item["id"], "output_index": i, "delta": item[field]}); e != nil { + return e + } + if e = emit(prefix+".done", map[string]any{"item_id": item["id"], "output_index": i, field: item[field]}); e != nil { + return e + } + } + if e = emit("response.output_item.done", map[string]any{"output_index": i, "item": item}); e != nil { + return e + } + } + if e = emit("response.completed", map[string]any{"response": transformed}); e != nil { + return e + } + completed = true + return nil + } + item, _ := payload["item"].(map[string]any) + if typ == "response.output_item.done" && (item["type"] == "function_call" || item["type"] == "custom_tool_call") { + if len(pendingTools) >= 1024 { + return &bpsError{502, "bps_invalid_tool_call", "BPS returned too many pending tool items"} + } + pendingTools[stringValue(item["id"])+"\x00"+stringValue(item["call_id"])] = true + } + if r.Compact { + return nil + } + if r.Structured != nil && bpsStructuredMessageEvent(typ, item) { + return nil + } + if strings.HasPrefix(typ, "response.function_call_arguments.") || strings.HasPrefix(typ, "response.custom_tool_call_input.") { + return nil + } + if item, ok := payload["item"].(map[string]any); ok { + if item["type"] == "function_call" || item["type"] == "custom_tool_call" { + return nil + } + if item["type"] != "message" && item["type"] != "reasoning" { + return &bpsError{502, "bps_unsupported_tool", "BPS returned an unsupported output item"} + } + if typ == "response.output_item.done" { + seenItems[stringValue(item["id"])] = true + } + } + if response, ok := payload["response"].(map[string]any); ok { + response["model"] = r.Source["model"] + response["output"] = []any{} + if r.Structured != nil { + delete(response, "output_text") + response["text"] = map[string]any{"format": r.Structured.Format} + } + } + if typ == "response.created" { + created = true + } + if !bpsSafeStreamingEvent(typ) { + return &bpsError{502, "bps_unsupported_event", "BPS returned an unsupported streaming event"} + } + return emit(typ, payload) + }) + result.Duration = time.Since(started) + if timedOut.Load() && !completed { + err = &bpsError{504, "bps_upstream_timeout", "BPS upstream stopped sending data"} + } + if err == nil && !completed { + err = &bpsError{502, "bps_stream_interrupted", "BPS stream ended before response.completed"} + } + if err != nil { + result.UpstreamTerminalEvent = "response.failed" + return result, err + } + result.UpstreamTerminalEvent = "response.completed" + return result, nil +} + +// Unary upstream responses still produce a complete Responses event sequence +// for a streaming client. Incremental SSE items have already been emitted. +func bpsEmitBufferedItem(index int, item map[string]any, emit func(string, map[string]any) error) error { + added := map[string]any{} + for k, v := range item { + added[k] = v + } + added["status"] = "in_progress" + if item["type"] == "message" { + added["content"] = []any{} + } + if err := emit("response.output_item.added", map[string]any{"output_index": index, "item": added}); err != nil { + return err + } + if item["type"] == "message" { + parts, _ := item["content"].([]any) + for i, raw := range parts { + part, ok := raw.(map[string]any) + if !ok || (part["type"] != "output_text" && part["type"] != "refusal") { + continue + } + field, prefix := "text", "response.output_text" + if part["type"] == "refusal" { + field, prefix = "refusal", "response.refusal" + } + fields := func() map[string]any { + return map[string]any{"item_id": item["id"], "output_index": index, "content_index": i} + } + payload := fields() + empty := map[string]any{} + for key, value := range part { + empty[key] = value + } + empty[field] = "" + payload["part"] = empty + if err := emit("response.content_part.added", payload); err != nil { + return err + } + payload = fields() + payload["delta"] = part[field] + if err := emit(prefix+".delta", payload); err != nil { + return err + } + payload = fields() + payload[field] = part[field] + if err := emit(prefix+".done", payload); err != nil { + return err + } + payload = fields() + payload["part"] = part + if err := emit("response.content_part.done", payload); err != nil { + return err + } + } + } + return emit("response.output_item.done", map[string]any{"output_index": index, "item": item}) +} + +func bpsSafeStreamingEvent(typ string) bool { + switch typ { + case "response.created", "response.in_progress", "response.queued", + "response.output_item.added", "response.output_item.done", + "response.content_part.added", "response.content_part.done", + "response.output_text.delta", "response.output_text.done", "response.output_text.annotation.added", + "response.refusal.delta", "response.refusal.done", + "response.reasoning_summary_part.added", "response.reasoning_summary_part.done", + "response.reasoning_summary_text.delta", "response.reasoning_summary_text.done", + "response.reasoning_text.delta", "response.reasoning_text.done": + return true + default: + return false + } +} diff --git a/backend/internal/service/openai_bps_protocol.go b/backend/internal/service/openai_bps_protocol.go new file mode 100644 index 000000000..86369f658 --- /dev/null +++ b/backend/internal/service/openai_bps_protocol.go @@ -0,0 +1,613 @@ +package service + +// BPS wire adaptation is informed by Nonary/ghcp_proxy (Unlicense), +// excel_upstream.py at ad23ce2db3b5212c0355762d981c3877322fb160. +// Credentials, tenant isolation and persistence are owned by Sub4API. +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "strings" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/santhosh-tekuri/jsonschema/v5" +) + +type bpsTool struct { + Name, Namespace, Kind string + Spec map[string]any + Schema *jsonschema.Schema +} +type bpsRequest struct { + APIKeyID int64 + Body []byte + Source map[string]any + Tools map[string]bpsTool + Scope, Model, Effort string + Compact, Stream, RequireTool bool + TurnID string + AgentIteration int + Structured *bpsStructuredOutput +} +type bpsNativeCall struct { + Native map[string]any `json:"native"` + Client map[string]any `json:"client"` +} +type bpsCompactState struct { + Summary string `json:"summary"` + TurnID string `json:"turn_id,omitempty"` + AgentIteration int `json:"agent_iteration,omitempty"` +} + +const bpsCompactPrefix = "bpscmp_v1_" +const bpsToolProtocol = `This request comes from an external Responses client. Its tools run in the client, not in Excel. Use only the client tools listed below. To request one, call the native run_officejs tool with its code field containing a JSON-encoded object: {"name":"catalog tool name","arguments":{...}} for a function. For a custom tool set summary to exactly codex2api.custom/CATALOG_NAME and put its exact raw input in code, without JSON wrapping or Markdown fences. The marker must include the exact namespace-qualified catalog name. Include the namespace in the catalog tool name. Populate the native wrapper fields summary, extended_summary, destructive=false and references=[]. For functions the code field is JSON text. For custom tools it is opaque client input; the proxy never evaluates it as JavaScript or OfficeJS. Request exactly one client tool at a time. Do not call workbook or Office tools. The proxy converts the request and the client executes it. After receiving its real result, continue the task. Do not repeat a successful tool call. Tool catalog: ` +const bpsSummaryPrompt = `Summarize the conversation so a successor assistant can continue the user's task after earlier messages are discarded. Preserve the user's requests and constraints, decisions, important paths and code, completed work, actual tool results and errors, pending work and the immediate next step. Incorporate relevant earlier summaries. Return only the summary as plain text. Do not call tools.` + +func bpsDecode(data []byte, v any) error { + dec := json.NewDecoder(bytes.NewReader(data)) + dec.UseNumber() + if err := dec.Decode(v); err != nil { + return err + } + var extra any + if err := dec.Decode(&extra); err != io.EOF { + return fmt.Errorf("expected one JSON value") + } + return nil +} +func bpsMessage(role, text string) map[string]any { + return map[string]any{"type": "message", "role": role, "content": []any{map[string]any{"type": "input_text", "text": text}}} +} +func bpsJSON(v any) string { data, _ := json.Marshal(v); return string(data) } + +func bpsCollectTools(raw any, namespace string, result map[string]bpsTool, catalog *[]any, depth int) error { + if depth > 8 { + return bpsInvalid("Tool namespaces are nested too deeply") + } + if raw == nil { + return nil + } + tools, ok := raw.([]any) + if !ok { + return bpsInvalid("tools must be an array") + } + for _, entry := range tools { + spec, ok := entry.(map[string]any) + if !ok { + return bpsInvalid("Invalid tool declaration") + } + name := strings.TrimSpace(stringValue(spec["name"])) + kind := stringValue(spec["type"]) + if name == "" { + return bpsInvalid("BPS only supports named function and custom client tools") + } + full := name + if namespace != "" { + full = namespace + "." + name + } + if kind == "namespace" { + if e := bpsCollectTools(spec["tools"], full, result, catalog, depth+1); e != nil { + return e + } + continue + } + if kind != "function" && kind != "custom" { + return bpsInvalid("BPS only supports function, custom and namespace client tools") + } + if previous, exists := result[full]; exists { + if bpsJSON(previous.Spec) != bpsJSON(spec) { + return bpsInvalid("Conflicting client tool: " + full) + } + continue + } + if len(result) >= 256 { + return bpsInvalid("Too many client tools") + } + tool := bpsTool{Name: name, Namespace: namespace, Kind: kind, Spec: spec} + declaration := map[string]any{"name": full, "type": kind, "description": spec["description"]} + if kind == "function" { + schema := spec["parameters"] + if schema == nil { + schema = spec["inputSchema"] + } + if schema == nil { + schema = spec["input_schema"] + } + if schema == nil { + schema = map[string]any{"type": "object"} + } + compiler := jsonschema.NewCompiler() + // Never fetch a client-supplied $ref from the network or local filesystem. + compiler.LoadURL = func(string) (io.ReadCloser, error) { + return nil, fmt.Errorf("external schema references are unsupported") + } + if e := compiler.AddResource("https://bps.invalid/tool.json", strings.NewReader(bpsJSON(schema))); e != nil { + return bpsInvalid("Invalid schema for " + full) + } + compiled, e := compiler.Compile("https://bps.invalid/tool.json") + if e != nil { + return bpsInvalid("Invalid or externally referenced schema for " + full) + } + tool.Schema = compiled + declaration["parameters"] = schema + } else { + declaration["format"] = spec["format"] + } + result[full] = tool + *catalog = append(*catalog, declaration) + } + return nil +} + +func (s *OpenAIGatewayService) prepareOpenAIBPS(ctx context.Context, c *gin.Context, account *Account, body []byte) (*bpsRequest, error) { + var source map[string]any + if bpsDecode(body, &source) != nil || source == nil { + return nil, bpsInvalid("Invalid Responses request") + } + if stringValue(source["previous_response_id"]) != "" { + return nil, bpsInvalid("BPS requires complete input history; previous_response_id is not supported") + } + if background, _ := source["background"].(bool); background { + return nil, bpsInvalid("BPS does not support background responses") + } + for _, key := range []string{"service_tier", "temperature", "top_p", "max_output_tokens"} { + if value, exists := source[key]; exists && value != nil { + if key == "service_tier" && (value == "auto" || value == "default") { + continue + } + return nil, bpsInvalid("BPS does not support " + key) + } + } + model := strings.TrimSpace(stringValue(source["model"])) + if model == "" { + return nil, bpsInvalid("model is required") + } + if !account.IsModelSupported(model) { + return nil, bpsInvalid("Model is not allowed by this BPS account") + } + r := &bpsRequest{APIKeyID: getAPIKeyIDFromContext(c), Source: source, Tools: map[string]bpsTool{}, Scope: s.bpsScope(c, body), Model: account.GetMappedModel(model), Effort: "medium"} + if routing, ok := ctx.Value(bpsRoutingContextKey{}).(bpsRoutingContext); ok { + r.Scope = routing.Scope + } + r.Stream, _ = source["stream"].(bool) + r.Compact = isOpenAIResponsesCompactPath(c) || HasCompactionTriggerInInput(body) + if !r.Compact { + var err error + r.Structured, err = bpsPrepareStructuredOutput(source["text"]) + if err != nil { + return nil, err + } + } + rawEffort := source["reasoning_effort"] + if raw, exists := source["reasoning"]; exists && raw != nil { + reasoning, ok := raw.(map[string]any) + if !ok { + return nil, bpsInvalid("reasoning must be an object") + } + if effort, exists := reasoning["effort"]; exists { + rawEffort = effort + } + } + if rawEffort != nil { + effort, ok := rawEffort.(string) + if !ok || effort == "" { + return nil, bpsInvalid("BPS reasoning effort must be low, medium, high or xhigh") + } + r.Effort = effort + } + if r.Effort == "x-high" { + r.Effort = "xhigh" + } + switch r.Effort { + case "low", "medium", "high", "xhigh": + default: + return nil, bpsInvalid("BPS reasoning effort must be low, medium, high or xhigh") + } + var input []any + switch v := source["input"].(type) { + case string: + input = []any{bpsMessage("user", v)} + case []any: + input = v + default: + return nil, bpsInvalid("input must be a string or an array") + } + var catalog []any + if !r.Compact && source["tool_choice"] != "none" { + if e := bpsCollectTools(source["tools"], "", r.Tools, &catalog, 0); e != nil { + return nil, e + } + for _, raw := range input { + if item, ok := raw.(map[string]any); ok && item["type"] == "additional_tools" { + if e := bpsCollectTools(item["tools"], "", r.Tools, &catalog, 0); e != nil { + return nil, e + } + } + } + if choice, ok := source["tool_choice"].(map[string]any); ok { + name := stringValue(choice["name"]) + if ns := stringValue(choice["namespace"]); ns != "" { + name = ns + "." + name + } + tool, found := r.Tools[name] + if !found { + return nil, bpsInvalid("tool_choice must name a declared client tool") + } + r.Tools = map[string]bpsTool{name: tool} + catalog = nil + if e := bpsCollectTools([]any{tool.Spec}, tool.Namespace, map[string]bpsTool{}, &catalog, 0); e != nil { + return nil, e + } + r.RequireTool = true + } else { + choice := stringValue(source["tool_choice"]) + if choice != "" && choice != "auto" && choice != "required" { + return nil, bpsInvalid("Unsupported tool_choice") + } + r.RequireTool = choice == "required" + } + } + if r.RequireTool && len(r.Tools) == 0 { + return nil, bpsInvalid("tool_choice requires at least one client tool") + } + translated := make([]any, 0, len(input)+3) + restoredCalls := map[string]bool{} + compactIndex := -1 + compactRef := "" + var lastCompact bpsCompactState + for index, raw := range input { + item, ok := raw.(map[string]any) + if !ok { + return nil, bpsInvalid("input items must be objects") + } + delete(item, "internal_chat_message_metadata_passthrough") + kind := stringValue(item["type"]) + switch kind { + case "function_call", "custom_tool_call": + id := stringValue(item["call_id"]) + if id == "" { + return nil, bpsInvalid("BPS tool history requires call_id") + } + var saved bpsNativeCall + if e := s.bpsGet(ctx, bpsStateKey(r.Scope, account, "call", id), &saved); e != nil { + return nil, e + } + translated = append(translated, saved.Native) + restoredCalls[id] = true + case "function_call_output", "custom_tool_call_output": + id := stringValue(item["call_id"]) + if id == "" { + return nil, bpsInvalid("BPS tool history requires call_id") + } + var saved bpsNativeCall + if e := s.bpsGet(ctx, bpsStateKey(r.Scope, account, "call", id), &saved); e != nil { + return nil, e + } + if !restoredCalls[id] { + translated = append(translated, saved.Native) + restoredCalls[id] = true + } + output := item["output"] + if bpsIsNativePlan(stringValue(saved.Native["name"])) && strings.EqualFold(strings.TrimSpace(stringValue(output)), "Plan updated") { + output = `{"status":"ok"}` + } + translated = append(translated, map[string]any{"type": "function_call_output", "id": bpsFunctionOutputID(id), "call_id": id, "output": output}) + case "reasoning": + if stringValue(item["encrypted_content"]) != "" { + translated = append(translated, map[string]any{"type": "reasoning", "summary": []any{}, "encrypted_content": item["encrypted_content"]}) + } + case "compaction", "compaction_summary": + ref := stringValue(item["encrypted_content"]) + if ref == "" && r.Compact { + continue + } + if !strings.HasPrefix(ref, bpsCompactPrefix) { + return nil, bpsInvalid("BPS cannot replay compaction created by another provider") + } + var compact bpsCompactState + if e := s.bpsGet(ctx, bpsStateKey(r.Scope, account, "compact", ref), &compact); e != nil { + return nil, e + } + translated = append(translated, bpsMessage("user", "\n"+compact.Summary+"\n")) + compactIndex, compactRef, lastCompact = index, ref, compact + case "compaction_trigger", "additional_tools": + continue + case "item_reference": + return nil, bpsInvalid("BPS requires full items instead of item_reference") + default: + if parts, ok := item["content"].([]any); ok { + for _, raw := range parts { + if part, ok := raw.(map[string]any); ok && (part["type"] == "input_image" || part["type"] == "input_audio" || part["type"] == "input_file") { + return nil, bpsInvalid("BPS currently supports text input only") + } + } + } + translated = append(translated, item) + } + } + prologue := []any{} + if instructions := stringValue(source["instructions"]); instructions != "" { + prologue = append(prologue, bpsMessage("developer", instructions)) + } + protocol := "This is an external Responses client without an Excel workbook. Return assistant text and do not call server-injected Excel or Office tools." + if len(r.Tools) > 0 { + protocol = bpsToolProtocol + bpsJSON(catalog) + if r.RequireTool { + protocol += " You must call one of the listed tools in this response." + } + } + if r.Structured != nil { + protocol += "\n" + r.Structured.instructions() + } + prologue = append(prologue, bpsMessage("developer", protocol)) + translated = append(prologue, translated...) + if r.Compact { + translated = append(translated, bpsMessage("user", bpsSummaryPrompt)) + } + r.TurnID, r.AgentIteration = bpsTurnState(r.Scope, input, compactIndex, compactRef, lastCompact) + metadata := map[string]any{"task_id": uuid.NewSHA1(uuid.NameSpaceURL, []byte(r.Scope)).String(), "turn_id": r.TurnID, "agent_iteration": fmt.Sprint(r.AgentIteration)} + upstream := map[string]any{"model": r.Model, "model_selection": "explicit", "stream": true, "store": false, "input": translated, "reasoning_effort": r.Effort, "metadata": metadata, "prompt_cache_key": bpsDigest(r.Scope)} + r.Body, _ = json.Marshal(upstream) + return r, nil +} + +func bpsIsNativePlan(name string) bool { + return name == "update_plan" || name == "functions.update_plan" +} + +func bpsPlanArguments(raw map[string]any) (map[string]any, error) { + textAlias := func(item map[string]any, keys ...string) (string, error) { + value := "" + present := false + for _, key := range keys { + if raw, exists := item[key]; exists { + candidate, ok := raw.(string) + if !ok || (present && value != candidate) { + return "", fmt.Errorf("ambiguous plan text fields") + } + value, present = candidate, true + } + } + return value, nil + } + plan, ok := raw["plan"].([]any) + if !ok { + return nil, fmt.Errorf("native update_plan requires a plan array") + } + normalized := make([]any, 0, len(plan)) + for _, entry := range plan { + p, ok := entry.(map[string]any) + if !ok { + return nil, fmt.Errorf("invalid native plan entry") + } + step, err := textAlias(p, "step", "description", "title") + if err != nil || strings.TrimSpace(step) == "" { + return nil, fmt.Errorf("missing or conflicting native plan step") + } + status := strings.NewReplacer("-", "_", " ", "_").Replace(strings.ToLower(strings.TrimSpace(stringValue(p["status"])))) + switch status { + case "pending", "not_started", "todo", "planned", "queued", "blocked": + status = "pending" + case "in_progress", "inprogress", "running", "active", "started", "doing", "current": + status = "in_progress" + case "completed", "done", "complete", "finished": + status = "completed" + default: + return nil, fmt.Errorf("unsupported native plan status") + } + normalized = append(normalized, map[string]any{"step": step, "status": status}) + } + result := map[string]any{"plan": normalized} + explanation, err := textAlias(raw, "explanation", "summary") + if err != nil { + return nil, err + } + if explanation != "" { + result["explanation"] = explanation + } + return result, nil +} + +func bpsConvertTool(native map[string]any, r *bpsRequest) (map[string]any, error) { + invalid := func(message string) (map[string]any, error) { + return nil, &bpsError{502, "bps_invalid_tool_call", message} + } + nativeName := stringValue(native["name"]) + name := nativeName + var args map[string]any + if value, ok := native["arguments"].(map[string]any); ok { + args = value + } else if bpsDecode([]byte(stringValue(native["arguments"])), &args) != nil { + return invalid("BPS returned malformed tool arguments") + } + if args == nil { + return invalid("BPS returned empty tool arguments") + } + var envelope map[string]any + marked := false + if nativeName == "run_officejs" || nativeName == "functions.run_officejs" { + var err error + envelope, marked, err = bpsCustomTransportEnvelope(args) + if err == nil && !marked { + envelope, err = bpsDecodeTransportEnvelope(args["code"]) + } + if err != nil { + return invalid(err.Error()) + } + name, err = bpsEnvelopeName(envelope) + if err != nil { + return invalid(err.Error()) + } + } else if !bpsIsNativePlan(nativeName) { + return nil, &bpsError{502, "bps_unsupported_tool", "BPS returned an undeclared server tool"} + } + tool, ok := r.Tools[name] + if !ok && bpsIsNativePlan(nativeName) { + for key, candidate := range r.Tools { + if candidate.Name == "update_plan" { + if ok { + return invalid("Ambiguous update_plan namespace") + } + name, tool, ok = key, candidate, true + } + } + } + if !ok { + return nil, &bpsError{502, "bps_unsupported_tool", "BPS returned a tool not declared by the client"} + } + callID, itemID := stringValue(native["call_id"]), stringValue(native["id"]) + if strings.TrimSpace(callID) == "" || strings.TrimSpace(callID) != callID || itemID == "" { + return invalid("BPS tool call is missing its native identity") + } + if marked && tool.Kind != "custom" { + return invalid("Raw tool transport requires a declared custom tool") + } + result := map[string]any{"type": "function_call", "id": itemID, "call_id": callID, "name": tool.Name, "status": "completed"} + if tool.Namespace != "" { + result["namespace"] = tool.Namespace + } + if tool.Kind == "custom" { + value, exists := envelope["input"] + if alias, hasAlias := envelope["args"]; hasAlias { + if exists { + return invalid("BPS custom envelope contains conflicting input fields") + } + value = alias + } + if _, exists := envelope["arguments"]; exists { + return invalid("BPS custom tools require raw input, not function arguments") + } + input, ok := value.(string) + if !ok || len(input) > bpsMaxEnvelopeBytes { + return invalid("BPS custom tool input must be text within 1 MiB") + } + result["type"], result["id"], result["input"] = "custom_tool_call", "ctc_"+callID, input + } else { + if envelope != nil { + value, err := bpsEnvelopeArguments(envelope) + if err != nil { + return invalid(err.Error()) + } + if text, ok := value.(string); ok { + if len(text) > bpsMaxEnvelopeBytes || bpsDecode([]byte(text), &value) != nil { + return invalid("BPS function arguments must be one JSON object") + } + } + args, _ = value.(map[string]any) + } else { + var err error + args, err = bpsPlanArguments(args) + if err != nil { + return invalid(err.Error()) + } + } + if args == nil || tool.Schema == nil || tool.Schema.Validate(args) != nil { + return invalid("BPS tool arguments do not match the client schema") + } + result["arguments"] = bpsJSON(args) + } + return result, nil +} + +func (s *OpenAIGatewayService) bpsTransformResponse(ctx context.Context, account *Account, r *bpsRequest, response map[string]any) (map[string]any, error) { + output, ok := response["output"].([]any) + if !ok { + return nil, &bpsError{502, "bps_invalid_response", "BPS response has no output array"} + } + for _, raw := range output { + item, ok := raw.(map[string]any) + if !ok { + return nil, &bpsError{502, "bps_invalid_response", "BPS returned a malformed output item"} + } + switch item["type"] { + case "message", "reasoning", "function_call", "custom_tool_call": + default: + return nil, &bpsError{502, "bps_unsupported_tool", "BPS returned an unsupported output item"} + } + } + if r.Structured != nil { + if err := r.Structured.validate(response); err != nil { + return nil, err + } + config, _ := response["text"].(map[string]any) + if config == nil { + config = map[string]any{} + } + config["format"] = r.Structured.Format + response["text"] = config + delete(response, "output_text") + } + if r.Compact { + summary := bpsOutputText(response) + if strings.TrimSpace(summary) == "" { + return nil, &bpsError{502, "bps_compaction_failed", "BPS did not return a conversation summary"} + } + for _, raw := range output { + if item, ok := raw.(map[string]any); ok && (item["type"] == "function_call" || item["type"] == "custom_tool_call") { + return nil, &bpsError{502, "bps_compaction_failed", "BPS requested a tool instead of returning a summary"} + } + } + ref := bpsCompactPrefix + uuid.NewString() + if e := s.bpsPut(ctx, bpsStateKey(r.Scope, account, "compact", ref), bpsCompactState{Summary: summary, TurnID: r.TurnID, AgentIteration: r.AgentIteration}); e != nil { + return nil, e + } + if e := s.bpsPut(ctx, bpsCompactReferenceKey(r.APIKeyID, ref), bpsCompactReference{Scope: r.Scope}); e != nil { + return nil, e + } + response["output"] = []any{map[string]any{"type": "compaction", "id": "cmp_" + uuid.NewString(), "status": "completed", "encrypted_content": ref}} + delete(response, "output_text") + } else { + count := 0 + for _, raw := range output { + if item, ok := raw.(map[string]any); ok && (item["type"] == "function_call" || item["type"] == "custom_tool_call") { + count++ + } + } + if count > 1 { + return nil, &bpsError{502, "bps_parallel_tools_unsupported", "BPS must return one client tool at a time"} + } + if r.RequireTool && count == 0 { + return nil, &bpsError{502, "bps_tool_required", "BPS did not return the required client tool"} + } + for i, raw := range output { + item, ok := raw.(map[string]any) + if !ok { + continue + } + if item["type"] != "function_call" && item["type"] != "custom_tool_call" { + continue + } + client, e := bpsConvertTool(item, r) + if e != nil { + return nil, e + } + if e = s.bpsPut(ctx, bpsStateKey(r.Scope, account, "call", stringValue(item["call_id"])), bpsNativeCall{Native: item, Client: client}); e != nil { + return nil, e + } + output[i] = client + } + response["output"] = output + } + response["model"] = r.Source["model"] + return response, nil +} +func bpsOutputText(response map[string]any) string { + var parts []string + output, _ := response["output"].([]any) + for _, raw := range output { + item, ok := raw.(map[string]any) + if !ok || item["type"] != "message" { + continue + } + content, _ := item["content"].([]any) + for _, v := range content { + if part, ok := v.(map[string]any); ok && part["type"] == "output_text" { + parts = append(parts, stringValue(part["text"])) + } + } + } + return strings.Join(parts, "\n") +} diff --git a/backend/internal/service/openai_bps_state.go b/backend/internal/service/openai_bps_state.go new file mode 100644 index 000000000..4a21170e5 --- /dev/null +++ b/backend/internal/service/openai_bps_state.go @@ -0,0 +1,230 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" +) + +const OpenAIBPSStateTTL = 7 * 24 * time.Hour + +// Implemented by the Redis gateway cache. No in-process fallback: tool history +// must survive an instance change and must never be shared between API keys. +type OpenAIBPSStateStore interface { + BPSGet(context.Context, string) ([]byte, error) + BPSPut(context.Context, string, []byte) error + BPSBind(context.Context, string, []byte) ([]byte, error) +} + +type bpsSessionBinding struct { + AccountID int64 `json:"account_id"` + Identity string `json:"identity"` +} +type bpsRoutingContext struct { + Scope string + Binding *bpsSessionBinding +} +type bpsRoutingContextKey struct{} + +type bpsError struct { + Status int + Code, Message string +} + +func (e *bpsError) Error() string { return e.Message } +func bpsInvalid(message string) error { return &bpsError{400, "invalid_request_error", message} } +func bpsExpired() error { + return &bpsError{409, "bps_context_expired", "BPS conversation state has expired; start a new conversation"} +} +func bpsUnavailable() error { + return &bpsError{503, "bps_state_unavailable", "BPS conversation state is temporarily unavailable"} +} +func bpsDigest(s string) string { d := sha256.Sum256([]byte(s)); return hex.EncodeToString(d[:]) } +func (s *OpenAIGatewayService) bpsStateStore() (OpenAIBPSStateStore, error) { + store, ok := s.cache.(OpenAIBPSStateStore) + if !ok { + return nil, bpsUnavailable() + } + return store, nil +} +func (s *OpenAIGatewayService) bpsExplicitSession(c *gin.Context, body []byte) string { + session := s.ExtractSessionID(c, body) + if session == "" { + for _, key := range []string{"client_metadata.session_id", "client_metadata.sessionId", "session_id", "sessionId", "promptCacheKey"} { + if value := gjson.GetBytes(body, key).String(); value != "" { + session = value + break + } + } + } + return strings.TrimSpace(session) +} + +func (s *OpenAIGatewayService) bpsScope(c *gin.Context, body []byte) string { + session := s.bpsExplicitSession(c, body) + if session != "" { + session = "explicit:" + session + } else { + input := gjson.GetBytes(body, "input") + if input.Type == gjson.String { + session = "root:" + input.String() + } else { + for _, item := range input.Array() { + if item.Get("role").String() != "user" { + continue + } + content := item.Get("content") + if content.Type == gjson.String { + session = "root:" + content.String() + } else { + var texts []string + for _, part := range content.Array() { + if part.Get("type").String() == "input_text" { + texts = append(texts, part.Get("text").String()) + } + } + session = "root:" + strings.Join(texts, "\n") + } + break + } + } + } + return "openai_bps:" + bpsDigest(fmt.Sprintf("%d:%s", getAPIKeyIDFromContext(c), session)) +} + +type bpsCompactReference struct { + Scope string `json:"scope"` +} + +func bpsCompactReferenceKey(apiKeyID int64, ref string) string { + return "openai_bps:ref:" + bpsDigest(fmt.Sprintf("%d:%s", apiKeyID, ref)) +} + +// PrepareOpenAIBPSRouting runs before account selection. An established binding +// is a hard constraint, not a sticky preference that can silently fail over. +func (s *OpenAIGatewayService) PrepareOpenAIBPSRouting(c *gin.Context, body []byte) error { + store, err := s.bpsStateStore() + if err != nil { + return err + } + scope := s.bpsScope(c, body) + // A compacted history no longer contains the original user message. Recover + // its root from a tenant-scoped opaque reference when no session ID exists. + if s.bpsExplicitSession(c, body) == "" { + for _, item := range gjson.GetBytes(body, "input").Array() { + if item.Get("type").String() != "compaction" && item.Get("type").String() != "compaction_summary" { + continue + } + ref := item.Get("encrypted_content").String() + if !strings.HasPrefix(ref, bpsCompactPrefix) { + continue + } + var reference bpsCompactReference + if err := s.bpsGet(c.Request.Context(), bpsCompactReferenceKey(getAPIKeyIDFromContext(c), ref), &reference); err != nil { + return err + } + if reference.Scope == "" { + return bpsExpired() + } + scope = reference.Scope + break + } + } + data, err := store.BPSGet(c.Request.Context(), scope+":session") + if err != nil { + return bpsUnavailable() + } + routing := bpsRoutingContext{Scope: scope} + if len(data) > 0 { + var binding bpsSessionBinding + if json.Unmarshal(data, &binding) != nil { + return bpsExpired() + } + routing.Binding = &binding + } else { + for _, item := range gjson.GetBytes(body, "input").Array() { + // A text-only continuation still belongs to its established account. + if item.Get("role").String() == "assistant" { + return bpsExpired() + } + switch item.Get("type").String() { + case "function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output", "reasoning", "compaction", "compaction_summary": + if item.Get("encrypted_content").String() != "" || item.Get("call_id").String() != "" { + return bpsExpired() + } + } + } + } + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), bpsRoutingContextKey{}, routing)) + return nil +} + +func bpsBoundAccountAllowed(ctx context.Context, account *Account) bool { + routing, ok := ctx.Value(bpsRoutingContextKey{}).(bpsRoutingContext) + return !ok || routing.Binding == nil || (account.ID == routing.Binding.AccountID && account.GetCredential("chatgpt_account_id") == routing.Binding.Identity) +} +func bpsHasBinding(ctx context.Context) bool { + r, ok := ctx.Value(bpsRoutingContextKey{}).(bpsRoutingContext) + return ok && r.Binding != nil +} + +func (s *OpenAIGatewayService) bpsBind(ctx context.Context, scope string, account *Account) error { + store, err := s.bpsStateStore() + if err != nil { + return err + } + binding := bpsSessionBinding{account.ID, account.GetCredential("chatgpt_account_id")} + data, _ := json.Marshal(binding) + actual, err := store.BPSBind(ctx, scope+":session", data) + if err != nil { + return bpsUnavailable() + } + var saved bpsSessionBinding + if json.Unmarshal(actual, &saved) != nil || saved != binding { + return &bpsError{409, "bps_account_conflict", "This BPS conversation is bound to another account"} + } + return nil +} +func bpsStateKey(scope string, account *Account, kind, id string) string { + return fmt.Sprintf("%s:%d:%s:%s", scope, account.ID, kind, bpsDigest(id)) +} +func (s *OpenAIGatewayService) bpsGet(ctx context.Context, key string, v any) error { + store, e := s.bpsStateStore() + if e != nil { + return e + } + data, e := store.BPSGet(ctx, key) + if e != nil { + return bpsUnavailable() + } + if len(data) == 0 || json.Unmarshal(data, v) != nil { + return bpsExpired() + } + return nil +} +func (s *OpenAIGatewayService) bpsPut(ctx context.Context, key string, v any) error { + store, e := s.bpsStateStore() + if e != nil { + return e + } + data, e := json.Marshal(v) + if e != nil { + return e + } + if e = store.BPSPut(ctx, key, data); e != nil { + return bpsUnavailable() + } + return nil +} + +func OpenAIBPSHasBinding(ctx context.Context) bool { return bpsHasBinding(ctx) } +func WriteOpenAIBPSAccountUnavailable(c *gin.Context) { + WriteOpenAIBPSError(c, &bpsError{409, "bps_account_unavailable", "The account bound to this BPS conversation is unavailable; restore that account or start a new conversation"}) +} diff --git a/backend/internal/service/openai_bps_structured.go b/backend/internal/service/openai_bps_structured.go new file mode 100644 index 000000000..a28bb876e --- /dev/null +++ b/backend/internal/service/openai_bps_structured.go @@ -0,0 +1,159 @@ +package service + +// Adapted from ranxi2001/sub2api at 055a1cd1470b3b866d04aad8d1514bd34cac73ab. +// See docs/openai-bps-sources.md. Validation uses this project's existing schema library. +import ( + "fmt" + "io" + "regexp" + "strings" + + "github.com/santhosh-tekuri/jsonschema/v5" +) + +const bpsStructuredSchemaURL = "https://bps.invalid/structured-output.json" +const bpsMaxStructuredTextBytes = 16 << 20 + +var bpsStructuredName = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`) + +type bpsStructuredOutput struct { + Format map[string]any + Schema *jsonschema.Schema +} + +func bpsPrepareStructuredOutput(raw any) (*bpsStructuredOutput, error) { + if raw == nil { + return nil, nil + } + config, ok := raw.(map[string]any) + if !ok { + return nil, bpsInvalid("text must be an object") + } + if config["format"] == nil { + return nil, nil + } + format, ok := config["format"].(map[string]any) + if !ok { + return nil, bpsInvalid("text.format must be an object") + } + kind := stringValue(format["type"]) + if kind == "text" { + return nil, nil + } + if kind != "json_object" && kind != "json_schema" { + return nil, bpsInvalid("text.format.type must be text, json_object or json_schema") + } + for key := range format { + if key == "type" || (kind == "json_schema" && (key == "name" || key == "schema" || key == "strict" || key == "description")) { + continue + } + return nil, bpsInvalid("Unsupported text.format field: " + key) + } + result := &bpsStructuredOutput{Format: format} + if kind == "json_object" { + return result, nil + } + if !bpsStructuredName.MatchString(stringValue(format["name"])) { + return nil, bpsInvalid("json_schema requires a name of 1-64 letters, digits, underscores or hyphens") + } + if value := format["strict"]; value != nil { + if _, ok := value.(bool); !ok { + return nil, bpsInvalid("json_schema strict must be a boolean") + } + } + if value := format["description"]; value != nil { + if _, ok := value.(string); !ok { + return nil, bpsInvalid("json_schema description must be text") + } + } + schema, ok := format["schema"].(map[string]any) + if !ok || schema == nil { + return nil, bpsInvalid("json_schema requires a schema object") + } + encoded := bpsJSON(schema) + if len(encoded) > 1<<20 { + return nil, bpsInvalid("BPS structured output schema exceeds 1 MiB") + } + compiler := jsonschema.NewCompiler() + compiler.Draft = jsonschema.Draft2020 + compiler.AssertFormat = true + compiler.LoadURL = func(string) (io.ReadCloser, error) { + return nil, fmt.Errorf("external schema references are unsupported") + } + if err := compiler.AddResource(bpsStructuredSchemaURL, strings.NewReader(encoded)); err != nil { + return nil, bpsInvalid("Invalid structured output schema") + } + compiled, err := compiler.Compile(bpsStructuredSchemaURL) + if err != nil { + return nil, bpsInvalid("Invalid structured output schema or external reference") + } + result.Schema = compiled + return result, nil +} + +func (s *bpsStructuredOutput) instructions() string { + instruction := "The client requires a structured final answer. Return exactly one JSON object without Markdown fences or surrounding prose. Tool calls and explicit refusals remain separate protocol items; use declared client tools as needed before the final answer. The proxy validates your final answer before returning it." + if s.Schema != nil { + instruction = "The client requires a structured final answer. Return exactly one JSON value without Markdown fences or surrounding prose, satisfying this output format: " + bpsJSON(s.Format) + ". Tool calls and explicit refusals remain separate protocol items; use declared client tools as needed before the final answer. The proxy validates your final answer before returning it." + } + return instruction +} +func bpsInvalidStructured(message string) error { + return &bpsError{502, "bps_invalid_structured_output", message} +} +func (s *bpsStructuredOutput) validate(response map[string]any) error { + output, _ := response["output"].([]any) + var answer strings.Builder + hasTool, hasRefusal := false, false + for _, raw := range output { + item, _ := raw.(map[string]any) + kind := stringValue(item["type"]) + hasTool = hasTool || kind == "function_call" || kind == "custom_tool_call" + if kind != "message" { + continue + } + content, ok := item["content"].([]any) + if !ok { + return bpsInvalidStructured("BPS structured message has invalid content") + } + for _, rawPart := range content { + part, ok := rawPart.(map[string]any) + if !ok { + return bpsInvalidStructured("BPS structured message has invalid content") + } + switch part["type"] { + case "output_text": + value, ok := part["text"].(string) + if !ok || len(value) > bpsMaxStructuredTextBytes-answer.Len() { + return bpsInvalidStructured("BPS structured answer is invalid or exceeds 16 MiB") + } + answer.WriteString(value) + case "refusal": + if _, ok := part["refusal"].(string); !ok { + return bpsInvalidStructured("BPS refusal must contain text") + } + hasRefusal = true + default: + return bpsInvalidStructured("BPS structured answer contains unsupported message content") + } + } + } + if hasTool || (hasRefusal && answer.Len() == 0) { + return nil + } + var value any + if bpsDecode([]byte(answer.String()), &value) != nil { + return bpsInvalidStructured("BPS final answer is not one valid JSON value") + } + if s.Schema == nil { + if _, ok := value.(map[string]any); !ok { + return bpsInvalidStructured("BPS json_object answer must be an object") + } + } else if s.Schema.Validate(value) != nil { + return bpsInvalidStructured("BPS final answer does not satisfy the requested JSON schema") + } + return nil +} +func bpsStructuredMessageEvent(kind string, item map[string]any) bool { + return strings.HasPrefix(kind, "response.output_text.") || strings.HasPrefix(kind, "response.refusal.") || strings.HasPrefix(kind, "response.content_part.") || (strings.HasPrefix(kind, "response.output_item.") && item["type"] == "message") +} diff --git a/backend/internal/service/openai_bps_structured_test.go b/backend/internal/service/openai_bps_structured_test.go new file mode 100644 index 000000000..15b40a137 --- /dev/null +++ b/backend/internal/service/openai_bps_structured_test.go @@ -0,0 +1,184 @@ +package service + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func bpsTestStructuredFormat(strict bool) map[string]any { + return map[string]any{"type": "json_schema", "name": "answer", "strict": strict, "schema": map[string]any{"type": "object", "properties": map[string]any{"ok": map[string]any{"type": "boolean"}}, "required": []any{"ok"}, "additionalProperties": false}} +} +func bpsTestStructuredRequest(format map[string]any, stream bool) map[string]any { + return map[string]any{"model": "gpt-6-astra", "input": "Answer the request", "stream": stream, "text": map[string]any{"format": format}} +} + +func TestOpenAIBPSStructuredJSONAndSSE(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, strict := range []bool{false, true} { + for _, valid := range []bool{false, true} { + name := bpsJSON([]bool{stream, strict, valid}) + t.Run(name, func(t *testing.T) { + s, a := bpsFixture() + c, rec := bpsContext(1, "/responses") + format := bpsTestStructuredFormat(strict) + text := `{"ok":true}` + if !valid { + text = `{"ok":"wrong"}` + } + final := bpsResponse(bpsText(text)) + up := &bpsHTTPStub{contentType: "application/json", body: bpsJSON(final)} + if stream { + up.contentType = "text/event-stream" + up.body = bpsEvent("response.created", map[string]any{"response": map[string]any{"id": "r1", "status": "in_progress", "output": []any{}, "output_text": "unchecked-created"}}) + + bpsEvent("response.output_item.added", map[string]any{"output_index": 0, "item": bpsText("unchecked-item")}) + + bpsEvent("response.output_text.delta", map[string]any{"item_id": "msg_test", "output_index": 0, "content_index": 0, "delta": "unchecked-delta"}) + + bpsEvent("response.output_item.done", map[string]any{"output_index": 0, "item": bpsText("unchecked-done")}) + + bpsEvent("response.completed", map[string]any{"response": final}) + } + s.httpUpstream = up + result, err := s.Forward(c.Request.Context(), c, a, []byte(bpsJSON(bpsTestStructuredRequest(format, stream)))) + require.NotNil(t, result) + require.Equal(t, 100, result.Usage.InputTokens) + require.Equal(t, 12, result.Usage.OutputTokens) + require.NotContains(t, rec.Body.String(), "unchecked-") + require.False(t, gjson.GetBytes(up.requestBody, "text").Exists()) + require.Contains(t, string(up.requestBody), "structured final answer") + require.Equal(t, 1, up.requests) + if valid { + require.NoError(t, err) + if stream { + require.Contains(t, rec.Body.String(), "event: response.output_text.delta") + require.Contains(t, rec.Body.String(), "event: response.completed") + } else { + require.Equal(t, 200, rec.Code) + require.Equal(t, "json_schema", gjson.Get(rec.Body.String(), "text.format.type").String()) + require.Equal(t, text, gjson.Get(rec.Body.String(), "output.0.content.0.text").String()) + } + } else { + require.Error(t, err) + require.Contains(t, rec.Body.String(), "bps_invalid_structured_output") + require.NotContains(t, rec.Body.String(), "event: response.completed") + if stream { + require.Contains(t, rec.Body.String(), "event: response.failed") + } else { + require.Equal(t, 502, rec.Code) + } + } + }) + } + } + } +} + +func TestOpenAIBPSStructuredValidationBoundaries(t *testing.T) { + object, err := bpsPrepareStructuredOutput(map[string]any{"format": map[string]any{"type": "json_object"}}) + require.NoError(t, err) + for _, text := range []string{`[]`, `null`, `true`, `{"ok":true} trailing`, `{"ok":true}{}`, "```json\n{}\n```", ""} { + require.Error(t, object.validate(bpsResponse(bpsText(text))), text) + } + require.NoError(t, object.validate(bpsResponse(bpsText(`{"ok":true}`)))) + require.Error(t, object.validate(bpsResponse(bpsText(strings.Repeat(" ", bpsMaxStructuredTextBytes+1))))) + var format map[string]any + require.NoError(t, bpsDecode([]byte(`{"type":"json_schema","name":"large","schema":{"type":"object","properties":{"id":{"const":9007199254740993}},"required":["id"]}}`), &format)) + large, err := bpsPrepareStructuredOutput(map[string]any{"format": format}) + require.NoError(t, err) + require.NoError(t, large.validate(bpsResponse(bpsText(`{"id":9007199254740993}`)))) + require.Error(t, large.validate(bpsResponse(bpsText(`{"id":9007199254740992}`)))) + require.IsType(t, json.Number(""), format["schema"].(map[string]any)["properties"].(map[string]any)["id"].(map[string]any)["const"]) + // Only references within this schema document are permitted. + require.NoError(t, bpsDecode([]byte(`{"type":"json_schema","name":"local","schema":{"type":"object","$defs":{"flag":{"type":"boolean"}},"properties":{"ok":{"$ref":"#/$defs/flag"}},"required":["ok"]}}`), &format)) + local, err := bpsPrepareStructuredOutput(map[string]any{"format": format}) + require.NoError(t, err) + require.NoError(t, local.validate(bpsResponse(bpsText(`{"ok":true}`)))) + for _, schema := range []map[string]any{{"$ref": "file:///etc/passwd"}, {"$ref": "https://example.invalid/schema.json"}, {"type": "invalid"}, {"description": strings.Repeat("x", 1<<20)}} { + _, err := bpsPrepareStructuredOutput(map[string]any{"format": map[string]any{"type": "json_schema", "name": "bad", "schema": schema}}) + require.Error(t, err) + } + for _, format := range []any{true, map[string]any{"type": "unknown"}, map[string]any{"type": "json_schema", "name": "bad name", "schema": map[string]any{}}, map[string]any{"type": "json_schema", "name": "ok", "strict": "yes", "schema": map[string]any{}}, map[string]any{"type": "json_schema", "name": "ok"}} { + s, a := bpsFixture() + up := &bpsHTTPStub{} + s.httpUpstream = up + c, rec := bpsContext(1, "/responses") + _, err := s.Forward(c.Request.Context(), c, a, []byte(bpsJSON(map[string]any{"model": "gpt-6-astra", "input": "test", "text": map[string]any{"format": format}}))) + require.Error(t, err) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Zero(t, up.requests) + } +} + +func TestOpenAIBPSStructuredToolsRefusalsAndCompaction(t *testing.T) { + for _, stream := range []bool{false, true} { + s, a := bpsFixture() + c, rec := bpsContext(1, "/responses") + source := bpsTestStructuredRequest(bpsTestStructuredFormat(true), stream) + source["input"] = []any{bpsMessage("user", "inspect then return JSON")} + source["tools"] = []any{bpsFunction("exec")} + native := bpsNative("structured_tool", "exec", map[string]any{"command": "pwd"}) + s.httpUpstream = &bpsHTTPStub{body: bpsJSON(bpsResponse(bpsText("Inspecting first"), native)), contentType: "application/json"} + _, err := s.Forward(c.Request.Context(), c, a, []byte(bpsJSON(source))) + require.NoError(t, err) + require.Contains(t, rec.Body.String(), "function_call") + require.NotContains(t, rec.Body.String(), "run_officejs") + call := map[string]any{"type": "function_call", "id": "fc_structured_tool", "call_id": "structured_tool", "name": "exec", "arguments": `{"command":"pwd"}`} + source["input"] = append(source["input"].([]any), call, map[string]any{"type": "function_call_output", "call_id": "structured_tool", "output": "/workspace"}) + s.httpUpstream = &bpsHTTPStub{body: bpsJSON(bpsResponse(bpsText(`{"ok":true}`))), contentType: "application/json"} + next, nextRec := bpsContext(1, "/responses") + _, err = s.Forward(next.Request.Context(), next, a, []byte(bpsJSON(source))) + require.NoError(t, err) + require.NotContains(t, nextRec.Body.String(), "bps_invalid_structured_output") + // A pure refusal is a protocol item, not a fabricated JSON answer. + refusal := map[string]any{"type": "message", "id": "msg_refusal", "role": "assistant", "status": "completed", "content": []any{map[string]any{"type": "refusal", "refusal": "Cannot provide that"}}} + s.httpUpstream = &bpsHTTPStub{body: bpsJSON(bpsResponse(refusal)), contentType: "application/json"} + refusalCtx, refusalRec := bpsContext(2, "/responses") + _, err = s.Forward(refusalCtx.Request.Context(), refusalCtx, a, []byte(bpsJSON(bpsTestStructuredRequest(bpsTestStructuredFormat(true), stream)))) + require.NoError(t, err) + require.Contains(t, refusalRec.Body.String(), "Cannot provide that") + if stream { + require.Contains(t, refusalRec.Body.String(), "response.refusal.delta") + require.Contains(t, refusalRec.Body.String(), "response.refusal.done") + } + } + s, a := bpsFixture() + c, _ := bpsContext(1, "/responses/compact") + r, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, []byte(bpsJSON(bpsTestStructuredRequest(bpsTestStructuredFormat(true), false)))) + require.NoError(t, err) + require.Nil(t, r.Structured) + response, err := s.bpsTransformResponse(c.Request.Context(), a, r, bpsResponse(bpsText("A plain summary."))) + require.NoError(t, err) + require.Equal(t, "compaction", response["output"].([]any)[0].(map[string]any)["type"]) +} + +func TestOpenAIBPSStructuredInterruptedStreamNeverLeaksText(t *testing.T) { + for _, terminal := range []string{"", "response.incomplete", "response.failed"} { + s, a := bpsFixture() + c, rec := bpsContext(1, "/responses") + raw := bpsEvent("response.created", map[string]any{"response": map[string]any{"id": "r", "status": "in_progress"}}) + bpsEvent("response.output_text.delta", map[string]any{"delta": "unvalidated partial content"}) + if terminal != "" { + raw += bpsEvent(terminal, map[string]any{"response": map[string]any{"status": "failed", "usage": map[string]any{"input_tokens": 42}}}) + } + s.httpUpstream = &bpsHTTPStub{contentType: "text/event-stream", body: raw} + result, err := s.Forward(c.Request.Context(), c, a, []byte(bpsJSON(bpsTestStructuredRequest(bpsTestStructuredFormat(true), true)))) + require.Error(t, err) + require.NotContains(t, rec.Body.String(), "unvalidated partial content") + require.NotContains(t, rec.Body.String(), "event: response.completed") + require.Contains(t, rec.Body.String(), "response.failed") + if terminal != "" { + require.Equal(t, 42, result.Usage.InputTokens) + } + } +} + +func TestOpenAIBPSStructuredNullableMetadata(t *testing.T) { + format := bpsTestStructuredFormat(false) + format["strict"] = nil + format["description"] = nil + prepared, err := bpsPrepareStructuredOutput(map[string]any{"format": format}) + require.NoError(t, err) + require.NoError(t, prepared.validate(bpsResponse(bpsText(`{"ok":true}`)))) + require.Error(t, prepared.validate(bpsResponse(bpsText(`{"ok":"wrong"}`)))) +} diff --git a/backend/internal/service/openai_bps_test.go b/backend/internal/service/openai_bps_test.go new file mode 100644 index 000000000..82df8f126 --- /dev/null +++ b/backend/internal/service/openai_bps_test.go @@ -0,0 +1,623 @@ +package service + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type bpsMemoryStore struct { + GatewayCache + mu sync.Mutex + data map[string][]byte +} + +func (s *bpsMemoryStore) BPSGet(_ context.Context, k string) ([]byte, error) { + s.mu.Lock() + defer s.mu.Unlock() + return append([]byte(nil), s.data[k]...), nil +} +func (s *bpsMemoryStore) BPSPut(_ context.Context, k string, v []byte) error { + s.mu.Lock() + defer s.mu.Unlock() + s.data[k] = append([]byte(nil), v...) + return nil +} +func (s *bpsMemoryStore) BPSBind(_ context.Context, k string, v []byte) ([]byte, error) { + s.mu.Lock() + defer s.mu.Unlock() + if old, ok := s.data[k]; ok { + return old, nil + } + s.data[k] = append([]byte(nil), v...) + return v, nil +} +func bpsFixture() (*OpenAIGatewayService, *Account) { + return &OpenAIGatewayService{cache: &bpsMemoryStore{data: map[string][]byte{}}}, &Account{ID: 7, Platform: PlatformOpenAIBPS, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Credentials: map[string]any{"access_token": "test-secret", "chatgpt_account_id": "workspace-1", "model_mapping": map[string]any{"gpt-6-astra": "gpt-6-astra", "gpt-5.6-sol": "gpt-5.6-sol"}}} +} +func bpsContext(key int64, path string) (*gin.Context, *httptest.ResponseRecorder) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest("POST", path, nil) + c.Request.Header.Set("session_id", "conversation-1") + c.Set("api_key", &APIKey{ID: key}) + return c, rec +} +func bpsRequestBody(input any, stream bool) []byte { + return []byte(bpsJSON(map[string]any{"model": "gpt-6-astra", "input": input, "stream": stream})) +} +func bpsFunction(name string) map[string]any { + return map[string]any{"type": "function", "name": name, "parameters": map[string]any{"type": "object", "properties": map[string]any{"command": map[string]any{"type": "string"}}, "required": []any{"command"}, "additionalProperties": false}} +} +func bpsNative(id, name string, args any) map[string]any { + return map[string]any{"type": "function_call", "id": "fc_" + id, "call_id": id, "name": "run_officejs", "arguments": bpsJSON(map[string]any{"code": bpsJSON(map[string]any{"name": name, "arguments": args})}), "status": "completed"} +} +func bpsResponse(output ...any) map[string]any { + return map[string]any{"id": "resp_test", "object": "response", "status": "completed", "model": "gpt-6-astra", "output": output, "usage": map[string]any{"input_tokens": 100, "output_tokens": 12, "input_tokens_details": map[string]any{"cached_tokens": 35}}} +} +func bpsText(text string) map[string]any { + return map[string]any{"type": "message", "id": "msg_test", "role": "assistant", "status": "completed", "content": []any{map[string]any{"type": "output_text", "text": text, "annotations": []any{}}}} +} +func bpsEvent(typ string, fields map[string]any) string { + fields["type"] = typ + return "event: " + typ + "\ndata: " + bpsJSON(fields) + "\n\n" +} + +type bpsHTTPStub struct { + HTTPUpstream + body string + contentType string + status int + request *http.Request + requestBody []byte + requests int +} + +func (u *bpsHTTPStub) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + u.requests++ + u.request = req + u.requestBody, _ = io.ReadAll(req.Body) + status := u.status + if status == 0 { + status = 200 + } + return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": []string{u.contentType}}, Body: io.NopCloser(strings.NewReader(u.body))}, nil +} + +func TestOpenAIBPSCredentials(t *testing.T) { + exp := time.Now().Add(time.Hour).Unix() + jwt := "e30." + base64.RawURLEncoding.EncodeToString([]byte(bpsJSON(map[string]any{"exp": exp, "https://api.openai.com/auth": map[string]any{"chatgpt_account_id": "jwt-account"}}))) + ".sig" + creds, err := NormalizeOpenAIBPSCredentials(AccountTypeOAuth, map[string]any{"access_token": jwt}, nil) + require.NoError(t, err) + require.Equal(t, "jwt-account", creds["chatgpt_account_id"]) + require.Equal(t, time.Unix(exp, 0).UTC().Format(time.RFC3339), creds["expires_at"]) + kept, err := NormalizeOpenAIBPSCredentials(AccountTypeOAuth, map[string]any{"access_token": "", "chatgpt_account_id": "override"}, creds) + require.NoError(t, err) + require.Equal(t, jwt, kept["access_token"]) + require.Equal(t, "override", kept["chatgpt_account_id"]) + _, err = NormalizeOpenAIBPSCredentials(AccountTypeAPIKey, map[string]any{"access_token": jwt}, nil) + require.Error(t, err) + _, err = NormalizeOpenAIBPSCredentials(AccountTypeOAuth, map[string]any{"access_token": "opaque"}, nil) + require.Error(t, err) + _, account := bpsFixture() + account.Credentials["expires_at"] = time.Now().Add(-time.Second).Format(time.RFC3339) + require.False(t, account.IsSchedulable()) + _, err = buildOpenAIBPSRequest(context.Background(), account, []byte(`{}`)) + require.Error(t, err) +} +func TestOpenAIBPSProtocolAndHeaders(t *testing.T) { + s, a := bpsFixture() + c, _ := bpsContext(1, "/v1/responses") + c.Request.Header.Set("Authorization", "Bearer hostile") + c.Request.Header.Set("chatgpt-account-id", "hostile") + body := []byte(`{"model":"gpt-6-astra","input":"hi","reasoning":{"effort":"xhigh"}}`) + first, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, body) + require.NoError(t, err) + again, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, body) + require.NoError(t, err) + require.Equal(t, first.Body, again.Body) + require.Equal(t, "explicit", gjson.GetBytes(first.Body, "model_selection").String()) + require.False(t, gjson.GetBytes(first.Body, "store").Bool()) + require.Equal(t, "xhigh", gjson.GetBytes(first.Body, "reasoning_effort").String()) + req, err := buildOpenAIBPSRequest(c.Request.Context(), a, first.Body) + require.NoError(t, err) + require.Equal(t, OpenAIBPSResponsesURL, req.URL.String()) + require.Equal(t, "Bearer test-secret", req.Header.Get("Authorization")) + require.Equal(t, "workspace-1", req.Header.Get("chatgpt-account-id")) + require.Equal(t, "workspace-1", req.Header.Get("x-openai-account-id")) + require.Equal(t, "chatgpt", req.Header.Get("x-basispoints-auth-mode")) + for _, bad := range []string{`{"model":"gpt-6-astra","input":"hi","reasoning":{"effort":"max"}}`, `{"model":"gpt-6-astra","input":"hi","previous_response_id":"resp_1"}`, `{"model":"missing","input":"hi"}`, `{"model":"gpt-6-astra","input":[],"tools":[{"type":"web_search"}]}`} { + _, err = s.prepareOpenAIBPS(c.Request.Context(), c, a, []byte(bad)) + require.Error(t, err, bad) + } + require.True(t, a.SupportsOpenAIEndpointCapability(OpenAIEndpointCapabilityResponses)) + require.False(t, a.SupportsOpenAIEndpointCapability(OpenAIEndpointCapabilityChatCompletions)) +} +func TestOpenAIBPSToolsAndStableTurns(t *testing.T) { + s, a := bpsFixture() + c, _ := bpsContext(1, "/v1/responses") + source := map[string]any{"model": "gpt-6-astra", "input": []any{bpsMessage("user", "implement")}, "tools": []any{map[string]any{"type": "namespace", "name": "functions", "tools": []any{bpsFunction("exec")}}}} + first, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, []byte(bpsJSON(source))) + require.NoError(t, err) + require.False(t, gjson.GetBytes(first.Body, "tools").Exists()) + native := bpsNative("call_1", "functions.exec", map[string]any{"command": "pwd"}) + original := bpsJSON(native) + response, err := s.bpsTransformResponse(c.Request.Context(), a, first, bpsResponse(map[string]any{"id": "rs1", "type": "reasoning", "encrypted_content": "ciphertext"}, native)) + require.NoError(t, err) + output := response["output"].([]any) + client := output[1].(map[string]any) + require.Equal(t, "exec", client["name"]) + require.Equal(t, "functions", client["namespace"]) + source["input"] = []any{bpsMessage("user", "implement"), output[0], client, map[string]any{"type": "function_call_output", "call_id": "call_1", "output": "/workspace"}} + second, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, []byte(bpsJSON(source))) + require.NoError(t, err) + require.Equal(t, gjson.GetBytes(first.Body, "metadata.turn_id").String(), gjson.GetBytes(second.Body, "metadata.turn_id").String()) + require.Equal(t, "2", gjson.GetBytes(second.Body, "metadata.agent_iteration").String()) + require.Contains(t, string(second.Body), "ciphertext") + nativeRestored := gjson.GetBytes(second.Body, "input").Array()[3].Raw + require.JSONEq(t, original, nativeRestored) + secondOutput, err := s.bpsTransformResponse(c.Request.Context(), a, second, bpsResponse(bpsNative("call_2", "functions.exec", map[string]any{"command": "ls"}))) + require.NoError(t, err) + source["input"] = append(source["input"].([]any), secondOutput["output"].([]any)[0], map[string]any{"type": "function_call_output", "call_id": "call_2", "output": "files"}) + third, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, []byte(bpsJSON(source))) + require.NoError(t, err) + require.Equal(t, "3", gjson.GetBytes(third.Body, "metadata.agent_iteration").String()) + require.Equal(t, gjson.GetBytes(first.Body, "metadata.turn_id").String(), gjson.GetBytes(third.Body, "metadata.turn_id").String()) + for _, call := range []map[string]any{bpsNative("call_bad", "missing", map[string]any{}), bpsNative("call_bad", "functions.exec", map[string]any{"command": 123}), bpsNative("call_bad", "functions.exec", map[string]any{"command": "pwd", "extra": true})} { + _, err = bpsConvertTool(call, first) + require.Error(t, err) + } + // The envelope may be JSON encoded twice; trailing code must never be evaluated. + native["arguments"] = bpsJSON(map[string]any{"code": bpsJSON(bpsJSON(map[string]any{"name": "functions.exec", "arguments": map[string]any{"command": "pwd"}}))}) + _, err = bpsConvertTool(native, first) + require.NoError(t, err) + native["arguments"] = bpsJSON(map[string]any{"code": `{"name":"functions.exec","arguments":{"command":"pwd"}}; doSomething()`}) + _, err = bpsConvertTool(native, first) + require.Error(t, err) +} +func TestOpenAIBPSCustomAndPlan(t *testing.T) { + tools := map[string]bpsTool{} + var catalog []any + plan := map[string]any{"type": "function", "name": "update_plan", "parameters": map[string]any{"type": "object", "required": []any{"plan"}, "properties": map[string]any{"plan": map[string]any{"type": "array", "items": map[string]any{"type": "object", "required": []any{"step", "status"}, "properties": map[string]any{"step": map[string]any{"type": "string"}, "status": map[string]any{"enum": []any{"pending", "in_progress", "completed"}}}}}}}} + require.NoError(t, bpsCollectTools([]any{plan, map[string]any{"type": "custom", "name": "apply_patch"}}, "", tools, &catalog, 0)) + r := &bpsRequest{Tools: tools} + native := map[string]any{"type": "function_call", "id": "fc_p", "call_id": "p", "name": "update_plan", "arguments": `{"plan":[{"description":"fix it","status":"done"}]}`} + client, err := bpsConvertTool(native, r) + require.NoError(t, err) + require.JSONEq(t, `{"plan":[{"step":"fix it","status":"completed"}]}`, client["arguments"].(string)) + native["name"] = "run_officejs" + native["arguments"] = bpsJSON(map[string]any{"code": bpsJSON(map[string]any{"name": "apply_patch", "input": "*** Begin Patch\n*** End Patch"})}) + client, err = bpsConvertTool(native, r) + require.NoError(t, err) + require.Equal(t, "custom_tool_call", client["type"]) + require.Equal(t, "ctc_p", client["id"]) + // A client schema can never trigger file or network reads. + tools = map[string]bpsTool{} + err = bpsCollectTools([]any{map[string]any{"type": "function", "name": "remote", "parameters": map[string]any{"$ref": "file:///etc/passwd"}}}, "", tools, &catalog, 0) + require.Error(t, err) +} +func TestOpenAIBPSCompactionAndIsolation(t *testing.T) { + s, a := bpsFixture() + c, _ := bpsContext(1, "/v1/responses/compact") + body := bpsRequestBody("previous history", false) + require.NoError(t, s.PrepareOpenAIBPSRouting(c, body)) + require.NoError(t, s.bpsBind(c.Request.Context(), s.bpsScope(c, body), a)) + r, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, body) + require.NoError(t, err) + require.Empty(t, r.Tools) + compact, err := s.bpsTransformResponse(c.Request.Context(), a, r, bpsResponse(bpsText("Real summary containing pending work."))) + require.NoError(t, err) + ref := compact["output"].([]any)[0] + require.Contains(t, bpsJSON(ref), bpsCompactPrefix) + nextBody := []byte(bpsJSON(map[string]any{"model": "gpt-6-astra", "input": []any{ref, bpsMessage("user", "continue")}, "tools": []any{bpsFunction("exec")}})) + // A new service instance, same shared store, can continue the conversation. + next := &OpenAIGatewayService{cache: s.cache} + c2, _ := bpsContext(1, "/v1/responses") + require.NoError(t, next.PrepareOpenAIBPSRouting(c2, nextBody)) + require.True(t, bpsHasBinding(c2.Request.Context())) + resumed, err := next.prepareOpenAIBPS(c2.Request.Context(), c2, a, nextBody) + require.NoError(t, err) + require.False(t, resumed.Compact) + require.Contains(t, string(resumed.Body), "Real summary") + require.NotContains(t, string(resumed.Body), bpsCompactPrefix) + _, err = next.bpsTransformResponse(c2.Request.Context(), a, resumed, bpsResponse(bpsNative("after_compact", "exec", map[string]any{"command": "pwd"}))) + require.NoError(t, err) + other := *a + other.ID++ + require.False(t, bpsBoundAccountAllowed(c2.Request.Context(), &other)) + require.Error(t, next.bpsBind(c2.Request.Context(), r.Scope, &other)) + stranger, _ := bpsContext(2, "/v1/responses") + require.ErrorContains(t, next.PrepareOpenAIBPSRouting(stranger, nextBody), "expired") + store := s.cache.(*bpsMemoryStore) + store.data = map[string][]byte{} + require.ErrorContains(t, next.PrepareOpenAIBPSRouting(c2, nextBody), "expired") +} +func TestOpenAIBPSForward(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(map[bool]string{false: "JSON", true: "SSE"}[stream], func(t *testing.T) { + s, a := bpsFixture() + up := &bpsHTTPStub{body: bpsJSON(bpsResponse(bpsText("hello"))), contentType: "application/json"} + s.httpUpstream = up + c, rec := bpsContext(1, "/v1/responses") + body := bpsRequestBody("hi", stream) + require.NoError(t, s.PrepareOpenAIBPSRouting(c, body)) + result, err := s.Forward(c.Request.Context(), c, a, body) + require.NoError(t, err) + require.Equal(t, 200, rec.Code) + require.Equal(t, 100, result.Usage.InputTokens) + require.Equal(t, 35, result.Usage.CacheReadInputTokens) + require.Equal(t, 12, result.Usage.OutputTokens) + require.Contains(t, rec.Body.String(), "hello") + if stream { + require.Contains(t, rec.Body.String(), "event: response.output_text.delta") + require.Contains(t, rec.Body.String(), "event: response.completed") + } + }) + } + t.Run("tool buffering", func(t *testing.T) { + s, a := bpsFixture() + native := bpsNative("call1", "exec", map[string]any{"command": "pwd"}) + up := &bpsHTTPStub{contentType: "text/event-stream", body: bpsEvent("response.output_item.added", map[string]any{"item": native, "output_index": 0}) + bpsEvent("response.function_call_arguments.delta", map[string]any{"delta": "private-office-code"}) + bpsEvent("response.completed", map[string]any{"response": bpsResponse(native)})} + s.httpUpstream = up + c, rec := bpsContext(1, "/v1/responses") + body := []byte(bpsJSON(map[string]any{"model": "gpt-6-astra", "input": "hi", "stream": true, "tools": []any{bpsFunction("exec")}})) + _, err := s.Forward(c.Request.Context(), c, a, body) + require.NoError(t, err) + require.NotContains(t, rec.Body.String(), "run_officejs") + require.NotContains(t, rec.Body.String(), "private-office-code") + require.Contains(t, rec.Body.String(), `"name":"exec"`) + require.Contains(t, rec.Body.String(), "response.function_call_arguments.done") + }) + t.Run("interrupted", func(t *testing.T) { + s, a := bpsFixture() + s.httpUpstream = &bpsHTTPStub{contentType: "text/event-stream", body: bpsEvent("response.created", map[string]any{"response": map[string]any{"id": "resp1", "status": "in_progress"}}) + bpsEvent("response.output_text.delta", map[string]any{"delta": "partial"})} + c, rec := bpsContext(1, "/v1/responses") + result, err := s.Forward(c.Request.Context(), c, a, bpsRequestBody("hi", true)) + require.Error(t, err) + require.Equal(t, "response.failed", result.UpstreamTerminalEvent) + require.Contains(t, rec.Body.String(), "bps_stream_interrupted") + require.NotContains(t, rec.Body.String(), "event: response.completed") + }) + t.Run("unknown tool never completes", func(t *testing.T) { + s, a := bpsFixture() + s.httpUpstream = &bpsHTTPStub{contentType: "application/json", body: bpsJSON(bpsResponse(bpsNative("x", "unknown", map[string]any{})))} + c, rec := bpsContext(1, "/v1/responses") + _, err := s.Forward(c.Request.Context(), c, a, bpsRequestBody("hi", true)) + require.Error(t, err) + require.Equal(t, 502, rec.Code) + require.NotContains(t, rec.Body.String(), "event: response.completed") + }) + t.Run("native compaction signal", func(t *testing.T) { + s, a := bpsFixture() + s.httpUpstream = &bpsHTTPStub{contentType: "application/json", body: bpsJSON(bpsResponse(bpsText("summary")))} + c, rec := bpsContext(1, "/v1/responses") + _, err := s.Forward(c.Request.Context(), c, a, bpsRequestBody([]any{bpsMessage("user", "task"), map[string]any{"type": "compaction_trigger"}}, true)) + require.NoError(t, err) + require.Contains(t, rec.Body.String(), bpsCompactPrefix) + require.NotContains(t, rec.Body.String(), `"text":"summary"`) + up := s.httpUpstream.(*bpsHTTPStub) + require.NotContains(t, string(up.requestBody), "compaction_trigger") + }) +} +func TestOpenAIBPSHTTPFailoverBoundary(t *testing.T) { + s, a := bpsFixture() + c, _ := bpsContext(1, "/v1/responses") + body := bpsRequestBody("hi", false) + require.NoError(t, s.PrepareOpenAIBPSRouting(c, body)) + s.httpUpstream = &bpsHTTPStub{status: 503, body: `{"error":{"message":"busy"}}`} + _, err := s.Forward(c.Request.Context(), c, a, body) + var failover *UpstreamFailoverError + require.True(t, errors.As(err, &failover)) + require.NoError(t, s.bpsBind(c.Request.Context(), s.bpsScope(c, body), a)) + require.NoError(t, s.PrepareOpenAIBPSRouting(c, body)) + _, err = s.Forward(c.Request.Context(), c, a, body) + require.False(t, errors.As(err, &failover)) + var failure *bpsError + require.True(t, errors.As(err, &failure)) + require.Equal(t, 503, failure.Status) +} +func TestOpenAIBPSCatalogAndPlatform(t *testing.T) { + body, err := buildOpenAIBPSCodexModelsManifest(OpenAIBPSDefaultModels()) + require.NoError(t, err) + require.Equal(t, 2, len(gjson.GetBytes(body, "models").Array())) + for _, m := range gjson.GetBytes(body, "models").Array() { + require.False(t, m.Get("supports_parallel_tool_calls").Bool()) + require.Equal(t, "medium", m.Get("default_reasoning_level").String()) + require.Equal(t, 4, len(m.Get("supported_reasoning_levels").Array())) + require.NotContains(t, m.Get("supported_reasoning_levels").Raw, "max") + } + platform, ok := DetectModelPlatform("gpt-6-astra") + require.True(t, ok) + require.Equal(t, PlatformOpenAI, platform) + require.Equal(t, PlatformOpenAIBPS, NormalizeOpenAICompatiblePlatform(PlatformOpenAIBPS)) + require.True(t, isConcreteRequestPlatform(PlatformOpenAIBPS)) + require.NoError(t, validateProvider(MonitorProviderOpenAIBPS)) + require.NoError(t, validateAPIMode(MonitorProviderOpenAIBPS, MonitorAPIModeResponses)) + require.Error(t, validateCheckMode(MonitorProviderOpenAIBPS, MonitorCheckModeQuota)) +} + +// Ensure response.failed remains valid JSON even before a response ID is known. +func TestOpenAIBPSErrorJSON(t *testing.T) { + c, rec := bpsContext(1, "/responses") + WriteOpenAIBPSError(c, bpsExpired()) + require.Equal(t, 409, rec.Code) + var body map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) +} + +func TestOpenAIBPSCredentialReplacementPreservesDisabledState(t *testing.T) { + for _, status := range []string{StatusDisabled, "inactive", StatusActive, StatusError} { + t.Run(status, func(t *testing.T) { + _, account := bpsFixture() + account.Status = status + account.Schedulable = false + account.ErrorMessage = "BPS authentication failed; replace access_token" + repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{account.ID: account}} + admin := &adminServiceImpl{accountRepo: repo} + updated, err := admin.UpdateAccount(context.Background(), account.ID, &UpdateAccountInput{Credentials: map[string]any{"access_token": "replacement"}}) + require.NoError(t, err) + require.False(t, updated.Schedulable) + require.Equal(t, "replacement", updated.GetCredential("access_token")) + if status == StatusError { + require.Equal(t, StatusActive, updated.Status) + require.Empty(t, updated.ErrorMessage) + } else { + require.Equal(t, status, updated.Status) + } + }) + } +} +func TestOpenAIBPSCompositeRequiresExplicitRule(t *testing.T) { + _, account := bpsFixture() + gateway := &GatewayService{accountRepo: &compositeOwnershipAccountRepo{accounts: []Account{*account}}} + resolver := NewCompositeRouteResolver(nil) + resolver.SetModelOwnershipResolver(gateway.resolveCompositeModelOwnership) + decision, err := resolver.Resolve(context.Background(), 1, "gpt-6-astra", CompositeRouteEndpointResponses) + require.NoError(t, err) + require.Equal(t, PlatformOpenAI, decision.TargetPlatform) + platform, _, ok := resolveCodexCompositeModelTarget("gpt-6-astra", []Account{*account}, nil, true) + require.True(t, ok) + require.Equal(t, PlatformOpenAI, platform) + routes := []CompositeModelRoute{{PublicModel: "bps", UpstreamModel: "gpt-6-astra", TargetPlatform: PlatformOpenAIBPS, Endpoint: CompositeRouteEndpointResponses, MatchType: CompositeRouteMatchExact}} + body, err := buildCodexModelsManifestForAccounts(PlatformComposite, []string{"bps"}, []Account{*account}, &Group{Platform: PlatformComposite}, routes, true) + require.NoError(t, err) + require.False(t, gjson.GetBytes(body, "models.0.supports_parallel_tool_calls").Bool()) + require.Equal(t, "medium", gjson.GetBytes(body, "models.0.default_reasoning_level").String()) +} + +func TestOpenAIBPSCreateValidatesCredentials(t *testing.T) { + _, err := buildAccountForCreate(&CreateAccountInput{Platform: PlatformOpenAIBPS, Type: AccountTypeOAuth, Credentials: map[string]any{"access_token": "opaque"}}, nil) + require.Error(t, err) + account, err := buildAccountForCreate(&CreateAccountInput{Platform: PlatformOpenAIBPS, Type: AccountTypeOAuth, Credentials: map[string]any{"access_token": "opaque", "chatgpt_account_id": "workspace"}}, nil) + require.NoError(t, err) + require.Len(t, account.GetModelMapping(), 2) + _, err = buildAccountForCreate(&CreateAccountInput{Platform: PlatformOpenAIBPS, Type: AccountTypeAPIKey, Credentials: map[string]any{"access_token": "opaque", "chatgpt_account_id": "workspace"}}, nil) + require.Error(t, err) +} + +type bpsFailureRepo struct { + AccountRepository + authErrors []string + limitedModels []string + cooldown time.Time +} + +func (r *bpsFailureRepo) SetError(_ context.Context, _ int64, message string) error { + r.authErrors = append(r.authErrors, message) + return nil +} +func (r *bpsFailureRepo) SetModelRateLimit(_ context.Context, _ int64, model string, _ time.Time, _ ...string) error { + r.limitedModels = append(r.limitedModels, model) + return nil +} +func (r *bpsFailureRepo) SetRateLimited(_ context.Context, _ int64, until time.Time) error { + r.cooldown = until + return nil +} +func TestOpenAIBPSHTTPErrorClassification(t *testing.T) { + for _, tc := range []struct { + status int + body string + auth, model bool + }{{401, `{"error":{"message":"invalid test-secret"}}`, true, false}, {403, `{"error":{"code":"model_not_allowed"}}`, false, true}, {400, `{"error":{"message":"bad parameter"}}`, false, false}, {429, `{"error":{"message":"limited"}}`, false, false}} { + s, a := bpsFixture() + repo := &bpsFailureRepo{} + s.accountRepo = repo + c, rec := bpsContext(1, "/responses") + response := &http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(tc.body)), Header: http.Header{"Retry-After": []string{"120"}}} + err := s.bpsHTTPError(c.Request.Context(), c, a, response, "gpt-6-astra") + require.Error(t, err) + require.Equal(t, tc.auth, len(repo.authErrors) > 0) + require.Equal(t, tc.model, len(repo.limitedModels) > 0) + require.NotContains(t, err.Error(), "test-secret") + if tc.status == 429 { + require.InDelta(t, 120, time.Until(repo.cooldown).Seconds(), 2) + require.Equal(t, "120", rec.Header().Get("Retry-After")) + } + } +} +func TestOpenAIBPSTextContinuationRequiresSession(t *testing.T) { + s, _ := bpsFixture() + c, _ := bpsContext(1, "/responses") + body := bpsRequestBody([]any{bpsMessage("user", "hello"), bpsText("hello back"), bpsMessage("user", "continue")}, false) + require.ErrorContains(t, s.PrepareOpenAIBPSRouting(c, body), "expired") +} +func TestOpenAIBPSSchedulerBinding(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + for _, advanced := range []bool{false, true} { + _, a := bpsFixture() + a.Concurrency = 1 + a.GroupIDs = []int64{91} + other := *a + other.ID = 8 + other.Priority = -10 + svc := newOpenAICompactionSchedulerTestService([]Account{other, *a}, advanced) + ctx := context.WithValue(context.Background(), bpsRoutingContextKey{}, bpsRoutingContext{Scope: "test", Binding: &bpsSessionBinding{a.ID, a.GetCredential("chatgpt_account_id")}}) + group := int64(91) + selection, _, err := svc.SelectAccountWithSchedulerForCapability(ctx, &group, "", "", "gpt-6-astra", nil, OpenAIUpstreamTransportAny, OpenAIEndpointCapabilityResponses, true, false, false, PlatformOpenAIBPS) + require.NoError(t, err) + require.NotNil(t, selection) + require.Equal(t, a.ID, selection.Account.ID) + } +} + +func TestOpenAIBPSImplicitSessionSurvivesModelAndToolChanges(t *testing.T) { + s, a := bpsFixture() + c, _ := bpsContext(1, "/responses") + c.Request.Header.Del("session_id") + original := []byte(`{"model":"gpt-6-astra","input":"task"}`) + require.NoError(t, s.PrepareOpenAIBPSRouting(c, original)) + first, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, original) + require.NoError(t, err) + secondContext, _ := bpsContext(1, "/responses") + secondContext.Request.Header.Del("session_id") + changed := []byte(bpsJSON(map[string]any{"model": "gpt-5.6-sol", "instructions": "new rules", "tools": []any{bpsFunction("exec")}, "input": []any{bpsMessage("user", "task"), bpsMessage("user", "next")}})) + second, err := s.prepareOpenAIBPS(secondContext.Request.Context(), secondContext, a, changed) + require.NoError(t, err) + require.Equal(t, first.Scope, second.Scope) + require.Equal(t, gjson.GetBytes(first.Body, "metadata.task_id").String(), gjson.GetBytes(second.Body, "metadata.task_id").String()) + require.NotEqual(t, gjson.GetBytes(first.Body, "metadata.turn_id").String(), gjson.GetBytes(second.Body, "metadata.turn_id").String()) + // Explicit IDs and derived conversation roots occupy different namespaces. + secondContext.Request.Header.Set("session_id", "root:task") + require.NotEqual(t, first.Scope, s.bpsScope(secondContext, changed)) +} + +func TestOpenAIBPSCompactionWithoutSessionHeader(t *testing.T) { + s, a := bpsFixture() + c, _ := bpsContext(9, "/responses/compact") + c.Request.Header.Del("session_id") + body := bpsRequestBody("original task", false) + require.NoError(t, s.PrepareOpenAIBPSRouting(c, body)) + r, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, body) + require.NoError(t, err) + require.NoError(t, s.bpsBind(c.Request.Context(), r.Scope, a)) + response, err := s.bpsTransformResponse(c.Request.Context(), a, r, bpsResponse(bpsText("real summary"))) + require.NoError(t, err) + nextBody := bpsRequestBody(append(response["output"].([]any), bpsMessage("user", "continue")), false) + next, _ := bpsContext(9, "/responses") + next.Request.Header.Del("session_id") + fresh := &OpenAIGatewayService{cache: s.cache} + require.NoError(t, fresh.PrepareOpenAIBPSRouting(next, nextBody)) + continued, err := fresh.prepareOpenAIBPS(next.Request.Context(), next, a, nextBody) + require.NoError(t, err) + require.Equal(t, r.Scope, continued.Scope) + require.Contains(t, string(continued.Body), "real summary") + require.NotContains(t, string(continued.Body), bpsCompactPrefix) + stranger, _ := bpsContext(10, "/responses") + stranger.Request.Header.Del("session_id") + require.ErrorContains(t, fresh.PrepareOpenAIBPSRouting(stranger, nextBody), "expired") +} + +func TestOpenAIBPSRefusesUnknownNativeItemsAndEvents(t *testing.T) { + for _, stream := range []bool{false, true} { + s, a := bpsFixture() + s.httpUpstream = &bpsHTTPStub{contentType: "application/json", body: bpsJSON(bpsResponse(map[string]any{"type": "web_search_call", "id": "ws1", "status": "completed"}))} + c, rec := bpsContext(1, "/responses") + _, err := s.Forward(c.Request.Context(), c, a, bpsRequestBody("task", stream)) + require.Error(t, err) + require.NotContains(t, rec.Body.String(), "web_search_call") + require.NotContains(t, rec.Body.String(), "event: response.completed") + } + s, a := bpsFixture() + s.httpUpstream = &bpsHTTPStub{contentType: "text/event-stream", body: bpsEvent("response.web_search_call.in_progress", map[string]any{"item_id": "ws1"})} + c, rec := bpsContext(1, "/responses") + _, err := s.Forward(c.Request.Context(), c, a, bpsRequestBody("task", true)) + require.Error(t, err) + require.Contains(t, rec.Body.String(), "bps_unsupported_event") +} + +func TestOpenAIBPSFailedJSONPreservesUsage(t *testing.T) { + s, a := bpsFixture() + response := bpsResponse(bpsText("partial")) + response["status"] = "incomplete" + s.httpUpstream = &bpsHTTPStub{contentType: "application/json", body: bpsJSON(response)} + c, rec := bpsContext(1, "/responses") + result, err := s.Forward(c.Request.Context(), c, a, bpsRequestBody("task", false)) + require.Error(t, err) + require.Equal(t, 100, result.Usage.InputTokens) + require.Equal(t, 12, result.Usage.OutputTokens) + require.Equal(t, 502, rec.Code) + require.False(t, result.SucceededForScheduling()) +} + +func TestOpenAIBPSStrictReasoningAndAuthRecovery(t *testing.T) { + s, a := bpsFixture() + c, _ := bpsContext(1, "/responses") + for _, effort := range []any{false, 7, "max", ""} { + body := []byte(bpsJSON(map[string]any{"model": "gpt-6-astra", "input": "task", "reasoning": map[string]any{"effort": effort}})) + _, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, body) + require.Error(t, err) + } + a.Status = StatusError + a.ErrorMessage = "BPS authentication failed; replace access_token" + repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{a.ID: a}} + admin := &adminServiceImpl{accountRepo: repo} + updated, err := admin.UpdateAccount(context.Background(), a.ID, &UpdateAccountInput{Status: StatusError, Credentials: map[string]any{"access_token": "new-token"}}) + require.NoError(t, err) + require.Equal(t, StatusActive, updated.Status) + require.Empty(t, updated.ErrorMessage) +} + +func TestOpenAIBPSPlanResultRestoresNativeCall(t *testing.T) { + s, a := bpsFixture() + c, _ := bpsContext(1, "/responses") + body := []byte(`{"model":"gpt-6-astra","input":"make a plan","tools":[{"type":"function","name":"update_plan","parameters":{"type":"object"}}]}`) + require.NoError(t, s.PrepareOpenAIBPSRouting(c, body)) + r, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, body) + require.NoError(t, err) + native := map[string]any{"type": "function_call", "id": "native-plan-item", "call_id": "plan-call", "name": "update_plan", "arguments": `{"summary":"next","plan":[{"id":"s1","description":"code","status":"in_progress","result":""}]}`} + original := bpsJSON(native) + _, err = s.bpsTransformResponse(c.Request.Context(), a, r, bpsResponse(native)) + require.NoError(t, err) + // The client may send just the result alongside full user history; replay + // the complete native call from Redis, never synthesize a different identity. + nextBody := bpsRequestBody([]any{bpsMessage("user", "make a plan"), map[string]any{"type": "function_call_output", "call_id": "plan-call", "output": "Plan updated"}}, false) + next, err := s.prepareOpenAIBPS(c.Request.Context(), c, a, nextBody) + require.NoError(t, err) + items := gjson.GetBytes(next.Body, "input").Array() + require.JSONEq(t, original, items[2].Raw) + require.Equal(t, `{"status":"ok"}`, items[3].Get("output").String()) +} + +func TestOpenAIBPSNativeSSETextIsNotDuplicated(t *testing.T) { + s, a := bpsFixture() + item := bpsText("hello") + stream := bpsEvent("response.created", map[string]any{"response": map[string]any{"id": "resp_test", "status": "in_progress"}}) + bpsEvent("response.output_item.added", map[string]any{"output_index": 0, "item": map[string]any{"id": "msg_test", "type": "message", "content": []any{}}}) + bpsEvent("response.output_text.delta", map[string]any{"output_index": 0, "item_id": "msg_test", "content_index": 0, "delta": "hello"}) + bpsEvent("response.output_item.done", map[string]any{"output_index": 0, "item": item}) + bpsEvent("response.completed", map[string]any{"response": bpsResponse(item)}) + s.httpUpstream = &bpsHTTPStub{contentType: "text/event-stream", body: stream} + c, rec := bpsContext(1, "/responses") + _, err := s.Forward(c.Request.Context(), c, a, bpsRequestBody("task", true)) + require.NoError(t, err) + require.Equal(t, 1, strings.Count(rec.Body.String(), "event: response.output_text.delta")) + require.Equal(t, 1, strings.Count(rec.Body.String(), "event: response.output_item.added")) + require.Equal(t, 1, strings.Count(rec.Body.String(), "event: response.output_item.done")) +} + +func TestOpenAIBPSConnectivityUsesBPSForBothModels(t *testing.T) { + for _, model := range OpenAIBPSDefaultModels() { + for _, mode := range []string{"", "compact"} { + gateway, account := bpsFixture() + upstream := &bpsHTTPStub{contentType: "application/json", body: bpsJSON(bpsResponse(bpsText("OK")))} + gateway.httpUpstream = upstream + tester := &AccountTestService{openaiGatewayService: gateway, accountRepo: &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{account.ID: account}}} + c, rec := bpsContext(1, "/admin/test") + err := tester.TestAccountConnection(c, account.ID, model, "", mode) + require.NoError(t, err) + require.Equal(t, OpenAIBPSResponsesURL, upstream.request.URL.String()) + require.Equal(t, model, gjson.GetBytes(upstream.requestBody, "model").String()) + require.Contains(t, rec.Body.String(), `"success":true`) + } + } +} diff --git a/backend/internal/service/openai_bps_test_connection.go b/backend/internal/service/openai_bps_test_connection.go new file mode 100644 index 000000000..10cc667dd --- /dev/null +++ b/backend/internal/service/openai_bps_test_connection.go @@ -0,0 +1,62 @@ +package service + +import ( + "context" + "errors" + "net/http/httptest" + "strings" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +// Use the production adapter, Redis state and transport for connectivity tests. +// A fresh scope ensures tests never attach to a real client's conversation. +func (s *AccountTestService) testOpenAIBPSAccountConnection(c *gin.Context, account *Account, model, prompt, mode string) error { + if s.openaiGatewayService == nil { + return s.sendErrorAndEnd(c, "BPS gateway is unavailable") + } + if model == "" { + model = OpenAIBPSDefaultModels()[0] + } + if !account.IsModelSupported(model) { + return s.sendErrorAndEnd(c, "Model is not allowed by this account") + } + if strings.TrimSpace(prompt) == "" { + prompt = "Reply with OK." + } + s.sendEvent(c, TestEvent{Type: "test_start", Model: model}) + path := "/v1/responses" + if mode == "compact" { + path += "/compact" + } + body := []byte(bpsJSON(map[string]any{"model": model, "input": prompt, "stream": false, "prompt_cache_key": "bps-probe-" + uuid.NewString()})) + rec := httptest.NewRecorder() + probe, _ := gin.CreateTestContext(rec) + ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Minute) + defer cancel() + probe.Request = httptest.NewRequest("POST", path, strings.NewReader(string(body))).WithContext(ctx) + if err := s.openaiGatewayService.PrepareOpenAIBPSRouting(probe, body); err != nil { + return s.sendErrorAndEnd(c, err.Error()) + } + _, err := s.openaiGatewayService.forwardOpenAIBPS(probe.Request.Context(), probe, account, body) + if err != nil { + var typed *bpsError + if errors.As(err, &typed) { + return s.sendErrorAndEnd(c, typed.Message) + } + return s.sendErrorAndEnd(c, "BPS upstream request failed") + } + var response map[string]any + if bpsDecode(rec.Body.Bytes(), &response) != nil { + return s.sendErrorAndEnd(c, "Invalid BPS response") + } + text := bpsOutputText(response) + if mode == "compact" { + text = "BPS conversation summary saved successfully." + } + s.sendEvent(c, TestEvent{Type: "content", Text: text}) + s.sendEvent(c, TestEvent{Type: "test_complete", Success: true}) + return nil +} diff --git a/backend/internal/service/openai_bps_turn.go b/backend/internal/service/openai_bps_turn.go new file mode 100644 index 000000000..f9f43dca3 --- /dev/null +++ b/backend/internal/service/openai_bps_turn.go @@ -0,0 +1,51 @@ +package service + +import "github.com/google/uuid" + +// Turn identity is derived from immutable history. Retried requests never advance +// a mutable Redis counter; compaction retains the identity and iteration baseline. +func bpsTurnState(scope string, input []any, compactIndex int, compactRef string, compact bpsCompactState) (string, int) { + lastUser := -1 + for i, raw := range input { + if item, ok := raw.(map[string]any); ok && item["role"] == "user" { + lastUser = i + } + } + iteration := 1 + start := lastUser + 1 + turnID := "" + if compactIndex >= 0 && lastUser <= compactIndex { + turnID = compact.TurnID + if turnID == "" { + turnID = uuid.NewSHA1(uuid.NameSpaceURL, []byte(scope+":compact:"+compactRef)).String() + } + if compact.AgentIteration > 0 { + iteration = compact.AgentIteration + } + start = compactIndex + 1 + } else { + prefix := input + if lastUser >= 0 { + prefix = input[:lastUser+1] + } else if len(prefix) > 1 { + prefix = prefix[:1] + } + turnID = uuid.NewSHA1(uuid.NameSpaceURL, []byte(scope+":"+bpsJSON(prefix))).String() + } + for _, raw := range input[start:] { + if item, ok := raw.(map[string]any); ok && (item["type"] == "function_call_output" || item["type"] == "custom_tool_call_output") { + iteration++ + } + } + return turnID, iteration +} + +// Matches ghcp_proxy's responses_replay_ids.function_item_id. This ID belongs +// to the replayed result, not to the original upstream call stored in Redis. +func bpsFunctionOutputID(callID string) string { + candidate := "fc_" + callID + if len(candidate) <= 64 { + return candidate + } + return "fc_" + bpsDigest(callID)[:61] +} diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index 9e3d89d4a..59bc66edb 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -853,6 +853,9 @@ func (s *GatewayService) BuildCodexModelsManifestForGroup( platformOverride string, modelIDs []string, ) ([]byte, error) { + if platformOverride == PlatformOpenAIBPS || (platformOverride == "" && group != nil && group.Platform == PlatformOpenAIBPS) { + return buildOpenAIBPSCodexModelsManifest(modelIDs) + } if s == nil || s.accountRepo == nil || group == nil { return BuildCodexModelsManifest(modelIDs) } @@ -894,6 +897,9 @@ func buildCodexModelsManifestForAccounts( compositeRoutes []CompositeModelRoute, compositeRoutesAvailable bool, ) ([]byte, error) { + if effectivePlatform == PlatformOpenAIBPS { + return buildOpenAIBPSCodexModelsManifest(modelIDs) + } imageInputModels := make(map[string]bool, len(modelIDs)) searchToolModels := make(map[string]bool, len(modelIDs)) metadataModels := codexCatalogMetadataModels( @@ -935,7 +941,23 @@ func buildCodexModelsManifestForAccounts( modelMetadata[modelID] = metadata } } - return buildCodexModelsManifest(modelIDs, imageInputModels, searchToolModels, metadataModels, modelMetadata) + body, err := buildCodexModelsManifest(modelIDs, imageInputModels, searchToolModels, metadataModels, modelMetadata) + if err != nil || effectivePlatform != PlatformComposite { + return body, err + } + var catalog struct { + Models []map[string]any `json:"models"` + } + if err = json.Unmarshal(body, &catalog); err != nil { + return nil, err + } + for _, model := range catalog.Models { + platform, _, ok := resolveCodexCompositeModelTarget(stringValue(model["slug"]), accounts, compositeRoutes, compositeRoutesAvailable) + if ok && platform == PlatformOpenAIBPS { + applyOpenAIBPSModelCapabilities(model) + } + } + return json.Marshal(catalog) } func buildCodexModelsManifest( @@ -1210,7 +1232,7 @@ func resolveCodexCompositeModelTarget( claimedPlatforms := make(map[string]struct{}) for _, account := range accounts { platform := strings.TrimSpace(account.Platform) - if !isConcreteRequestPlatform(platform) || !codexExplicitModelMappingClaims(account, modelID) { + if platform == PlatformOpenAIBPS || !isConcreteRequestPlatform(platform) || !codexExplicitModelMappingClaims(account, modelID) { continue } claimedPlatforms[platform] = struct{}{} diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index a86a3b18a..0e3c4dcc8 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -19,6 +19,9 @@ import ( // Forward forwards request to OpenAI API func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (*OpenAIForwardResult, error) { + if account.IsOpenAIBPS() { + return s.forwardOpenAIBPS(ctx, c, account, body) + } beginUpstreamResponseModelObservation(c) body = normalizeOpenAIRequestLocale(ctx, account, body, "http") ClearActualOpenAIUpstreamEndpoint(c) diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index fea172cb1..792b9b90d 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -292,7 +292,7 @@ func (s *OpenAIGatewayService) SelectAccountForTokenCount( // handler 调度入口仍需导出,保持导出名。) func NormalizeOpenAICompatiblePlatform(platform string) string { switch platform { - case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS: return platform default: return PlatformOpenAI @@ -336,6 +336,9 @@ func (e openAINoAvailableSelectionError) Unwrap() error { // openAICompactSupportTier classifies an OpenAI-compatible account by compact capability. // 0 = explicitly unsupported, 1 = unknown / not yet probed, 2 = explicitly supported. func openAICompactSupportTier(account *Account) int { + if account.IsOpenAIBPS() { + return 2 + } if account == nil { return 0 } @@ -392,6 +395,9 @@ func openAICompatibleAccountEligibilityFailureReasonBeforeProfit(ctx context.Con if account == nil { return "account_nil" } + if !bpsBoundAccountAllowed(ctx, account) { + return "bps_account_binding" + } if account.Platform != platform || !account.IsOpenAICompatible() { return "platform_mismatch" } diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index 8b1444b68..3810eb16c 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -305,7 +305,7 @@ type OpenAIForwardResult struct { // that may clear model-scoped transient state. The zero value remains a success // for existing non-WS callers. func (r *OpenAIForwardResult) SucceededForScheduling() bool { - if r == nil || !r.OpenAIWSMode || r.UpstreamTerminalEvent == "" { + if r == nil || (!r.OpenAIWSMode && r.UpstreamEndpoint != "/basispoints/api/responses") || r.UpstreamTerminalEvent == "" { return true } switch r.UpstreamTerminalEvent { diff --git a/backend/internal/service/scheduler_snapshot_service.go b/backend/internal/service/scheduler_snapshot_service.go index 784af2075..af45661dc 100644 --- a/backend/internal/service/scheduler_snapshot_service.go +++ b/backend/internal/service/scheduler_snapshot_service.go @@ -609,7 +609,7 @@ func (s *SchedulerSnapshotService) handleBulkAccountEvent(ctx context.Context, p } accountGroupIDs := s.normalizeGroupIDs(account.GroupIDs) switch account.Platform { - case PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + case PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS: addPlatformGroups(account.Platform, accountGroupIDs) case PlatformAntigravity: // 批量更新可能刚关闭 mixed_scheduling,仍需清理两个兼容平台的旧快照。 @@ -824,8 +824,8 @@ func (s *SchedulerSnapshotService) rebuildByAccount(ctx context.Context, account return s.rebuildBuckets(ctx, buckets, reason) } -func schedulerSnapshotPlatforms() [10]string { - return [10]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} +func schedulerSnapshotPlatforms() [11]string { + return [11]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS} } // 生命周期辅助函数有意排除 group0;full rebuild 构造 group0 canonical 集时必须显式调用 canonical helper。 diff --git a/backend/migrations/245_openai_bps_platform.sql b/backend/migrations/245_openai_bps_platform.sql new file mode 100644 index 000000000..f8fc0ed08 --- /dev/null +++ b/backend/migrations/245_openai_bps_platform.sql @@ -0,0 +1,17 @@ +-- Register OpenAI BPS without changing existing accounts or groups. + +ALTER TABLE user_platform_quotas DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check; +ALTER TABLE user_platform_quotas ADD CONSTRAINT user_platform_quotas_platform_check + CHECK (platform IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go')); + +ALTER TABLE composite_model_routes DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check; +ALTER TABLE composite_model_routes ADD CONSTRAINT composite_model_routes_target_platform_check + CHECK (target_platform IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go')); + +ALTER TABLE channel_monitors DROP CONSTRAINT IF EXISTS channel_monitors_provider_check; +ALTER TABLE channel_monitors ADD CONSTRAINT channel_monitors_provider_check + CHECK (provider IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go')); + +ALTER TABLE channel_monitor_request_templates DROP CONSTRAINT IF EXISTS channel_monitor_request_templates_provider_check; +ALTER TABLE channel_monitor_request_templates ADD CONSTRAINT channel_monitor_request_templates_provider_check + CHECK (provider IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go')); diff --git a/backend/migrations/openai_bps_platform_migration_test.go b/backend/migrations/openai_bps_platform_migration_test.go new file mode 100644 index 000000000..a98a7258a --- /dev/null +++ b/backend/migrations/openai_bps_platform_migration_test.go @@ -0,0 +1,22 @@ +package migrations + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOpenAIBPSPlatformMigration(t *testing.T) { + data, err := FS.ReadFile("245_openai_bps_platform.sql") + require.NoError(t, err) + sql := string(data) + for _, table := range []string{"user_platform_quotas", "composite_model_routes", "channel_monitors", "channel_monitor_request_templates"} { + require.Contains(t, sql, "ALTER TABLE "+table+" DROP CONSTRAINT IF EXISTS") + require.Contains(t, sql, "ALTER TABLE "+table+" ADD CONSTRAINT") + } + for _, p := range []string{"anthropic", "openai", "openai_bps", "gemini", "antigravity", "grok", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"} { + require.Equal(t, 4, strings.Count(sql, "'"+p+"'"), p) + } + require.NotContains(t, strings.ToUpper(sql), "UPDATE ACCOUNTS") +} diff --git a/changelog/1.1.5/CHANGELOG.md b/changelog/1.1.5/CHANGELOG.md new file mode 100644 index 000000000..6ffc93410 --- /dev/null +++ b/changelog/1.1.5/CHANGELOG.md @@ -0,0 +1,23 @@ +# v1.1.5 + +## 更新内容 + +- 新增独立的 OpenAI BPS 平台,通过 ChatGPT Excel/BPS 上游提供 HTTP Responses 服务。支持手动配置 Access Token、ChatGPT Account ID、代理、账号分组、模型映射与连接测试,默认候选模型为 `gpt-6-astra`、`gpt-5.6-sol`。 +- BPS 账号自动提取 JWT 中的账号标识和到期时间,支持手动覆盖账号 ID;凭证脱敏展示,编辑留空保留原 Token,替换凭证不会解除管理员主动停用状态。 +- 接入现有调度、用量日志、计费、用户平台配额和渠道监测。BPS 分组只使用 BPS 账号;Composite 分组通过显式路由选择 BPS,普通 `gpt-*` 自动识别规则保持原有行为。 +- 增加 Codex 工具协议转换:将 function、custom、namespace 和 additional_tools 声明转换为文本目录,经原生 `run_officejs` 承载工具请求,再恢复客户端工具调用。支持信封别名、嵌套 JSON、custom 原始文本及 update_plan 参数和回执适配,工具仍由客户端执行。 +- 通过 Redis 保存完整原始工具调用、账号绑定和压缩摘要,支持跨实例续接与 7 天闲置过期。规范化工具结果 ID 和加密 reasoning 回放,已建立上下文的会话不会自动换号重放。 +- 支持 `/responses/compact` 和 Responses 压缩请求,使用真实文本摘要及不透明引用恢复上下文。压缩前后保持用户轮次,工具结果仅递增迭代次数,兼容旧摘要记录和连续压缩。 +- 支持 `text.format` 的 JSON Object / JSON Schema 输出,通过提示词约束与本地最终结果校验保证输出格式,保留大整数精度。结构化文本在校验通过后才发送;工具调用、明确拒答和压缩分别处理,校验失败保留实际用量并返回明确错误。 +- 完善 JSON/SSE 转换:普通文本实时输出,工具在完整解析、验证和保存后交付;异常断流或终态丢失工具 item 时返回失败,不伪造成功完成事件。 +- 修复 Composite 模型目录遗漏 BPS 别名、无有效候选时错误回退全部平台模型,以及 BPS 标准模型列表格式不兼容的问题。 +- 正确识别 BPS 模型权限错误,按实际映射模型冷却 30 分钟,不停用账号的其他模型;Token 过期或认证失败停止该账号调度,429 沿用上游退避信息。 + +## 升级说明 + +- 运行版本号为 `1.1.5`,本次候选镜像标签为 `macosdo/sub4api:1.1.5-rc`。 +- 启动时需完成 `245_openai_bps_platform.sql`,扩展平台约束;不新增账号凭证表。Redis 为 BPS 必需依赖。 +- BPS Token 需要手动替换,不提供自动续期。首版支持 HTTP Responses、文本输入与串行工具,不提供 WebSocket、Chat Completions、图像或音频接口。 +- 结构化输出采用提示词约束加本地校验,不是上游原生约束解码。无效 schema 返回 400,不符合输出格式的最终响应返回 502 或 SSE 失败事件。 +- BPS 使用需要完整历史;状态过期或绑定账号不可用时需恢复该账号或新建会话。正式使用前,请在测试分组验证实际账号权限,以及 Codex 工具、压缩和结构化输出链路。 +- 配置与协议来源说明见 `docs/openai-bps.md` 和 `docs/openai-bps-sources.md`。 diff --git a/docs/openai-bps-sources.md b/docs/openai-bps-sources.md new file mode 100644 index 000000000..1b122099b --- /dev/null +++ b/docs/openai-bps-sources.md @@ -0,0 +1,9 @@ +# BPS 协议实现来源 + +本项目的 BPS 适配保留 Sub4API 自身的独立平台、账号调度、Redis 状态、计费和 HTTP 入口。下列固定版本用于协议移植和兼容性对照;不导入其他项目的部署配置、插件 ABI 或凭证采集逻辑。 + +- `ranxi2001/sub2api`,提交 `055a1cd1470b3b866d04aad8d1514bd34cac73ab`,`backend/internal/service/basispoints/`:移植工具信封解码、custom 原始文本标记,并适配结构化输出、工具目录和计划参数处理。仓库使用 LGPL-3.0;本项目同样使用 LGPL-3.0。新增源文件注明移植来源。 +- `Nonary/ghcp_proxy`,提交 `ad23ce2db3b5212c0355762d981c3877322fb160`,`excel_upstream.py` 和 `responses_replay_ids.py`:工具隧道、完整调用回放、加密 reasoning、计划成功回执和结果 ID 规范化;Unlicense。 +- `1812095643/sub2api-excel2api-plugin`,提交 `ad2039077e5a625c846ed405d3473f7bc74b601a`:对照 `tool/args` 信封、轮次保持和工具结果回放;未导入插件二进制或内置静态工具目录。 + +Go 参考包的 `NOTICE.md` 另注明:原始 BPS 协议源于 hloolx/codex2api(其 README 声明 MIT),相关提交为 `9d02d3f5e5d69632ebb9590082a833c0a0916356`、`c125e560eefb5fd15c995943eb1e111795b0635f`、`20ff3e860d9a149e2df731e37ba1d9b56ae053fc`、`d39f7e3697aab342e303bf4be0142e39b6a58515`、`4dea83ec53b7668419edd2a9a9dd40fb55fdaacd`;并对照 JaxsonWang/cpa-plugin-oai-basispoints 的 `05b2d97efa1bd117da6bd4d362d6e88f8e483680`。这里保留上述来源链。 diff --git a/docs/openai-bps.md b/docs/openai-bps.md new file mode 100644 index 000000000..862fd713f --- /dev/null +++ b/docs/openai-bps.md @@ -0,0 +1,78 @@ +# OpenAI BPS 接入 + +平台值为 `openai_bps`,账号类型为 `oauth`,界面显示 **Access Token**。启动新版本时需完成 `245_openai_bps_platform.sql` 迁移。Redis 是必需依赖;会话状态不使用进程内降级。 + +## 配置 + +1. 创建 **OpenAI BPS** 分组,配置模型价格、倍率和白名单。上游成本由管理员设置,不从 Excel 点数或 Codex 配额推断。 +2. 创建 **OpenAI BPS** 账号,填写 `access_token`。`chatgpt_account_id` 留空时从 JWT 提取,填写时覆盖默认账号;同时提取 JWT 的到期时间。解析 JWT 只读取信息,不验证真实性。 +3. 绑定 BPS 分组,按需要选择代理、调整模型映射。默认候选模型为 `gpt-6-astra`、`gpt-5.6-sol`;模型映射支持管理员设置别名和白名单。删除全部规则表示不限模型。 +4. 在创建或编辑窗口选择“保存并测试连接”,用保存后的账号打开测试窗口。分别选择两个模型测试文本和压缩。账号列表也保留连接测试入口。 +5. Token 到期后手动替换。编辑时留空会保留原 token;替换 token 不会解除管理员主动停用或关闭调度的状态。列表显示到期时间和账号失败原因。 +6. 使用该分组的 **Sub4API API Key** 配置 Codex,`wire_api = "responses"`,`supports_websockets = false`。API Key 使用说明提供 Codex 配置和模型目录。 +7. Composite 分组必须为 BPS 添加显式路由。模型目录仅发布启用的 Responses/通用路由且有合格 BPS 账号承接的模型;精确路由直接发布别名,前缀路由筛选可枚举的账号模型。没有有效候选时返回空列表。普通 `gpt-*` 自动识别规则仍选择 OpenAI。 + +上游地址固定为 `https://bps.openai.com/basispoints/api/responses`,不接受客户端或账号配置替换。服务端设置 Bearer token、两个账号 ID 头和 `x-basispoints-auth-mode: chatgpt`,不转发客户端提供的认证头。 + +## 支持范围 + +- HTTP Responses 的 JSON 和 SSE、function/custom/namespace 工具、`update_plan`、多轮工具结果及加密 reasoning。 +- 推理强度 `low` / `medium` / `high` / `xhigh`,默认 `medium`;`max` 等不支持的值明确报错。 +- `/responses/compact` 和带 `compaction_trigger` 的 Responses 压缩请求。 +- `text.format.type=json_object/json_schema` 的 JSON 与 SSE 输出,采用提示词约束和本地最终结果校验。 +- 不提供 WebSocket、Chat Completions、Claude Messages、图像/音频、自动续期或 Excel 本地凭证读取。不能用 `previous_response_id` 或 `item_reference` 代替完整历史。 +- 模型目录声明串行工具、文本输入及 HTTP。目录的 200,000 token 上下文和 160,000 token 压缩阈值是保守的本地策略,不是上游配额或能力保证。 + +## 会话、工具与压缩 + +建议客户端保持 `session_id` 或 `prompt_cache_key` 并携带完整历史。没有显式 ID 时,以首条用户消息生成稳定身份,更换模型或工具不改变会话。完全相同的首条消息无法区分两个独立会话,因此需要并行同题对话时应指定不同 ID。 + +会话按 API Key 隔离,建立上下文后绑定账号和 ChatGPT workspace。绑定账号不可用时返回 `bps_account_unavailable`,不会把加密历史重放给另一个账号。Redis 中的绑定、原始工具 item 和压缩记录采用 7 天闲置过期。缺失上下文返回 `bps_context_expired`,需要新建会话。 + +工具声明(含 `additional_tools`)整理成稳定的文本目录;重复且相同的声明合并,冲突声明报错。function 默认使用 `name/arguments` JSON 信封,也兼容 `tool/args`;custom 默认使用 `summary=codex2api.custom/完整工具名` 和 `code` 原文,也接受旧 JSON 信封。工具信封上限 1 MiB。`run_officejs` 仅作为协议载体,代理不执行 OfficeJS 或客户端工具。只有本次声明的工具可输出给客户端,function 参数通过 JSON Schema 校验,外部 schema 引用被禁用。完整的原始 item、`id`、`call_id` 和 arguments 保存到 Redis,在客户端回传结果时恢复。结果转换为带稳定 `fc_` ID 的 `function_call_output`;加密 reasoning 重建为类型、空 summary 和不变的密文。原生 `update_plan` 对齐步骤别名、状态和成功回执,失败结果保留。一次最多交付一个工具调用;文本实时输出,工具事件在校验和保存完成后输出。 + +压缩调用真实摘要请求并关闭客户端工具。摘要保存到 Redis,客户端只收到版本化 `bpscmp_v1_` 引用;后续请求恢复摘要,引用本身不发给 BPS。无显式会话 ID 时,引用也可恢复原会话。压缩失败返回错误,不替换客户端原历史。异常断流或终态丢失已完成工具 item 时不会伪造成功。 + +压缩记录同时保存 `turn_id` 和迭代基数。恢复后没有新用户消息就保持同一轮次,仅按新增工具结果增加 `agent_iteration`;重试相同请求不改变上游请求体。旧摘要记录仍可读取,以不透明引用作为稳定轮次锚点;新记录在连续压缩与跨实例恢复后仍保留原始轮次。 + +## 结构化输出 + +通过 `text.format` 传入 `json_object` 或带 `name/schema/strict` 的 `json_schema`。代理将要求写入 developer 消息,BPS 请求不携带原生 `text.format`,客户端响应保留请求的格式声明。这是提示词约束加本地校验,不是上游原生约束解码。 + +`json_object` 必须返回一个 JSON 对象;`json_schema` 的最终 JSON 必须满足 schema,即使 `strict=false` 也会校验。保留大整数精度。schema 上限 1 MiB,仅允许文档内引用;无效 schema 在请求上游前返回 400。最终文本上限 16 MiB,同时受既有响应大小限制约束。 + +结构化消息文本等终态验证通过后才发送,JSON/SSE 使用同一套规则,普通文本仍实时输出。工具调用阶段与明确拒答按独立协议项处理;压缩始终生成真实文本摘要。校验失败返回 `bps_invalid_structured_output`:尚未开始响应时为 HTTP 502,已开始 SSE 时为 `response.failed`,不自动改写答案或重试生成。已取得的 usage 仍记录。 + +## 计费、错误与监测 + +按实际上游 `usage` 记录输入、缓存及输出 token,沿用现有分组/渠道价格、倍率、日志和用户平台配额。可取得用量的失败响应同样记录用量。 + +认证失败停止账号调度;过期 token 在调度前被排除。`basispoints_model_access_changed` 和 `model_not_allowed` 统一归为 `bps_model_not_allowed`,按映射后的上游模型冷却 30 分钟,原始错误码保留在诊断中;账号其他模型继续可用。普通 403 不直接判定整个账号失效。参数错误不重试,429 根据 `Retry-After` 冷却。只有尚未绑定上下文且尚未输出的新会话,才能在网络错误、429 或 5xx 时有限换号。 + +渠道监测选择 OpenAI BPS,填写 **Sub4API 地址和 BPS 分组 API Key**,使用 Responses 探活。监测模板支持 BPS;不提供上游配额探测。 + +## 验证与上线 + +仓库测试覆盖压缩轮次保持、连续压缩、旧摘要兼容、显式 Composite 目录、标准模型格式、结构化 JSON/SSE、错误 schema、文档内/外引用、大整数、未验证文本隔离、工具续接与拒答,以及凭证提取/覆盖/过期/脱敏、账号状态保留、平台隔离、两种调度路径、快照身份、请求头、JSON/SSE、未知工具、参数 schema、双层 JSON、连续工具往返、摘要恢复、API Key 隔离、Redis 闲置过期、双模型模拟连接及端点边界。Redis 使用 miniredis,并通过独立客户端验证跨实例读写及原子账号绑定。 + +本次没有真实 BPS token。两模型的实际权限、真实 Codex 工具与压缩闭环尚未验收;迁移目前通过 SQL 回归断言,未在真实 PostgreSQL 执行。正式启用前,在测试环境应用迁移,用实际账号分别验证文本、SSE、function/custom/namespace、`update_plan`,以及“压缩 → 新一轮对话 → 工具调用”。 + +主要验证命令: + +```sh +# backend/ +go test -tags=unit ./internal/service ./internal/handler/... ./internal/server/routes ./internal/repository ./migrations \ + -run 'Test(OpenAI|Composite|ResolveComposite|QuotaPlatform|BuildCodexModels|FilterCodex|Channel|SchedulerCanonical|SchedulerMetadata|FilterSchedulerCredentials|AccountFromService|UpdateAccountPreserves|CreateAccount)' -count=1 +go build -tags embed ./cmd/server + +# frontend/ +pnpm run build +pnpm exec vitest run src/components/account/__tests__/OpenAIBPSAccountFields.spec.ts \ + src/components/account/__tests__/CreateAccountModal.spec.ts \ + src/components/account/__tests__/EditAccountModal.spec.ts \ + src/components/keys/__tests__/UseKeyModal.spec.ts +``` + +协议参考:[Nonary/ghcp_proxy 的固定版本实现](https://github.com/Nonary/ghcp_proxy/blob/ad23ce2db3b5212c0355762d981c3877322fb160/excel_upstream.py)(Unlicense)。该 BPS 协议不是公开承诺稳定的 OpenAI API 契约;真实上游兼容性以测试账号验收为准。 + +固定版本的协议移植和对照来源见 [openai-bps-sources.md](openai-bps-sources.md)。 diff --git a/frontend/src/api/admin/channelMonitor.ts b/frontend/src/api/admin/channelMonitor.ts index 7ddd5697e..267b9bd23 100644 --- a/frontend/src/api/admin/channelMonitor.ts +++ b/frontend/src/api/admin/channelMonitor.ts @@ -7,6 +7,7 @@ import { apiClient } from '../client' export type Provider = | 'openai' + | 'openai_bps' | 'anthropic' | 'gemini' | 'grok' diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index bf7aacc65..a19d3b346 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -17,7 +17,7 @@ export interface DefaultSubscriptionSetting { } // ── 平台限额类型 ────────────────────────────────────────────────── -export type PlatformType = "anthropic" | "openai" | "gemini" | "antigravity" | "grok" +export type PlatformType = "anthropic" | "openai" | "openai_bps" | "gemini" | "antigravity" | "grok" export type QuotaWindowType = "daily" | "weekly" | "monthly" /** 单平台三档限额;null = 不限制,undefined = 未填(等价 null) */ @@ -30,7 +30,7 @@ export interface PlatformQuotaLimits { /** 全平台默认限额 map(key = PlatformType) */ export type DefaultPlatformQuotasMap = Partial> -const PLATFORMS: PlatformType[] = ["anthropic", "openai", "gemini", "antigravity", "grok"] +const PLATFORMS: PlatformType[] = ["anthropic", "openai", "openai_bps", "gemini", "antigravity", "grok"] export type SchedulingThresholdPlatformType = | "openai" diff --git a/frontend/src/api/admin/users.ts b/frontend/src/api/admin/users.ts index fae7ec6f8..d3b597d0a 100644 --- a/frontend/src/api/admin/users.ts +++ b/frontend/src/api/admin/users.ts @@ -332,7 +332,7 @@ export async function bindUserAuthIdentity( */ // Keep aligned with backend/internal/service/domain_constants.go AllowedQuotaPlatforms. export const PLATFORM_QUOTA_PLATFORMS = [ - 'anthropic', 'openai', 'gemini', 'antigravity', 'grok', + 'anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', ] as const export type PlatformQuotaPlatform = typeof PLATFORM_QUOTA_PLATFORMS[number] diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index f972a8a3b..f2c6bf047 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -1,8 +1,15 @@