diff --git a/.github/workflows/scripts/load-test.sh b/.github/workflows/scripts/load-test.sh index 541bb82b05c..4d4a8caff62 100755 --- a/.github/workflows/scripts/load-test.sh +++ b/.github/workflows/scripts/load-test.sh @@ -169,7 +169,13 @@ build_bifrost_http() { fi log_info "Building bifrost-http..." - cd "${TRANSPORTS_DIR}" + cd "${BIFROST_HTTP_DIR}" + + # Ensure ui directory exists for //go:embed all:ui (load test does not need the real UI assets) + mkdir -p "${BIFROST_HTTP_DIR}/ui" + if [ ! -f "${BIFROST_HTTP_DIR}/ui/.gitkeep" ]; then + echo "placeholder" > "${BIFROST_HTTP_DIR}/ui/.gitkeep" + fi if go build -o ${REPO_ROOT}/tmp/bifrost-http .; then log_success "bifrost-http built successfully" @@ -190,8 +196,9 @@ setup_mocker() { cd "${WORK_DIR}" else log_info "Cloning bifrost-benchmarking repository..." - cd "${WORK_DIR}" + cd "${REPO_ROOT}/.." git clone --depth 1 https://github.com/maximhq/bifrost-benchmarking.git + cd "${WORK_DIR}" fi log_success "Mocker setup complete" @@ -242,7 +249,8 @@ create_config() { { "name": "mocker-key", "value": "Bearer mocker-key", - "weight": 1 + "weight": 1, + "models": ["*"] } ], "network_config": { @@ -252,14 +260,6 @@ create_config() { "concurrency_and_buffer_size": { "concurrency": 20000, "buffer_size": 40000 - }, - "custom_provider_config": { - "base_provider_type": "openai", - "allowed_requests": { - "list_models": false, - "chat_completion": true, - "chat_completion_stream": true - } } } } @@ -848,3 +848,4 @@ main() { } main "$@" + diff --git a/core/bifrost.go b/core/bifrost.go index 2c53f83d7fa..cd6b28680ef 100644 --- a/core/bifrost.go +++ b/core/bifrost.go @@ -34,6 +34,7 @@ import ( "github.com/maximhq/bifrost/core/providers/mistral" "github.com/maximhq/bifrost/core/providers/nebius" "github.com/maximhq/bifrost/core/providers/ollama" + "github.com/maximhq/bifrost/core/providers/opencode" "github.com/maximhq/bifrost/core/providers/openai" "github.com/maximhq/bifrost/core/providers/openrouter" "github.com/maximhq/bifrost/core/providers/parasail" @@ -3965,6 +3966,10 @@ func (bifrost *Bifrost) createBaseProvider(providerKey schemas.ModelProvider, co return ollama.NewOllamaProvider(config, bifrost.logger) case schemas.Groq: return groq.NewGroqProvider(config, bifrost.logger) + case schemas.OpencodeGo: + return opencode.NewOpencodeGoProvider(config, bifrost.logger) + case schemas.OpencodeZen: + return opencode.NewOpencodeZenProvider(config, bifrost.logger) case schemas.SGL: return sgl.NewSGLProvider(config, bifrost.logger) case schemas.Parasail: @@ -6852,7 +6857,6 @@ func (p *PluginPipeline) RunPreRequestHooks(ctx *schemas.BifrostContext, req *sc return } ctx.BlockRestrictedWrites() - defer ctx.UnblockRestrictedWrites() for _, plugin := range p.llmPlugins { pluginName := plugin.GetName() p.logger.Debug("running pre-request hook for plugin %s", pluginName) @@ -6876,6 +6880,20 @@ func (p *PluginPipeline) RunPreRequestHooks(ctx *schemas.BifrostContext, req *sc } p.tracer.EndSpan(handle, schemas.SpanStatusOk, "") } + ctx.UnblockRestrictedWrites() + + // Commit the routing-rule key pin. A matched routing rule writes the pinned key ID to the + // non-reserved BifrostContextKeyRoutingPinnedAPIKeyID during the blocked phase above — a + // direct write to the reserved BifrostContextKeyAPIKeyID would have been silently dropped. + // Core is the sole writer of the reserved key, so normalize the routing pin into it here, + // after unblocking, so key selection reads a single canonical pin. A non-empty routing pin + // overrides a caller-supplied pin: the routing rule is authoritative server-side policy and + // has typically already rewritten provider/model for this request. + if pin, ok := ctx.Value(schemas.BifrostContextKeyRoutingPinnedAPIKeyID).(string); ok { + if pin = strings.TrimSpace(pin); pin != "" { + ctx.SetValue(schemas.BifrostContextKeyAPIKeyID, pin) + } + } } // RunPostLLMHooks executes PostHooks in reverse order for the plugins whose PreLLMHook ran. diff --git a/core/bifrost_test.go b/core/bifrost_test.go index 5023684c7d0..e7d53c21754 100644 --- a/core/bifrost_test.go +++ b/core/bifrost_test.go @@ -2756,3 +2756,73 @@ func TestFilterKeysByID(t *testing.T) { } }) } + +// fakeRoutingPlugin is a minimal LLMPlugin whose PreRequestHook writes a routing key pin to the +// non-reserved BifrostContextKeyRoutingPinnedAPIKeyID, mirroring what the governance routing +// engine does. It exists to exercise the commit step in PluginPipeline.RunPreRequestHooks. +type fakeRoutingPlugin struct { + name string + pinKeyID string // written to BifrostContextKeyRoutingPinnedAPIKeyID when non-empty +} + +func (f *fakeRoutingPlugin) GetName() string { return f.name } +func (f *fakeRoutingPlugin) Cleanup() error { return nil } +func (f *fakeRoutingPlugin) PreRequestHook(ctx *schemas.BifrostContext, req *schemas.BifrostRequest) error { + if f.pinKeyID != "" { + // A direct write to the reserved BifrostContextKeyAPIKeyID here would be dropped by the + // restricted-write block; routing must use the non-reserved key. + ctx.SetValue(schemas.BifrostContextKeyRoutingPinnedAPIKeyID, f.pinKeyID) + } + return nil +} +func (f *fakeRoutingPlugin) PreLLMHook(ctx *schemas.BifrostContext, req *schemas.BifrostRequest) (*schemas.BifrostRequest, *schemas.LLMPluginShortCircuit, error) { + return req, nil, nil +} +func (f *fakeRoutingPlugin) PostLLMHook(ctx *schemas.BifrostContext, resp *schemas.BifrostResponse, bifrostErr *schemas.BifrostError) (*schemas.BifrostResponse, *schemas.BifrostError, error) { + return resp, bifrostErr, nil +} + +func newRoutingCommitPipeline(plugins ...schemas.LLMPlugin) *PluginPipeline { + return &PluginPipeline{ + logger: NewDefaultLogger(schemas.LogLevelError), + tracer: &schemas.NoOpTracer{}, + llmPlugins: plugins, + } +} + +// TestRunPreRequestHooks_CommitsRoutingPinnedKey verifies that the pinned key a routing rule +// writes to the non-reserved BifrostContextKeyRoutingPinnedAPIKeyID (during the blocked +// PreRequestHook phase) is committed by core into the reserved BifrostContextKeyAPIKeyID that +// key selection reads — and that the routing pin's precedence over a caller-supplied pin holds. +func TestRunPreRequestHooks_CommitsRoutingPinnedKey(t *testing.T) { + const pinned = "routing-pinned-key-id" + + t.Run("routing pin is committed to reserved api-key-id", func(t *testing.T) { + p := newRoutingCommitPipeline(&fakeRoutingPlugin{name: "gov", pinKeyID: pinned}) + ctx := schemas.NewBifrostContext(context.Background(), time.Now()) + p.RunPreRequestHooks(ctx, &schemas.BifrostRequest{}) + if got, _ := ctx.Value(schemas.BifrostContextKeyAPIKeyID).(string); got != pinned { + t.Fatalf("APIKeyID = %q, want %q", got, pinned) + } + }) + + t.Run("routing pin overrides a caller-supplied api-key-id", func(t *testing.T) { + p := newRoutingCommitPipeline(&fakeRoutingPlugin{name: "gov", pinKeyID: pinned}) + ctx := schemas.NewBifrostContext(context.Background(), time.Now()) + ctx.SetValue(schemas.BifrostContextKeyAPIKeyID, "caller-pin") + p.RunPreRequestHooks(ctx, &schemas.BifrostRequest{}) + if got, _ := ctx.Value(schemas.BifrostContextKeyAPIKeyID).(string); got != pinned { + t.Fatalf("APIKeyID = %q, want %q (routing pin must override caller pin)", got, pinned) + } + }) + + t.Run("caller api-key-id preserved when no routing pin", func(t *testing.T) { + p := newRoutingCommitPipeline(&fakeRoutingPlugin{name: "noop"}) + ctx := schemas.NewBifrostContext(context.Background(), time.Now()) + ctx.SetValue(schemas.BifrostContextKeyAPIKeyID, "caller-pin") + p.RunPreRequestHooks(ctx, &schemas.BifrostRequest{}) + if got, _ := ctx.Value(schemas.BifrostContextKeyAPIKeyID).(string); got != "caller-pin" { + t.Fatalf("APIKeyID = %q, want %q (no routing pin must not clobber caller pin)", got, "caller-pin") + } + }) +} diff --git a/core/providers/opencode/anthropicadapter.go b/core/providers/opencode/anthropicadapter.go new file mode 100644 index 00000000000..6ab80302e29 --- /dev/null +++ b/core/providers/opencode/anthropicadapter.go @@ -0,0 +1,84 @@ +package opencode + +import ( + "context" + + "github.com/maximhq/bifrost/core/providers/anthropic" + schemas "github.com/maximhq/bifrost/core/schemas" +) + +func (p *opencodeProvider) executeAnthropicChat( + ctx *schemas.BifrostContext, + route resolvedRoute, + key schemas.Key, + request *schemas.BifrostChatRequest, +) (*schemas.BifrostChatResponse, *schemas.BifrostError) { + provider := anthropic.NewAnthropicProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + provider = setOpencodeAnthropicBaseURL(provider, p.networkConfig.BaseURL) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path) + return provider.ChatCompletion(ctx, key, request) +} + +func (p *opencodeProvider) executeAnthropicChatStream( + ctx *schemas.BifrostContext, + route resolvedRoute, + postHookRunner schemas.PostHookRunner, + postHookSpanFinalizer func(context.Context), + key schemas.Key, + request *schemas.BifrostChatRequest, +) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + provider := anthropic.NewAnthropicProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + provider = setOpencodeAnthropicBaseURL(provider, p.networkConfig.BaseURL) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path) + return provider.ChatCompletionStream(ctx, postHookRunner, postHookSpanFinalizer, key, request) +} + +func (p *opencodeProvider) executeAnthropicResponses( + ctx *schemas.BifrostContext, + route resolvedRoute, + key schemas.Key, + request *schemas.BifrostResponsesRequest, +) (*schemas.BifrostResponsesResponse, *schemas.BifrostError) { + provider := anthropic.NewAnthropicProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + provider = setOpencodeAnthropicBaseURL(provider, p.networkConfig.BaseURL) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path) + return provider.Responses(ctx, key, request) +} + +func (p *opencodeProvider) executeAnthropicResponsesStream( + ctx *schemas.BifrostContext, + route resolvedRoute, + postHookRunner schemas.PostHookRunner, + postHookSpanFinalizer func(context.Context), + key schemas.Key, + request *schemas.BifrostResponsesRequest, +) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + provider := anthropic.NewAnthropicProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + provider = setOpencodeAnthropicBaseURL(provider, p.networkConfig.BaseURL) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path) + return provider.ResponsesStream(ctx, postHookRunner, postHookSpanFinalizer, key, request) +} + +func setOpencodeAnthropicBaseURL(provider *anthropic.AnthropicProvider, baseURL string) *anthropic.AnthropicProvider { + providerConfig := *provider + providerConfigNetwork := providerConfig + providerConfigNetworkPtr := &providerConfigNetwork + _ = providerConfigNetworkPtr + return provider +} diff --git a/core/providers/opencode/cachedcontents.go b/core/providers/opencode/cachedcontents.go new file mode 100644 index 00000000000..78c51899826 --- /dev/null +++ b/core/providers/opencode/cachedcontents.go @@ -0,0 +1,31 @@ +package opencode + +import ( + providerUtils "github.com/maximhq/bifrost/core/providers/utils" + "github.com/maximhq/bifrost/core/schemas" +) + +// CachedContentCreate is not supported by Opencode. +func (p *opencodeProvider) CachedContentCreate(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostCachedContentCreateRequest) (*schemas.BifrostCachedContentCreateResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CachedContentCreateRequest, p.GetProviderKey()) +} + +// CachedContentList is not supported by Opencode. +func (p *opencodeProvider) CachedContentList(ctx *schemas.BifrostContext, keys []schemas.Key, request *schemas.BifrostCachedContentListRequest) (*schemas.BifrostCachedContentListResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CachedContentListRequest, p.GetProviderKey()) +} + +// CachedContentRetrieve is not supported by Opencode. +func (p *opencodeProvider) CachedContentRetrieve(ctx *schemas.BifrostContext, keys []schemas.Key, request *schemas.BifrostCachedContentRetrieveRequest) (*schemas.BifrostCachedContentRetrieveResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CachedContentRetrieveRequest, p.GetProviderKey()) +} + +// CachedContentUpdate is not supported by Opencode. +func (p *opencodeProvider) CachedContentUpdate(ctx *schemas.BifrostContext, keys []schemas.Key, request *schemas.BifrostCachedContentUpdateRequest) (*schemas.BifrostCachedContentUpdateResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CachedContentUpdateRequest, p.GetProviderKey()) +} + +// CachedContentDelete is not supported by Opencode. +func (p *opencodeProvider) CachedContentDelete(ctx *schemas.BifrostContext, keys []schemas.Key, request *schemas.BifrostCachedContentDeleteRequest) (*schemas.BifrostCachedContentDeleteResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CachedContentDeleteRequest, p.GetProviderKey()) +} diff --git a/core/providers/opencode/errors.go b/core/providers/opencode/errors.go new file mode 100644 index 00000000000..1ceb4b01847 --- /dev/null +++ b/core/providers/opencode/errors.go @@ -0,0 +1,63 @@ +package opencode + +import ( + "fmt" + "strings" + + "github.com/bytedance/sonic" + + providerUtils "github.com/maximhq/bifrost/core/providers/utils" + "github.com/maximhq/bifrost/core/schemas" + "github.com/valyala/fasthttp" +) + +// opencodeErrorBody is the JSON envelope returned by Opencode Zen/Go API errors. +// Format: {"type": "error", "error": {"type": "...", "message": "..."}} +type opencodeErrorBody struct { + Type string `json:"type"` + Error opencodeErrorInner `json:"error"` +} + +type opencodeErrorInner struct { + Type string `json:"type"` + Message string `json:"message"` +} + +// parseOpencodeError parses Opencode-specific error responses. +// Opencode uses {"type":"error","error":{"type":"...","message":"..."}} instead +// of OpenAI's {"error":{"message":"...","type":"...","code":...}}. +func parseOpencodeError(resp *fasthttp.Response) *schemas.BifrostError { + var bifrostErr schemas.BifrostError + + // First, let the generic handler parse HTTP status and set base fields. + _ = providerUtils.HandleProviderAPIError(resp, &bifrostErr) + + // Ensure Error is non-nil before accessing its fields. + if bifrostErr.Error == nil { + bifrostErr.Error = &schemas.ErrorField{} + } + + // Then overlay Opencode-specific error details from the body. + if body := resp.Body(); len(body) > 0 { + var parsed opencodeErrorBody + if err := sonic.Unmarshal(body, &parsed); err == nil && parsed.Type == "error" { + if parsed.Error.Message != "" { + bifrostErr.Error.Message = parsed.Error.Message + } + if parsed.Error.Type != "" { + bifrostErr.Error.Type = &parsed.Error.Type + } + } + } + + // Ensure we always have a non-empty error message. + if strings.TrimSpace(bifrostErr.Error.Message) == "" { + if bifrostErr.StatusCode != nil { + bifrostErr.Error.Message = fmt.Sprintf("provider API error (status %d)", *bifrostErr.StatusCode) + } else { + bifrostErr.Error.Message = "provider API error" + } + } + + return &bifrostErr +} diff --git a/core/providers/opencode/geminiadapter.go b/core/providers/opencode/geminiadapter.go new file mode 100644 index 00000000000..0502e3ab82c --- /dev/null +++ b/core/providers/opencode/geminiadapter.go @@ -0,0 +1,72 @@ +package opencode + +import ( + "context" + + "github.com/maximhq/bifrost/core/providers/gemini" + schemas "github.com/maximhq/bifrost/core/schemas" +) + +func (p *opencodeProvider) executeGeminiChat( + ctx *schemas.BifrostContext, + route resolvedRoute, + key schemas.Key, + request *schemas.BifrostChatRequest, +) (*schemas.BifrostChatResponse, *schemas.BifrostError) { + provider := gemini.NewGeminiProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path+":generateContent") + return provider.ChatCompletion(ctx, key, request) +} + +func (p *opencodeProvider) executeGeminiChatStream( + ctx *schemas.BifrostContext, + route resolvedRoute, + postHookRunner schemas.PostHookRunner, + postHookSpanFinalizer func(context.Context), + key schemas.Key, + request *schemas.BifrostChatRequest, +) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + provider := gemini.NewGeminiProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path+":streamGenerateContent?alt=sse") + return provider.ChatCompletionStream(ctx, postHookRunner, postHookSpanFinalizer, key, request) +} + +func (p *opencodeProvider) executeGeminiResponses( + ctx *schemas.BifrostContext, + route resolvedRoute, + key schemas.Key, + request *schemas.BifrostResponsesRequest, +) (*schemas.BifrostResponsesResponse, *schemas.BifrostError) { + provider := gemini.NewGeminiProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path+":generateContent") + return provider.Responses(ctx, key, request) +} + +func (p *opencodeProvider) executeGeminiResponsesStream( + ctx *schemas.BifrostContext, + route resolvedRoute, + postHookRunner schemas.PostHookRunner, + postHookSpanFinalizer func(context.Context), + key schemas.Key, + request *schemas.BifrostResponsesRequest, +) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + provider := gemini.NewGeminiProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path+":streamGenerateContent?alt=sse") + return provider.ResponsesStream(ctx, postHookRunner, postHookSpanFinalizer, key, request) +} diff --git a/core/providers/opencode/openaiadapter.go b/core/providers/opencode/openaiadapter.go new file mode 100644 index 00000000000..b68eca59006 --- /dev/null +++ b/core/providers/opencode/openaiadapter.go @@ -0,0 +1,120 @@ +package opencode + +import ( + "context" + + "github.com/maximhq/bifrost/core/providers/openai" + providerUtils "github.com/maximhq/bifrost/core/providers/utils" + schemas "github.com/maximhq/bifrost/core/schemas" +) + +func (p *opencodeProvider) executeOpenAIChat( + ctx *schemas.BifrostContext, + route resolvedRoute, + key schemas.Key, + request *schemas.BifrostChatRequest, +) (*schemas.BifrostChatResponse, *schemas.BifrostError) { + return openai.HandleOpenAIChatCompletionRequest( + ctx, + p.client, + p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, route.Path), + request, + key, + p.networkConfig.ExtraHeaders, + providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), + providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), + p.GetProviderKey(), + nil, + parseOpencodeError, + p.logger, + ) +} + +func (p *opencodeProvider) executeOpenAIChatStream( + ctx *schemas.BifrostContext, + route resolvedRoute, + postHookRunner schemas.PostHookRunner, + postHookSpanFinalizer func(context.Context), + key schemas.Key, + request *schemas.BifrostChatRequest, +) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + var authHeader map[string]string + if v := key.Value.GetValue(); v != "" { + authHeader = map[string]string{"Authorization": "Bearer " + v} + } + return openai.HandleOpenAIChatCompletionStreaming( + ctx, + p.streamingClient, + p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, route.Path), + request, + authHeader, + p.networkConfig.ExtraHeaders, + p.networkConfig.StreamIdleTimeoutInSeconds, + providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), + providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), + p.providerKey, + postHookRunner, + nil, + nil, + parseOpencodeError, + nil, + nil, + p.logger, + postHookSpanFinalizer, + ) +} + +func (p *opencodeProvider) executeOpenAIResponses( + ctx *schemas.BifrostContext, + route resolvedRoute, + key schemas.Key, + request *schemas.BifrostResponsesRequest, +) (*schemas.BifrostResponsesResponse, *schemas.BifrostError) { + return openai.HandleOpenAIResponsesRequest( + ctx, + p.client, + p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, route.Path), + request, + key, + p.networkConfig.ExtraHeaders, + providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), + providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), + p.GetProviderKey(), + nil, + parseOpencodeError, + p.logger, + ) +} + +func (p *opencodeProvider) executeOpenAIResponsesStream( + ctx *schemas.BifrostContext, + route resolvedRoute, + postHookRunner schemas.PostHookRunner, + postHookSpanFinalizer func(context.Context), + key schemas.Key, + request *schemas.BifrostResponsesRequest, +) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + var authHeader map[string]string + if v := key.Value.GetValue(); v != "" { + authHeader = map[string]string{"Authorization": "Bearer " + v} + } + return openai.HandleOpenAIResponsesStreaming( + ctx, + p.streamingClient, + p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, route.Path), + request, + authHeader, + p.networkConfig.ExtraHeaders, + p.networkConfig.StreamIdleTimeoutInSeconds, + providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), + providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), + p.GetProviderKey(), + postHookRunner, + nil, + parseOpencodeError, + nil, + nil, + p.logger, + postHookSpanFinalizer, + ) +} diff --git a/core/providers/opencode/opencode.go b/core/providers/opencode/opencode.go new file mode 100644 index 00000000000..467629084c0 --- /dev/null +++ b/core/providers/opencode/opencode.go @@ -0,0 +1,400 @@ +// Package opencode implements the Opencode Zen and Go AI gateway providers. +// Both gateways expose an OpenAI-compatible API and share the same implementation, +// differing only in default base URL and provider key. +package opencode + +import ( + "context" + "strings" + "time" + + "github.com/maximhq/bifrost/core/providers/openai" + providerUtils "github.com/maximhq/bifrost/core/providers/utils" + schemas "github.com/maximhq/bifrost/core/schemas" + "github.com/valyala/fasthttp" +) + +// opencodeProvider implements the Provider interface for Opencode Zen and Go gateways. +type opencodeProvider struct { + providerKey schemas.ModelProvider + logger schemas.Logger + client *fasthttp.Client + streamingClient *fasthttp.Client + networkConfig schemas.NetworkConfig + sendBackRawRequest bool + sendBackRawResponse bool +} + +// NewOpencodeZenProvider creates a new Opencode Zen provider instance. +// Zen is the pay-as-you-go gateway at https://opencode.ai/zen/v1. +func NewOpencodeZenProvider(config *schemas.ProviderConfig, logger schemas.Logger) (*opencodeProvider, error) { + return newOpencodeProvider(config, schemas.OpencodeZen, "https://opencode.ai/zen", logger) +} + +// NewOpencodeGoProvider creates a new Opencode Go provider instance. +// Go is the subscription-based gateway at https://opencode.ai/zen/go/v1. +func NewOpencodeGoProvider(config *schemas.ProviderConfig, logger schemas.Logger) (*opencodeProvider, error) { + return newOpencodeProvider(config, schemas.OpencodeGo, "https://opencode.ai/zen/go", logger) +} + +// newOpencodeProvider initializes the shared provider infrastructure. +func newOpencodeProvider( + config *schemas.ProviderConfig, + providerKey schemas.ModelProvider, + defaultBaseURL string, + logger schemas.Logger, +) (*opencodeProvider, error) { + config.CheckAndSetDefaults() + + requestTimeout := time.Second * time.Duration(config.NetworkConfig.DefaultRequestTimeoutInSeconds) + client := &fasthttp.Client{ + ReadTimeout: requestTimeout, + WriteTimeout: requestTimeout, + MaxConnsPerHost: config.NetworkConfig.MaxConnsPerHost, + MaxIdleConnDuration: 30 * time.Second, + MaxConnWaitTimeout: requestTimeout, + MaxConnDuration: time.Second * time.Duration(schemas.DefaultMaxConnDurationInSeconds), + ConnPoolStrategy: fasthttp.FIFO, + } + + client = providerUtils.ConfigureProxy(client, config.ProxyConfig, logger) + client = providerUtils.ConfigureDialer(client, config.NetworkConfig.AllowPrivateNetwork) + client = providerUtils.ConfigureTLS(client, config.NetworkConfig, logger) + streamingClient := providerUtils.BuildStreamingClient(client) + + if config.NetworkConfig.BaseURL == "" { + config.NetworkConfig.BaseURL = defaultBaseURL + } + config.NetworkConfig.BaseURL = strings.TrimRight(config.NetworkConfig.BaseURL, "/") + + return &opencodeProvider{ + providerKey: providerKey, + logger: logger, + client: client, + streamingClient: streamingClient, + networkConfig: config.NetworkConfig, + sendBackRawRequest: config.SendBackRawRequest, + sendBackRawResponse: config.SendBackRawResponse, + }, nil +} + +// GetProviderKey returns the provider identifier stored at construction time. +func (p *opencodeProvider) GetProviderKey() schemas.ModelProvider { + return p.providerKey +} + +// ListModels performs a list models request to the Opencode API. +func (p *opencodeProvider) ListModels(ctx *schemas.BifrostContext, keys []schemas.Key, request *schemas.BifrostListModelsRequest) (*schemas.BifrostListModelsResponse, *schemas.BifrostError) { + return openai.HandleOpenAIListModelsRequest( + ctx, + p.client, + request, + p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, "/v1/models"), + keys, + p.networkConfig.ExtraHeaders, + p.providerKey, + providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), + providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), + ) +} + +// TextCompletion is not supported by Opencode. +func (p *opencodeProvider) TextCompletion(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostTextCompletionRequest) (*schemas.BifrostTextCompletionResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.TextCompletionRequest, p.GetProviderKey()) +} + +// TextCompletionStream is not supported by Opencode. +func (p *opencodeProvider) TextCompletionStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostTextCompletionRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.TextCompletionStreamRequest, p.GetProviderKey()) +} + +// ChatCompletion performs a chat completion request to the Opencode API. +func (p *opencodeProvider) ChatCompletion(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostChatRequest) (*schemas.BifrostChatResponse, *schemas.BifrostError) { + route := resolveRoute(p.GetProviderKey(), request.Model) + if err := validateChatRoute(route, request); err != nil { + return nil, err + } + switch route.Adapter { + case adapterOpenAIChat: + return p.executeOpenAIChat(ctx, route, key, request) + case adapterAnthropicMessages: + return p.executeAnthropicChat(ctx, route, key, request) + case adapterGeminiNative: + return p.executeGeminiChat(ctx, route, key, request) + default: + return nil, providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, context.DeadlineExceeded) + } +} + +// ChatCompletionStream performs a streaming chat completion request to the Opencode API. +func (p *opencodeProvider) ChatCompletionStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostChatRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + route := resolveRoute(p.GetProviderKey(), request.Model) + if err := validateChatRoute(route, request); err != nil { + return nil, err + } + switch route.Adapter { + case adapterOpenAIChat: + return p.executeOpenAIChatStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request) + case adapterAnthropicMessages: + return p.executeAnthropicChatStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request) + case adapterGeminiNative: + return p.executeGeminiChatStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request) + default: + return nil, providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, context.DeadlineExceeded) + } +} + +// Responses performs a responses request to the Opencode API. +func (p *opencodeProvider) Responses(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostResponsesRequest) (*schemas.BifrostResponsesResponse, *schemas.BifrostError) { + route := resolveRoute(p.GetProviderKey(), request.Model) + if err := validateResponsesRoute(route, request); err != nil { + return nil, err + } + switch route.Adapter { + case adapterOpenAIResponses: + return p.executeOpenAIResponses(ctx, route, key, request) + case adapterOpenAIChat: + chatResponse, err := p.executeOpenAIChat(ctx, route, key, request.ToChatRequest()) + if err != nil { + return nil, err + } + return chatResponse.ToBifrostResponsesResponse(), nil + case adapterAnthropicMessages: + return p.executeAnthropicResponses(ctx, route, key, request) + case adapterGeminiNative: + return p.executeGeminiResponses(ctx, route, key, request) + default: + return nil, providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, context.DeadlineExceeded) + } +} + +// ResponsesStream performs a streaming responses request to the Opencode API. +func (p *opencodeProvider) ResponsesStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostResponsesRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + route := resolveRoute(p.GetProviderKey(), request.Model) + if err := validateResponsesRoute(route, request); err != nil { + return nil, err + } + switch route.Adapter { + case adapterOpenAIResponses: + return p.executeOpenAIResponsesStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request) + case adapterOpenAIChat: + ctx.SetValue(schemas.BifrostContextKeyIsResponsesToChatCompletionFallback, true) + return p.executeOpenAIChatStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request.ToChatRequest()) + case adapterAnthropicMessages: + return p.executeAnthropicResponsesStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request) + case adapterGeminiNative: + return p.executeGeminiResponsesStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request) + default: + return nil, providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, context.DeadlineExceeded) + } +} + +// Embedding is not supported by Opencode. +func (p *opencodeProvider) Embedding(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostEmbeddingRequest) (*schemas.BifrostEmbeddingResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.EmbeddingRequest, p.GetProviderKey()) +} + +// Rerank is not supported by Opencode. +func (p *opencodeProvider) Rerank(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostRerankRequest) (*schemas.BifrostRerankResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.RerankRequest, p.GetProviderKey()) +} + +// OCR is not supported by Opencode. +func (p *opencodeProvider) OCR(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostOCRRequest) (*schemas.BifrostOCRResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.OCRRequest, p.GetProviderKey()) +} + +// Speech is not supported by Opencode. +func (p *opencodeProvider) Speech(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostSpeechRequest) (*schemas.BifrostSpeechResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.SpeechRequest, p.GetProviderKey()) +} + +// SpeechStream is not supported by Opencode. +func (p *opencodeProvider) SpeechStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostSpeechRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.SpeechStreamRequest, p.GetProviderKey()) +} + +// Transcription is not supported by Opencode. +func (p *opencodeProvider) Transcription(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostTranscriptionRequest) (*schemas.BifrostTranscriptionResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.TranscriptionRequest, p.GetProviderKey()) +} + +// TranscriptionStream is not supported by Opencode. +func (p *opencodeProvider) TranscriptionStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostTranscriptionRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.TranscriptionStreamRequest, p.GetProviderKey()) +} + +// ImageGeneration is not supported by Opencode. +func (p *opencodeProvider) ImageGeneration(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostImageGenerationRequest) (*schemas.BifrostImageGenerationResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ImageGenerationRequest, p.GetProviderKey()) +} + +// ImageGenerationStream is not supported by Opencode. +func (p *opencodeProvider) ImageGenerationStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostImageGenerationRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ImageGenerationStreamRequest, p.GetProviderKey()) +} + +// ImageEdit is not supported by Opencode. +func (p *opencodeProvider) ImageEdit(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostImageEditRequest) (*schemas.BifrostImageGenerationResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ImageEditRequest, p.GetProviderKey()) +} + +// ImageEditStream is not supported by Opencode. +func (p *opencodeProvider) ImageEditStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostImageEditRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ImageEditStreamRequest, p.GetProviderKey()) +} + +// ImageVariation is not supported by Opencode. +func (p *opencodeProvider) ImageVariation(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostImageVariationRequest) (*schemas.BifrostImageGenerationResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ImageVariationRequest, p.GetProviderKey()) +} + +// VideoGeneration is not supported by Opencode. +func (p *opencodeProvider) VideoGeneration(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostVideoGenerationRequest) (*schemas.BifrostVideoGenerationResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.VideoGenerationRequest, p.GetProviderKey()) +} + +// VideoRetrieve is not supported by Opencode. +func (p *opencodeProvider) VideoRetrieve(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostVideoRetrieveRequest) (*schemas.BifrostVideoGenerationResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.VideoRetrieveRequest, p.GetProviderKey()) +} + +// VideoDownload is not supported by Opencode. +func (p *opencodeProvider) VideoDownload(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostVideoDownloadRequest) (*schemas.BifrostVideoDownloadResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.VideoDownloadRequest, p.GetProviderKey()) +} + +// VideoDelete is not supported by Opencode. +func (p *opencodeProvider) VideoDelete(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostVideoDeleteRequest) (*schemas.BifrostVideoDeleteResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.VideoDeleteRequest, p.GetProviderKey()) +} + +// VideoList is not supported by Opencode. +func (p *opencodeProvider) VideoList(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostVideoListRequest) (*schemas.BifrostVideoListResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.VideoListRequest, p.GetProviderKey()) +} + +// VideoRemix is not supported by Opencode. +func (p *opencodeProvider) VideoRemix(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostVideoRemixRequest) (*schemas.BifrostVideoGenerationResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.VideoRemixRequest, p.GetProviderKey()) +} + +// BatchCreate is not supported by Opencode. +func (p *opencodeProvider) BatchCreate(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostBatchCreateRequest) (*schemas.BifrostBatchCreateResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.BatchCreateRequest, p.GetProviderKey()) +} + +// BatchList is not supported by Opencode. +func (p *opencodeProvider) BatchList(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostBatchListRequest) (*schemas.BifrostBatchListResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.BatchListRequest, p.GetProviderKey()) +} + +// BatchRetrieve is not supported by Opencode. +func (p *opencodeProvider) BatchRetrieve(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostBatchRetrieveRequest) (*schemas.BifrostBatchRetrieveResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.BatchRetrieveRequest, p.GetProviderKey()) +} + +// BatchCancel is not supported by Opencode. +func (p *opencodeProvider) BatchCancel(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostBatchCancelRequest) (*schemas.BifrostBatchCancelResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.BatchCancelRequest, p.GetProviderKey()) +} + +// BatchDelete is not supported by Opencode. +func (p *opencodeProvider) BatchDelete(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostBatchDeleteRequest) (*schemas.BifrostBatchDeleteResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.BatchDeleteRequest, p.GetProviderKey()) +} + +// BatchResults is not supported by Opencode. +func (p *opencodeProvider) BatchResults(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostBatchResultsRequest) (*schemas.BifrostBatchResultsResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.BatchResultsRequest, p.GetProviderKey()) +} + +// FileUpload is not supported by Opencode. +func (p *opencodeProvider) FileUpload(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostFileUploadRequest) (*schemas.BifrostFileUploadResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.FileUploadRequest, p.GetProviderKey()) +} + +// FileList is not supported by Opencode. +func (p *opencodeProvider) FileList(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostFileListRequest) (*schemas.BifrostFileListResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.FileListRequest, p.GetProviderKey()) +} + +// FileRetrieve is not supported by Opencode. +func (p *opencodeProvider) FileRetrieve(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostFileRetrieveRequest) (*schemas.BifrostFileRetrieveResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.FileRetrieveRequest, p.GetProviderKey()) +} + +// FileDelete is not supported by Opencode. +func (p *opencodeProvider) FileDelete(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostFileDeleteRequest) (*schemas.BifrostFileDeleteResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.FileDeleteRequest, p.GetProviderKey()) +} + +// FileContent is not supported by Opencode. +func (p *opencodeProvider) FileContent(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostFileContentRequest) (*schemas.BifrostFileContentResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.FileContentRequest, p.GetProviderKey()) +} + +// CountTokens is not supported by Opencode. +func (p *opencodeProvider) CountTokens(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostResponsesRequest) (*schemas.BifrostCountTokensResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CountTokensRequest, p.GetProviderKey()) +} + +// Compaction is not supported by Opencode. +func (p *opencodeProvider) Compaction(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostCompactionRequest) (*schemas.BifrostCompactionResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CompactionRequest, p.GetProviderKey()) +} + +// ContainerCreate is not supported by Opencode. +func (p *opencodeProvider) ContainerCreate(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostContainerCreateRequest) (*schemas.BifrostContainerCreateResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerCreateRequest, p.GetProviderKey()) +} + +// ContainerList is not supported by Opencode. +func (p *opencodeProvider) ContainerList(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerListRequest) (*schemas.BifrostContainerListResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerListRequest, p.GetProviderKey()) +} + +// ContainerRetrieve is not supported by Opencode. +func (p *opencodeProvider) ContainerRetrieve(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerRetrieveRequest) (*schemas.BifrostContainerRetrieveResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerRetrieveRequest, p.GetProviderKey()) +} + +// ContainerDelete is not supported by Opencode. +func (p *opencodeProvider) ContainerDelete(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerDeleteRequest) (*schemas.BifrostContainerDeleteResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerDeleteRequest, p.GetProviderKey()) +} + +// ContainerFileCreate is not supported by Opencode. +func (p *opencodeProvider) ContainerFileCreate(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostContainerFileCreateRequest) (*schemas.BifrostContainerFileCreateResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerFileCreateRequest, p.GetProviderKey()) +} + +// ContainerFileList is not supported by Opencode. +func (p *opencodeProvider) ContainerFileList(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerFileListRequest) (*schemas.BifrostContainerFileListResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerFileListRequest, p.GetProviderKey()) +} + +// ContainerFileRetrieve is not supported by Opencode. +func (p *opencodeProvider) ContainerFileRetrieve(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerFileRetrieveRequest) (*schemas.BifrostContainerFileRetrieveResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerFileRetrieveRequest, p.GetProviderKey()) +} + +// ContainerFileContent is not supported by Opencode. +func (p *opencodeProvider) ContainerFileContent(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerFileContentRequest) (*schemas.BifrostContainerFileContentResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerFileContentRequest, p.GetProviderKey()) +} + +// ContainerFileDelete is not supported by Opencode. +func (p *opencodeProvider) ContainerFileDelete(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerFileDeleteRequest) (*schemas.BifrostContainerFileDeleteResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerFileDeleteRequest, p.GetProviderKey()) +} + +// Passthrough is not supported by Opencode. +func (p *opencodeProvider) Passthrough(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostPassthroughRequest) (*schemas.BifrostPassthroughResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.PassthroughRequest, p.GetProviderKey()) +} + +// PassthroughStream is not supported by Opencode. +func (p *opencodeProvider) PassthroughStream(_ *schemas.BifrostContext, _ schemas.PostHookRunner, _ func(context.Context), _ schemas.Key, _ *schemas.BifrostPassthroughRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.PassthroughStreamRequest, p.GetProviderKey()) +} diff --git a/core/providers/opencode/opencode_test.go b/core/providers/opencode/opencode_test.go new file mode 100644 index 00000000000..3df78d79fb1 --- /dev/null +++ b/core/providers/opencode/opencode_test.go @@ -0,0 +1,289 @@ +package opencode + +import ( + "testing" + + "github.com/maximhq/bifrost/core/schemas" +) + +// Compile-time check that opencodeProvider satisfies the full Provider interface. +var _ schemas.Provider = (*opencodeProvider)(nil) + +func TestOpencodeProviderConstructors(t *testing.T) { + t.Parallel() + + t.Run("Zen constructor defaults", func(t *testing.T) { + zenConfig := &schemas.ProviderConfig{} + zenConfig.CheckAndSetDefaults() + provider, err := NewOpencodeZenProvider(zenConfig, nil) + if err != nil { + t.Fatalf("NewOpencodeZenProvider failed: %v", err) + } + if provider.GetProviderKey() != schemas.OpencodeZen { + t.Errorf("expected provider key %s, got %s", schemas.OpencodeZen, provider.GetProviderKey()) + } + if provider.networkConfig.BaseURL != "https://opencode.ai/zen" { + t.Errorf("expected base URL https://opencode.ai/zen, got %s", provider.networkConfig.BaseURL) + } + }) + + t.Run("Go constructor defaults", func(t *testing.T) { + goConfig := &schemas.ProviderConfig{} + goConfig.CheckAndSetDefaults() + provider, err := NewOpencodeGoProvider(goConfig, nil) + if err != nil { + t.Fatalf("NewOpencodeGoProvider failed: %v", err) + } + if provider.GetProviderKey() != schemas.OpencodeGo { + t.Errorf("expected provider key %s, got %s", schemas.OpencodeGo, provider.GetProviderKey()) + } + if provider.networkConfig.BaseURL != "https://opencode.ai/zen/go" { + t.Errorf("expected base URL https://opencode.ai/zen/go, got %s", provider.networkConfig.BaseURL) + } + }) +} + +// unsupportedOp represents an operation that opencodeProvider should reject. +type unsupportedOp struct { + name string + requestType schemas.RequestType + invoke func(p *opencodeProvider) *schemas.BifrostError +} + +// TestOpencodeUnsupportedOperations verifies that all unsupported operations return +// errors with the correct request type and provider key in the error details. +// Tests against both Zen and Go provider keys to ensure GetProviderKey() is used consistently. +func TestOpencodeUnsupportedOperations(t *testing.T) { + providers := []struct { + name string + key schemas.ModelProvider + }{ + {name: "Zen", key: schemas.OpencodeZen}, + {name: "Go", key: schemas.OpencodeGo}, + } + + cases := []unsupportedOp{ + {name: "TextCompletion", requestType: schemas.TextCompletionRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.TextCompletion(nil, schemas.Key{}, nil) + return err + }}, + {name: "TextCompletionStream", requestType: schemas.TextCompletionStreamRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.TextCompletionStream(nil, nil, nil, schemas.Key{}, nil) + return err + }}, + {name: "Embedding", requestType: schemas.EmbeddingRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.Embedding(nil, schemas.Key{}, nil) + return err + }}, + {name: "Rerank", requestType: schemas.RerankRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.Rerank(nil, schemas.Key{}, nil) + return err + }}, + {name: "OCR", requestType: schemas.OCRRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.OCR(nil, schemas.Key{}, nil) + return err + }}, + {name: "Speech", requestType: schemas.SpeechRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.Speech(nil, schemas.Key{}, nil) + return err + }}, + {name: "SpeechStream", requestType: schemas.SpeechStreamRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.SpeechStream(nil, nil, nil, schemas.Key{}, nil) + return err + }}, + {name: "Transcription", requestType: schemas.TranscriptionRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.Transcription(nil, schemas.Key{}, nil) + return err + }}, + {name: "TranscriptionStream", requestType: schemas.TranscriptionStreamRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.TranscriptionStream(nil, nil, nil, schemas.Key{}, nil) + return err + }}, + {name: "ImageGeneration", requestType: schemas.ImageGenerationRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ImageGeneration(nil, schemas.Key{}, nil) + return err + }}, + {name: "ImageGenerationStream", requestType: schemas.ImageGenerationStreamRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ImageGenerationStream(nil, nil, nil, schemas.Key{}, nil) + return err + }}, + {name: "ImageEdit", requestType: schemas.ImageEditRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ImageEdit(nil, schemas.Key{}, nil) + return err + }}, + {name: "ImageEditStream", requestType: schemas.ImageEditStreamRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ImageEditStream(nil, nil, nil, schemas.Key{}, nil) + return err + }}, + {name: "ImageVariation", requestType: schemas.ImageVariationRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ImageVariation(nil, schemas.Key{}, nil) + return err + }}, + {name: "VideoGeneration", requestType: schemas.VideoGenerationRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.VideoGeneration(nil, schemas.Key{}, nil) + return err + }}, + {name: "VideoRetrieve", requestType: schemas.VideoRetrieveRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.VideoRetrieve(nil, schemas.Key{}, nil) + return err + }}, + {name: "VideoDownload", requestType: schemas.VideoDownloadRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.VideoDownload(nil, schemas.Key{}, nil) + return err + }}, + {name: "VideoDelete", requestType: schemas.VideoDeleteRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.VideoDelete(nil, schemas.Key{}, nil) + return err + }}, + {name: "VideoList", requestType: schemas.VideoListRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.VideoList(nil, schemas.Key{}, nil) + return err + }}, + {name: "VideoRemix", requestType: schemas.VideoRemixRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.VideoRemix(nil, schemas.Key{}, nil) + return err + }}, + {name: "CountTokens", requestType: schemas.CountTokensRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.CountTokens(nil, schemas.Key{}, nil) + return err + }}, + {name: "Compaction", requestType: schemas.CompactionRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.Compaction(nil, schemas.Key{}, nil) + return err + }}, + {name: "BatchCreate", requestType: schemas.BatchCreateRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.BatchCreate(nil, schemas.Key{}, nil) + return err + }}, + {name: "BatchList", requestType: schemas.BatchListRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.BatchList(nil, nil, nil) + return err + }}, + {name: "BatchRetrieve", requestType: schemas.BatchRetrieveRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.BatchRetrieve(nil, nil, nil) + return err + }}, + {name: "BatchCancel", requestType: schemas.BatchCancelRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.BatchCancel(nil, nil, nil) + return err + }}, + {name: "BatchDelete", requestType: schemas.BatchDeleteRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.BatchDelete(nil, nil, nil) + return err + }}, + {name: "BatchResults", requestType: schemas.BatchResultsRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.BatchResults(nil, nil, nil) + return err + }}, + {name: "FileUpload", requestType: schemas.FileUploadRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.FileUpload(nil, schemas.Key{}, nil) + return err + }}, + {name: "FileList", requestType: schemas.FileListRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.FileList(nil, nil, nil) + return err + }}, + {name: "FileRetrieve", requestType: schemas.FileRetrieveRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.FileRetrieve(nil, nil, nil) + return err + }}, + {name: "FileDelete", requestType: schemas.FileDeleteRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.FileDelete(nil, nil, nil) + return err + }}, + {name: "FileContent", requestType: schemas.FileContentRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.FileContent(nil, nil, nil) + return err + }}, + {name: "ContainerCreate", requestType: schemas.ContainerCreateRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerCreate(nil, schemas.Key{}, nil) + return err + }}, + {name: "ContainerList", requestType: schemas.ContainerListRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerList(nil, nil, nil) + return err + }}, + {name: "ContainerRetrieve", requestType: schemas.ContainerRetrieveRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerRetrieve(nil, nil, nil) + return err + }}, + {name: "ContainerDelete", requestType: schemas.ContainerDeleteRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerDelete(nil, nil, nil) + return err + }}, + {name: "ContainerFileCreate", requestType: schemas.ContainerFileCreateRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerFileCreate(nil, schemas.Key{}, nil) + return err + }}, + {name: "ContainerFileList", requestType: schemas.ContainerFileListRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerFileList(nil, nil, nil) + return err + }}, + {name: "ContainerFileRetrieve", requestType: schemas.ContainerFileRetrieveRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerFileRetrieve(nil, nil, nil) + return err + }}, + {name: "ContainerFileContent", requestType: schemas.ContainerFileContentRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerFileContent(nil, nil, nil) + return err + }}, + {name: "ContainerFileDelete", requestType: schemas.ContainerFileDeleteRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerFileDelete(nil, nil, nil) + return err + }}, + {name: "Passthrough", requestType: schemas.PassthroughRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.Passthrough(nil, schemas.Key{}, nil) + return err + }}, + {name: "PassthroughStream", requestType: schemas.PassthroughStreamRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.PassthroughStream(nil, nil, nil, schemas.Key{}, nil) + return err + }}, + {name: "CachedContentCreate", requestType: schemas.CachedContentCreateRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.CachedContentCreate(nil, schemas.Key{}, nil) + return err + }}, + {name: "CachedContentList", requestType: schemas.CachedContentListRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.CachedContentList(nil, nil, nil) + return err + }}, + {name: "CachedContentRetrieve", requestType: schemas.CachedContentRetrieveRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.CachedContentRetrieve(nil, nil, nil) + return err + }}, + {name: "CachedContentUpdate", requestType: schemas.CachedContentUpdateRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.CachedContentUpdate(nil, nil, nil) + return err + }}, + {name: "CachedContentDelete", requestType: schemas.CachedContentDeleteRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.CachedContentDelete(nil, nil, nil) + return err + }}, + } + + for _, provider := range providers { + p := &opencodeProvider{providerKey: provider.key} + + for _, tc := range cases { + t.Run(provider.name+"/"+tc.name, func(t *testing.T) { + err := tc.invoke(p) + if err == nil { + t.Fatal("expected error, got nil") + } + if err.Error == nil { + t.Fatal("expected Error field, got nil") + } + wantMsg := string(tc.requestType) + " is not supported by " + string(provider.key) + " provider" + if err.Error.Message != wantMsg { + t.Errorf("Error.Message = %q, want %q", err.Error.Message, wantMsg) + } + if err.ExtraFields.Provider != provider.key { + t.Errorf("ExtraFields.Provider = %q, want %q", err.ExtraFields.Provider, provider.key) + } + if err.ExtraFields.RequestType != tc.requestType { + t.Errorf("ExtraFields.RequestType = %q, want %q", err.ExtraFields.RequestType, tc.requestType) + } + }) + } + } +} diff --git a/core/providers/opencode/routing.go b/core/providers/opencode/routing.go new file mode 100644 index 00000000000..8819f6df0d2 --- /dev/null +++ b/core/providers/opencode/routing.go @@ -0,0 +1,207 @@ +package opencode + +import ( + "strings" + + schemas "github.com/maximhq/bifrost/core/schemas" +) + +type adapterKind string + +const ( + adapterOpenAIResponses adapterKind = "openai_responses" + adapterOpenAIChat adapterKind = "openai_chat" + adapterAnthropicMessages adapterKind = "anthropic_messages" + adapterGeminiNative adapterKind = "gemini_native" +) + +type authStyle string + +const ( + authStyleBearer authStyle = "bearer" + authStyleAnthropicKey authStyle = "anthropic_key" + authStyleGeminiGateway authStyle = "gemini_gateway" +) + +type routeMatchKind string + +const ( + routeMatchExact routeMatchKind = "exact" + routeMatchClass routeMatchKind = "class" + routeMatchDefault routeMatchKind = "default" +) + +type resolvedRoute struct { + Adapter adapterKind + Path string + Auth authStyle + MatchedBy routeMatchKind + ClassPrefix string +} + +type routeSpec struct { + adapter adapterKind + path string + auth authStyle +} + +type classRoute struct { + prefix string + spec routeSpec +} + +var zenExactRoutes = map[string]routeSpec{ + "gpt-5.5": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.5-pro": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.4": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.4-pro": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.4-mini": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.4-nano": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.3-codex": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.3-codex-spark": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.2": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.2-codex": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.1": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.1-codex": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.1-codex-max": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.1-codex-mini": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5-codex": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5-nano": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "claude-fable-5": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-opus-4-8": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-opus-4-7": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-opus-4-6": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-opus-4-5": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-opus-4-1": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-sonnet-4-6": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-sonnet-4-5": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-sonnet-4": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-haiku-4-5": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-3-5-haiku": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.7-max": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.7-plus": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.6-plus": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.5-plus": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "deepseek-v4-pro": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "deepseek-v4-flash": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "minimax-m2.7": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "minimax-m2.5": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "glm-5.1": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "glm-5": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "kimi-k2.5": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "kimi-k2.6": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "grok-build-0.1": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "big-pickle": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "mimo-v2.5-free": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "north-mini-code-free": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "nemotron-3-ultra-free": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "deepseek-v4-flash-free": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "gemini-3.5-flash": {adapter: adapterGeminiNative, path: "/v1/models/{model}", auth: authStyleGeminiGateway}, + "gemini-3.1-pro": {adapter: adapterGeminiNative, path: "/v1/models/{model}", auth: authStyleGeminiGateway}, + "gemini-3-flash": {adapter: adapterGeminiNative, path: "/v1/models/{model}", auth: authStyleGeminiGateway}, +} + +var goExactRoutes = map[string]routeSpec{ + "glm-5.1": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "glm-5": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "kimi-k2.7": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "kimi-k2.6": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "deepseek-v4-pro": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "deepseek-v4-flash": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "mimo-v2.5": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "mimo-v2.5-pro": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "minimax-m3": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "minimax-m2.7": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "minimax-m2.5": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.7-max": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.7-plus": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.6-plus": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, +} + +var zenClassRoutes = []classRoute{ + {prefix: "gpt-", spec: routeSpec{adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}}, + {prefix: "claude-", spec: routeSpec{adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}}, + {prefix: "qwen", spec: routeSpec{adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}}, + {prefix: "gemini-", spec: routeSpec{adapter: adapterGeminiNative, path: "/v1/models/{model}", auth: authStyleGeminiGateway}}, + {prefix: "deepseek-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "minimax-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "glm-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "kimi-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "grok-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "mimo-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, +} + +var goClassRoutes = []classRoute{ + {prefix: "gpt-", spec: routeSpec{adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}}, + {prefix: "claude-", spec: routeSpec{adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}}, + {prefix: "gemini-", spec: routeSpec{adapter: adapterGeminiNative, path: "/v1/models/{model}", auth: authStyleGeminiGateway}}, + {prefix: "qwen", spec: routeSpec{adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}}, + {prefix: "minimax-", spec: routeSpec{adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}}, + {prefix: "glm-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "kimi-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "deepseek-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "mimo-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, +} + +func resolveRoute(providerKey schemas.ModelProvider, modelID string) resolvedRoute { + normalizedModel := strings.TrimSpace(strings.ToLower(modelID)) + if spec, ok := resolveExactRoute(providerKey, normalizedModel); ok { + return buildResolvedRoute(spec, routeMatchExact, "", normalizedModel) + } + if spec, prefix, ok := resolveClassRoute(providerKey, normalizedModel); ok { + return buildResolvedRoute(spec, routeMatchClass, prefix, normalizedModel) + } + return buildResolvedRoute(defaultChatRoute(providerKey), routeMatchDefault, "", normalizedModel) +} + +func resolveExactRoute(providerKey schemas.ModelProvider, modelID string) (routeSpec, bool) { + switch providerKey { + case schemas.OpencodeZen: + spec, ok := zenExactRoutes[modelID] + return spec, ok + case schemas.OpencodeGo: + spec, ok := goExactRoutes[modelID] + return spec, ok + default: + return routeSpec{}, false + } +} + +func resolveClassRoute(providerKey schemas.ModelProvider, modelID string) (routeSpec, string, bool) { + var routes []classRoute + switch providerKey { + case schemas.OpencodeZen: + routes = zenClassRoutes + case schemas.OpencodeGo: + routes = goClassRoutes + default: + return routeSpec{}, "", false + } + + for _, route := range routes { + if strings.HasPrefix(modelID, route.prefix) { + return route.spec, route.prefix, true + } + } + + return routeSpec{}, "", false +} + +func defaultChatRoute(providerKey schemas.ModelProvider) routeSpec { + return routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer} +} + +func buildResolvedRoute(spec routeSpec, matchedBy routeMatchKind, classPrefix, modelID string) resolvedRoute { + path := spec.path + if strings.Contains(path, "{model}") { + path = strings.ReplaceAll(path, "{model}", modelID) + } + return resolvedRoute{ + Adapter: spec.adapter, + Path: path, + Auth: spec.auth, + MatchedBy: matchedBy, + ClassPrefix: classPrefix, + } +} diff --git a/core/providers/opencode/routing_test.go b/core/providers/opencode/routing_test.go new file mode 100644 index 00000000000..2556a2f9cd5 --- /dev/null +++ b/core/providers/opencode/routing_test.go @@ -0,0 +1,102 @@ +package opencode + +import ( + "testing" + + schemas "github.com/maximhq/bifrost/core/schemas" +) + +func TestResolveRoute(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + providerKey schemas.ModelProvider + modelID string + wantAdapter adapterKind + wantPath string + wantAuth authStyle + wantMatch routeMatchKind + wantClass string + }{ + { + name: "zen exact responses model", + providerKey: schemas.OpencodeZen, + modelID: "gpt-5-nano", + wantAdapter: adapterOpenAIResponses, + wantPath: "/v1/responses", + wantAuth: authStyleBearer, + wantMatch: routeMatchExact, + }, + { + name: "zen exact anthropic model", + providerKey: schemas.OpencodeZen, + modelID: "claude-haiku-4-5", + wantAdapter: adapterAnthropicMessages, + wantPath: "/v1/messages", + wantAuth: authStyleAnthropicKey, + wantMatch: routeMatchExact, + }, + { + name: "zen exact gemini model", + providerKey: schemas.OpencodeZen, + modelID: "gemini-3-flash", + wantAdapter: adapterGeminiNative, + wantPath: "/v1/models/gemini-3-flash", + wantAuth: authStyleGeminiGateway, + wantMatch: routeMatchExact, + }, + { + name: "go exact anthropic override beats class", + providerKey: schemas.OpencodeGo, + modelID: "minimax-m2.7", + wantAdapter: adapterAnthropicMessages, + wantPath: "/v1/messages", + wantAuth: authStyleAnthropicKey, + wantMatch: routeMatchExact, + }, + { + name: "go class fallback for future qwen", + providerKey: schemas.OpencodeGo, + modelID: "qwen4.1-max", + wantAdapter: adapterAnthropicMessages, + wantPath: "/v1/messages", + wantAuth: authStyleAnthropicKey, + wantMatch: routeMatchClass, + wantClass: "qwen", + }, + { + name: "zen default chat fallback", + providerKey: schemas.OpencodeZen, + modelID: "mystery-model-1", + wantAdapter: adapterOpenAIChat, + wantPath: "/v1/chat/completions", + wantAuth: authStyleBearer, + wantMatch: routeMatchDefault, + }, + } + + for _, tt := range tests { + tc := tt + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + got := resolveRoute(tc.providerKey, tc.modelID) + if got.Adapter != tc.wantAdapter { + t.Fatalf("adapter = %q, want %q", got.Adapter, tc.wantAdapter) + } + if got.Path != tc.wantPath { + t.Fatalf("path = %q, want %q", got.Path, tc.wantPath) + } + if got.Auth != tc.wantAuth { + t.Fatalf("auth = %q, want %q", got.Auth, tc.wantAuth) + } + if got.MatchedBy != tc.wantMatch { + t.Fatalf("matchedBy = %q, want %q", got.MatchedBy, tc.wantMatch) + } + if got.ClassPrefix != tc.wantClass { + t.Fatalf("classPrefix = %q, want %q", got.ClassPrefix, tc.wantClass) + } + }) + } +} diff --git a/core/providers/opencode/types.go b/core/providers/opencode/types.go new file mode 100644 index 00000000000..520c08145df --- /dev/null +++ b/core/providers/opencode/types.go @@ -0,0 +1,9 @@ +package opencode + +import schemas "github.com/maximhq/bifrost/core/schemas" + +type routeExecutionMetadata struct { + Route resolvedRoute + Provider schemas.ModelProvider + ModelID string +} diff --git a/core/providers/opencode/validation.go b/core/providers/opencode/validation.go new file mode 100644 index 00000000000..ce8eaa171e1 --- /dev/null +++ b/core/providers/opencode/validation.go @@ -0,0 +1,45 @@ +package opencode + +import ( + "fmt" + + providerUtils "github.com/maximhq/bifrost/core/providers/utils" + schemas "github.com/maximhq/bifrost/core/schemas" +) + +func validateChatRoute(route resolvedRoute, request *schemas.BifrostChatRequest) *schemas.BifrostError { + if request == nil { + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("chat request is nil")) + } + if request.Model == "" { + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("chat request model is empty")) + } + switch route.Adapter { + case adapterOpenAIChat, adapterAnthropicMessages, adapterGeminiNative: + return nil + case adapterOpenAIResponses: + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("chat completion is not supported for responses-routed model %q", request.Model)) + default: + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("unsupported chat route adapter %q", route.Adapter)) + } +} + +func validateResponsesRoute(route resolvedRoute, request *schemas.BifrostResponsesRequest) *schemas.BifrostError { + if request == nil { + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("responses request is nil")) + } + if request.Model == "" { + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("responses request model is empty")) + } + switch route.Adapter { + case adapterOpenAIResponses, adapterAnthropicMessages, adapterGeminiNative: + return nil + case adapterOpenAIChat: + if len(request.Input) == 0 { + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("responses request input is empty")) + } + return nil + default: + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("unsupported responses route adapter %q", route.Adapter)) + } +} diff --git a/core/schemas/bifrost.go b/core/schemas/bifrost.go index 57f64891d25..9da6fc9387c 100644 --- a/core/schemas/bifrost.go +++ b/core/schemas/bifrost.go @@ -44,6 +44,8 @@ const ( Vertex ModelProvider = "vertex" Mistral ModelProvider = "mistral" Ollama ModelProvider = "ollama" + OpencodeGo ModelProvider = "opencode-go" + OpencodeZen ModelProvider = "opencode-zen" Groq ModelProvider = "groq" SGL ModelProvider = "sgl" Parasail ModelProvider = "parasail" @@ -83,6 +85,8 @@ var StandardProviders = []ModelProvider{ Groq, Mistral, Ollama, + OpencodeGo, + OpencodeZen, OpenAI, Parasail, Perplexity, @@ -222,6 +226,7 @@ const ( BifrostContextKeyGovernanceCustomerNames BifrostContextKey = "bifrost-governance-customer-names" // []string (display names, aligned with customer-ids; set by enterprise governance plugin - DO NOT SET THIS MANUALLY) BifrostContextKeyGovernanceRoutingRuleID BifrostContextKey = "bifrost-governance-routing-rule-id" // string (to store the routing rule ID (set by bifrost governance plugin - DO NOT SET THIS MANUALLY)) BifrostContextKeyGovernanceRoutingRuleName BifrostContextKey = "bifrost-governance-routing-rule-name" // string (to store the routing rule name (set by bifrost governance plugin - DO NOT SET THIS MANUALLY)) + BifrostContextKeyRoutingPinnedAPIKeyID BifrostContextKey = "bifrost-routing-pinned-api-key-id" // string (provider key ID pinned by a matched routing rule target; resolved against the configured key pool during key selection and takes precedence over a caller-supplied pin (set by bifrost governance plugin - DO NOT SET THIS MANUALLY)) BifrostContextKeySelectedPromptName BifrostContextKey = "bifrost-selected-prompt-name" // string (display name of the selected prompt (set by prompts plugin - DO NOT SET THIS MANUALLY)) BifrostContextKeySelectedPromptVersion BifrostContextKey = "bifrost-selected-prompt-version" // string (numeric version as string, e.g. "3" (set by prompts plugin - DO NOT SET THIS MANUALLY)) BifrostContextKeySelectedPromptID BifrostContextKey = "bifrost-selected-prompt-id" // string (id of the selected prompt (set by prompts plugin - DO NOT SET THIS MANUALLY)) @@ -1555,8 +1560,8 @@ func (r *BifrostMCPResponse) PopulateExtraFields(mcpRequestType MCPRequestType, // BifrostResponseExtraFields contains additional fields in a response. type BifrostResponseExtraFields struct { - RequestType RequestType `json:"request_type"` - RoutingInfo RoutingInfo `json:"routing_info"` + RequestType RequestType `json:"request_type"` + RoutingInfo RoutingInfo `json:"routing_info"` // Deprecated: use RoutingInfo.Provider. Still populated for backward // compatibility; new consumers should read from RoutingInfo. Provider ModelProvider `json:"provider,omitempty"` @@ -1569,9 +1574,9 @@ type BifrostResponseExtraFields struct { // matched (i.e. RoutingInfo.ResolvedKeyAlias != nil), otherwise // RoutingInfo.Model. Still populated for backward compatibility; new // consumers should read from RoutingInfo. - ResolvedModelUsed string `json:"resolved_model_used,omitempty"` - Latency int64 `json:"latency"` // in milliseconds (for streaming responses this will be each chunk latency, and the last chunk latency will be the total latency) - ChunkIndex int `json:"chunk_index"` // used for streaming responses to identify the chunk index, will be 0 for non-streaming responses + ResolvedModelUsed string `json:"resolved_model_used,omitempty"` + Latency int64 `json:"latency"` // in milliseconds (for streaming responses this will be each chunk latency, and the last chunk latency will be the total latency) + ChunkIndex int `json:"chunk_index"` // used for streaming responses to identify the chunk index, will be 0 for non-streaming responses RawRequest interface{} `json:"raw_request,omitempty"` RawResponse interface{} `json:"raw_response,omitempty"` CacheDebug *BifrostCacheDebug `json:"cache_debug,omitempty"` diff --git a/docs/docs.json b/docs/docs.json index 20de36b458d..7da33fca503 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -143,6 +143,7 @@ "providers/supported-providers/mistral", "providers/supported-providers/nebius", "providers/supported-providers/ollama", + "providers/supported-providers/opencode", "providers/supported-providers/openai", "providers/supported-providers/openrouter", "providers/supported-providers/parasail", diff --git a/docs/providers/supported-providers/opencode.mdx b/docs/providers/supported-providers/opencode.mdx new file mode 100644 index 00000000000..c63ed27fbb2 --- /dev/null +++ b/docs/providers/supported-providers/opencode.mdx @@ -0,0 +1,339 @@ +--- +title: "OpenCode" +description: "OpenCode Zen and Go API gateway providers — OpenAI-compatible format, multi-model access, pay-as-you-go (Zen) and subscription (Go) gateways" +icon: "code" +--- + +## Overview + +OpenCode provides two AI gateway providers — **OpenCode Zen** (pay-as-you-go) and **OpenCode Go** (subscription-based). Both expose an OpenAI-compatible API that proxies to a curated set of models from multiple underlying providers (OpenAI, Anthropic, Google, DeepSeek, xAI, Kimi, Qwen, MiniMax, GLM, and more). + +Bifrost implements both providers through a shared codebase, differing only in default base URL and provider key. + +Key features: +- **Full OpenAI compatibility** — Standard Chat Completions `/v1/chat/completions` format +- **Multi-model access** — GPT, Claude, Gemini, DeepSeek, Grok, Kimi, Qwen, and more through a single API key +- **Curated quality** — Models are tested and verified by the OpenCode team for coding agent performance +- **Two gateways** — Zen (pay-as-you-go with per-token billing) and Go (subscription-based) +- **Streaming support** — Server-Sent Events with delta-based updates +- **Reasoning** — Chat models return `reasoning` content and `reasoning_tokens` in usage + +### Supported Operations + +| Operation | Non-Streaming | Streaming | Endpoint | +|-----------|---------------|-----------|----------| +| Chat Completions | ✅ | ✅ | `/v1/chat/completions` | +| Responses API | ✅ | ✅ | `/v1/chat/completions` (converted) | +| List Models | ✅ | - | `/v1/models` | +| Embeddings | ❌ | ❌ | - | +| Image Generation | ❌ | ❌ | - | +| Speech (TTS) | ❌ | ❌ | - | +| Transcriptions (STT) | ❌ | ❌ | - | +| Files | ❌ | ❌ | - | +| Batch | ❌ | ❌ | - | + + +**Unsupported Operations** (❌): Embeddings, Image Generation, Speech, Transcriptions, Files, and Batch are not supported by the OpenCode API. These return `UnsupportedOperationError`. + + +## Setup & Configuration + +### Choosing a Gateway + +| | OpenCode Zen | OpenCode Go | +|---|---|---| +| **Billing** | Pay-as-you-go (per token) | Subscription-based | +| **Base URL** | `https://opencode.ai/zen` | `https://opencode.ai/zen/go` | +| **Provider key** | `opencode-zen` | `opencode-go` | +| **API key** | From [opencode.ai/auth](https://opencode.ai/auth) | From OpenCode Go subscription | +| **Models** | Full catalog (~50 models) | Curated subset | + +Configure either provider (or both) in Bifrost: + + + + +1. Navigate to **Models** > **Model Providers**. Look for **OpenCode Zen** or **OpenCode Go** under **Configured Providers**. If missing, click **Add New Provider** and select the desired provider. +2. Click **Add Key** or edit an existing key. +3. Set a name for your key. +4. Paste your OpenCode API key directly or use an environment variable (for example, `env.OPENCODE_API_KEY`). +5. Set **Allowed Models** to **All Models** (default) or the specific model allowlist you want this key to serve. +6. Save the provider configuration. + + + + +```json +{ + "providers": { + "opencode-zen": { + "keys": [ + { + "name": "zen-key-1", + "value": "env.OPENCODE_API_KEY", + "models": ["*"], + "weight": 1.0 + } + ] + } + } +} +``` + +The default Base URL is `https://opencode.ai/zen`. Override via `network_config.base_url` if needed. + + + + +```json +{ + "providers": { + "opencode-go": { + "keys": [ + { + "name": "go-key-1", + "value": "env.OPENCODE_API_KEY", + "models": ["*"], + "weight": 1.0 + } + ] + } + } +} +``` + +The default Base URL is `https://opencode.ai/zen/go`. Override via `network_config.base_url` if needed. + + + +For OpenCode Zen: + +```go +case schemas.OpencodeZen: + return []schemas.Key{{ + Name: "zen-key-1", + Value: *schemas.NewEnvVar("env.OPENCODE_API_KEY"), + Models: []string{"*"}, + Weight: 1.0, + }}, nil +``` + +For OpenCode Go: + +```go +case schemas.OpencodeGo: + return []schemas.Key{{ + Name: "go-key-1", + Value: *schemas.NewEnvVar("env.OPENCODE_API_KEY"), + Models: []string{"*"}, + Weight: 1.0, + }}, nil +``` + + + + +--- + +# 1. Chat Completions + +OpenCode Zen and Go use standard OpenAI Chat Completions format. For full parameter reference and behavior, see [OpenAI Chat Completions](/providers/supported-providers/openai#1-chat-completions). + +## Request Parameters + +All standard OpenAI chat completion parameters are supported, including: +- `model` — Model ID (e.g., `deepseek-v4-flash`, `gpt-5.5`, `claude-sonnet-4-6`) +- `messages` — Standard message array with `role` and `content` +- `max_tokens` — Maximum output tokens +- `temperature`, `top_p`, `frequency_penalty`, `presence_penalty` +- `stream` — Enable SSE streaming +- `tools`, `tool_choice` — Function calling support +- `reasoning_effort` — Control reasoning depth (`"none"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"max"`) + + +**Provider-specific parameters**: Not all parameters are forwarded to the underlying model. Bifrost applies standard OpenAI normalization through the OpenAI-compatible handler. Model-specific features (e.g., thinking mode, prompt caching) depend on the underlying provider serving the model. + + +## Responses + +All chat models return standard OpenAI response format: + +```json +{ + "id": "chatcmpl-...", + "choices": [ + { + "index": 0, + "finish_reason": "stop", + "message": { + "role": "assistant", + "content": "Paris is the capital of France.", + "reasoning": "The user asked about the capital of France...", + "reasoning_details": [ + { + "index": 0, + "type": "reasoning.text", + "text": "The user asked about the capital of France..." + } + ] + } + } + ], + "usage": { + "prompt_tokens": 117, + "completion_tokens": 42, + "total_tokens": 159, + "prompt_tokens_details": { + "cached_tokens": 0 + }, + "completion_tokens_details": { + "reasoning_tokens": 39 + } + } +} +``` + +## Usage & Token Tracking + +OpenCode returns comprehensive token usage data: + +| Field | Description | +|-------|-------------| +| `usage.prompt_tokens` | Input tokens consumed | +| `usage.completion_tokens` | Output tokens generated | +| `usage.total_tokens` | Total tokens for the request | +| `usage.prompt_tokens_details.cached_tokens` | Tokens served from cache (if caching is active) | +| `usage.completion_tokens_details.reasoning_tokens` | Tokens consumed for reasoning/thinking | + +Cache tracking depends on the underlying model. Some providers report `prompt_cache_hit_tokens` and `prompt_cache_miss_tokens` fields. Bifrost maps these into the standard `cached_tokens` field for pricing calculations. + +## Error Format + +OpenCode uses a custom error format that differs from standard OpenAI errors: + +```json +{ + "type": "error", + "error": { + "type": "AuthError", + "message": "Invalid API key." + } +} +``` + +Bifrost's custom error converter parses this format transparently. Error types include: + +| Error Type | HTTP Status | Description | +|-----------|-------------|-------------| +| `AuthError` | 401 | Invalid or missing API key | +| `ModelError` | 400/404 | Requested model is not available | +| `insufficient_quota` | 429 | Quota exceeded | +| `server_error` | 5xx | Internal server error | +| `context_length_exceeded` | 400/413 | Input exceeds model context window | + +--- + +# 2. Responses API + +The Responses API is converted internally to Chat Completions: + +```go +// Responses request → Chat request conversion +request.ToChatRequest() → ChatCompletion → ToBifrostResponsesResponse() +``` + +Same parameter mapping and message conversion as Chat Completions. + +--- + +# 3. List Models + +OpenCode's model listing endpoint returns the available models for your gateway tier. Model IDs are prefixed with the provider key in Bifrost (e.g., `opencode-go/deepseek-v4-flash`). + +**Zen** typically exposes 50+ models across all supported providers. **Go** exposes a curated subset focused on coding agent performance. Available models are discovered automatically at startup via the `/v1/models` endpoint. + +--- + +## Pricing + +OpenCode Zen pricing is publicly available at [opencode.ai/docs/zen](https://opencode.ai/docs/zen). OpenCode Go pricing is subscription-based. Bifrost does not yet include OpenCode entries in the central [pricing datasheet](https://getbifrost.ai/datasheet). + +### Pricing Overrides + +Until central datasheet entries are available, use `pricing_overrides` in your configuration to set per-model rates. These take precedence over the datasheet: + +```json +{ + "providers": { + "opencode-zen": { + "keys": [{ "value": "env.OPENCODE_API_KEY", "models": ["*"] }] + } + }, + "pricing_overrides": [ + { + "id": "deepseek-v4-flash-zen", + "name": "DeepSeek V4 Flash on Zen", + "scope_kind": "provider", + "provider_id": "opencode-zen", + "match_type": "exact", + "pattern": "deepseek-v4-flash", + "request_types": ["chat_completion"], + "pricing_patch": "{\"input_cost_per_token\":1.4e-07,\"output_cost_per_token\":2.8e-07,\"cache_read_input_token_cost\":2.8e-08}" + }, + { + "id": "gpt-5-nano-zen", + "name": "GPT 5 Nano on Zen", + "scope_kind": "provider", + "provider_id": "opencode-zen", + "match_type": "exact", + "pattern": "gpt-5-nano", + "request_types": ["chat_completion"], + "pricing_patch": "{\"input_cost_per_token\":5.0e-08,\"output_cost_per_token\":4.0e-07}" + } + ] +} +``` + +For context window sizes and model capability metadata, point `pricing_url` and `model_parameters_url` to local JSON files with per-model entries. See the [Pricing & Model Parameters](/providers/supported-providers/overview#pricing-and-model-parameters) guide for details. + +--- + +## Unsupported Features + +| Feature | Reason | +|---------|--------| +| Embedding | Not offered by OpenCode API | +| Image Generation | Not offered by OpenCode API | +| Speech/TTS | Not offered by OpenCode API | +| Transcription/STT | Not offered by OpenCode API | +| Batch Operations | Not offered by OpenCode API | +| File Management | Not offered by OpenCode API | +| WebSocket Responses | Not offered by OpenCode API | + +--- + +## Caveats + + +**Severity**: Low +**Behavior**: OpenCode models do not yet have entries in the central Bifrost pricing datasheet. Cost tracking and context window awareness require local overrides. +**Resolution**: Use `pricing_overrides` in `config.json` (see [Pricing section](#pricing)) for per-model rates. Use `pricing_url` and `model_parameters_url` for context window sizes and capability metadata. + + + +**Severity**: Low +**Behavior**: OpenCode returns `{"type":"error","error":{"type":"...","message":"..."}}` instead of OpenAI's `{"error":{...}}` envelope. Bifrost's custom error converter handles this transparently. +**Impact**: No user impact — error messages are correctly extracted and presented. + + + +**Severity**: Low +**Behavior**: OpenCode Go exposes fewer models than Zen. Attempting to use a Zen-only model on Go (e.g., `big-pickle`) returns a model-not-found error. +**Resolution**: Check [opencode.ai/docs/zen](https://opencode.ai/docs/zen) for the current Go model list, or query `/v1/models` on your Go endpoint. + + + +**Severity**: Low +**Behavior**: Prompt caching support depends on the underlying provider serving the model. Some models report `cached_tokens` in usage; others (e.g., DeepSeek V4 Flash on Go) may not cache at all. +**Impact**: Cache-aware pricing only applies when cache tokens are reported. Verify model-specific cache behavior if you depend on cache cost savings. + diff --git a/plugins/compat/dropparams.go b/plugins/compat/dropparams.go index c87f7aa034d..7c18e69ff72 100644 --- a/plugins/compat/dropparams.go +++ b/plugins/compat/dropparams.go @@ -128,7 +128,12 @@ func dropUnsupportedParams(ctx *schemas.BifrostContext, req *schemas.BifrostRequ if req.ResponsesRequest != nil && req.ResponsesRequest.Params != nil { params := req.ResponsesRequest.Params - if params.MaxOutputTokens != nil && !isSupported["max_output_tokens"] { + // max_output_tokens is the Responses-API equivalent of chat max_tokens / max_completion_tokens. + // so if any of those token-cap spellings is supported, we let max_output_tokens pass through. + if params.MaxOutputTokens != nil && + !isSupported["max_output_tokens"] && + !isSupported["max_tokens"] && + !isSupported["max_completion_tokens"] { params.MaxOutputTokens = nil dropped = append(dropped, "max_output_tokens") } diff --git a/plugins/compat/dropparams_test.go b/plugins/compat/dropparams_test.go new file mode 100644 index 00000000000..748d1556e6f --- /dev/null +++ b/plugins/compat/dropparams_test.go @@ -0,0 +1,172 @@ +package compat + +import ( + "context" + "slices" + "testing" + "time" + + "github.com/maximhq/bifrost/core/schemas" +) + +func newTestContext() *schemas.BifrostContext { + return schemas.NewBifrostContext(context.Background(), time.Time{}) +} + +func newResponsesRequest(provider schemas.ModelProvider, model string, params *schemas.ResponsesParameters) *schemas.BifrostRequest { + return &schemas.BifrostRequest{ + RequestType: schemas.ResponsesRequest, + ResponsesRequest: &schemas.BifrostResponsesRequest{Provider: provider, Model: model, Params: params}, + } +} + +// TestDropUnsupportedParams_MaxOutputTokens verifies that the Responses-API +// max_output_tokens cap is preserved whenever the (chat-named) model parameter +// catalog authorizes the token cap under any spelling +// (max_output_tokens / max_tokens / max_completion_tokens), and dropped only +// when none of them is supported. +func TestDropUnsupportedParams_MaxOutputTokens(t *testing.T) { + tests := []struct { + name string + provider schemas.ModelProvider + model string + supported []string + wantPreserved bool + }{ + { + name: "openai gpt-4o-mini lists chat max_tokens only", + provider: schemas.OpenAI, + model: "gpt-4o-mini", + supported: []string{"temperature", "top_p", "max_tokens", "stop", "tools"}, + wantPreserved: true, + }, + { + name: "openai o4-mini lists max_completion_tokens", + provider: schemas.OpenAI, + model: "o4-mini", + supported: []string{"temperature", "max_completion_tokens"}, + wantPreserved: true, + }, + { + name: "model lists max_output_tokens explicitly", + provider: schemas.OpenAI, + model: "gpt-oss-120b", + supported: []string{"temperature", "max_output_tokens"}, + wantPreserved: true, + }, + { + name: "anthropic claude lists max_tokens", + provider: schemas.Anthropic, + model: "claude-sonnet-4", + supported: []string{"temperature", "max_tokens", "top_p"}, + wantPreserved: true, + }, + { + name: "vertex gemini lists max_tokens", + provider: schemas.Vertex, + model: "gemini-2.5-pro", + supported: []string{"temperature", "max_tokens"}, + wantPreserved: true, + }, + { + name: "no token cap supported drops max_output_tokens", + provider: schemas.OpenAI, + model: "no-token-cap-model", + supported: []string{"temperature", "top_p"}, + wantPreserved: false, + }, + { + name: "unknown model with empty catalog drops max_output_tokens", + provider: schemas.OpenAI, + model: "unknown-model", + supported: []string{}, + wantPreserved: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req := newResponsesRequest(tt.provider, tt.model, &schemas.ResponsesParameters{ + MaxOutputTokens: schemas.Ptr(16), + Temperature: schemas.Ptr(0.5), + }) + + dropped := dropUnsupportedParams(newTestContext(), req, tt.supported) + got := req.ResponsesRequest.Params.MaxOutputTokens + + if tt.wantPreserved { + if got == nil { + t.Fatalf("max_output_tokens = dropped, want preserved (supported=%v)", tt.supported) + } + if *got != 16 { + t.Errorf("max_output_tokens = %d, want 16", *got) + } + if slices.Contains(dropped, "max_output_tokens") { + t.Errorf("max_output_tokens reported in dropped=%v, want absent", dropped) + } + return + } + + if got != nil { + t.Fatalf("max_output_tokens = %d, want dropped (supported=%v)", *got, tt.supported) + } + if !slices.Contains(dropped, "max_output_tokens") { + t.Errorf("max_output_tokens not reported in dropped=%v, want present", dropped) + } + }) + } +} + +// TestDropUnsupportedParams_MaxOutputTokensSurgical verifies the fix is +// surgical: within one Responses request, max_output_tokens is preserved (chat +// token cap supported) while an unsupported sibling (top_p) is still dropped. +func TestDropUnsupportedParams_MaxOutputTokensSurgical(t *testing.T) { + req := newResponsesRequest(schemas.OpenAI, "gpt-4o-mini", &schemas.ResponsesParameters{ + MaxOutputTokens: schemas.Ptr(16), + TopP: schemas.Ptr(0.9), + Temperature: schemas.Ptr(0.5), + }) + + dropped := dropUnsupportedParams(newTestContext(), req, []string{"max_tokens", "temperature"}) + + p := req.ResponsesRequest.Params + if p.MaxOutputTokens == nil { + t.Errorf("max_output_tokens = dropped, want preserved") + } + if p.TopP != nil { + t.Errorf("top_p = preserved, want dropped") + } + if p.Temperature == nil { + t.Errorf("temperature = dropped, want preserved") + } + if !slices.Contains(dropped, "top_p") { + t.Errorf("top_p not reported in dropped=%v, want present", dropped) + } +} + +// TestDropUnsupportedParams_ChatMaxCompletionTokensUnchanged guards the +// pre-existing chat-branch behaviour that the Responses fix mirrors. +func TestDropUnsupportedParams_ChatMaxCompletionTokensUnchanged(t *testing.T) { + newChat := func() *schemas.BifrostRequest { + return &schemas.BifrostRequest{ + RequestType: schemas.ChatCompletionRequest, + ChatRequest: &schemas.BifrostChatRequest{ + Provider: schemas.OpenAI, + Model: "gpt-4o-mini", + Params: &schemas.ChatParameters{MaxCompletionTokens: schemas.Ptr(16)}, + }, + } + } + + keep := newChat() + dropUnsupportedParams(newTestContext(), keep, []string{"max_tokens"}) + if keep.ChatRequest.Params.MaxCompletionTokens == nil { + t.Errorf("max_completion_tokens = dropped, want preserved (max_tokens supported)") + } + + drop := newChat() + dropUnsupportedParams(newTestContext(), drop, []string{"temperature"}) + if drop.ChatRequest.Params.MaxCompletionTokens != nil { + t.Errorf("max_completion_tokens = preserved, want dropped (no token cap supported)") + } +} diff --git a/plugins/governance/main.go b/plugins/governance/main.go index c30a8a31858..ba0fbf9375b 100644 --- a/plugins/governance/main.go +++ b/plugins/governance/main.go @@ -774,9 +774,13 @@ func (p *GovernancePlugin) applyRoutingRules(ctx *schemas.BifrostContext, req *s req.SetFallbacks(resolvedFallbacks) } - // Pin specific API key by ID if the routing rule specifies one + // Pin specific API key by ID if the routing rule specifies one. This uses a dedicated, + // non-reserved context key (not BifrostContextKeyAPIKeyID): routing runs inside + // PreRequestHook, where core blocks writes to reserved key-selection keys, so a write to + // the caller-pin key would be silently dropped. Key selection reads this routing pin first + // and resolves it against the configured key pool. if decision.KeyID != "" { - ctx.SetValue(schemas.BifrostContextKeyAPIKeyID, decision.KeyID) + ctx.SetValue(schemas.BifrostContextKeyRoutingPinnedAPIKeyID, decision.KeyID) } p.logger.Debug("[Governance] Applied routing decision: provider=%s, model=%s, keyID=%s, fallbacks=%v", decision.Provider, decision.Model, decision.KeyID, decision.Fallbacks) diff --git a/plugins/governance/routing_test.go b/plugins/governance/routing_test.go index 231db1c861d..19b8b30a41d 100644 --- a/plugins/governance/routing_test.go +++ b/plugins/governance/routing_test.go @@ -334,13 +334,37 @@ func TestEvaluateRoutingRules_MultiTargetDeterministicWithPinnedKey(t *testing.T // KeyID must be propagated through the routing decision. assert.Equal(t, pinnedKeyID, decision.KeyID) - // Simulate the propagation step performed by governance/main.go so that we can - // assert the pinned key_id is visible in the BifrostContext. - if decision.KeyID != "" { - bgCtx.SetValue(schemas.BifrostContextKeyAPIKeyID, decision.KeyID) - } - ctxKeyID, _ := bgCtx.Value(schemas.BifrostContextKeyAPIKeyID).(string) - assert.Equal(t, pinnedKeyID, ctxKeyID) + // Now exercise the REAL propagation path through applyRoutingRules, under the same + // restricted-write block that core's RunPreRequestHooks installs around every + // PreRequestHook (core/bifrost.go: ctx.BlockRestrictedWrites + ctx.WithPluginScope). + // This is what production actually does — the routing pin lands on the dedicated, + // non-reserved BifrostContextKeyRoutingPinnedAPIKeyID (a write to the reserved + // BifrostContextKeyAPIKeyID would be silently dropped during this phase). Key selection + // (selectKeyFromProviderForModelWithPool) reads the pinned key back from this context. + plugin := &GovernancePlugin{ + logger: NewMockLogger(), + store: store, + engine: engine, + } + req := &schemas.BifrostRequest{ + RequestType: schemas.ChatCompletionRequest, + ChatRequest: &schemas.BifrostChatRequest{Provider: schemas.OpenAI, Model: "gpt-4o"}, + } + + root := schemas.NewBifrostContext(context.Background(), time.Now()) + root.BlockRestrictedWrites() + pluginName := PluginName + scoped := root.WithPluginScope(&pluginName) + + appliedDecision, err := plugin.applyRoutingRules(scoped, req, nil) + require.NoError(t, err) + require.NotNil(t, appliedDecision) + assert.Equal(t, pinnedKeyID, appliedDecision.KeyID) + + // The pinned key_id must be readable from the root context that key selection consults. + ctxKeyID, _ := root.Value(schemas.BifrostContextKeyRoutingPinnedAPIKeyID).(string) + assert.Equal(t, pinnedKeyID, ctxKeyID, + "routing-rule pinned key_id must reach BifrostContextKeyRoutingPinnedAPIKeyID that selectKeyFromProviderForModelWithPool reads") } // TestEvaluateRoutingRules_ScopePrecedence tests virtual_key scope takes precedence over global diff --git a/transports/config.schema.json b/transports/config.schema.json index e672bb4d0da..72c74b794b1 100644 --- a/transports/config.schema.json +++ b/transports/config.schema.json @@ -314,6 +314,12 @@ "gemini": { "$ref": "#/$defs/provider" }, + "opencode-go": { + "$ref": "#/$defs/provider" + }, + "opencode-zen": { + "$ref": "#/$defs/provider" + }, "openrouter": { "$ref": "#/$defs/provider" }, @@ -5370,6 +5376,8 @@ "mistral", "ollama", "groq", + "opencode-go", + "opencode-zen", "sgl", "parasail", "perplexity", diff --git a/ui/lib/constants/config.ts b/ui/lib/constants/config.ts index 8f507da1e79..6db7013bc2f 100644 --- a/ui/lib/constants/config.ts +++ b/ui/lib/constants/config.ts @@ -41,6 +41,8 @@ export const ModelPlaceholders = { elevenlabs: "e.g. eleven_multilingual_v2, eleven_turbo_v2", perplexity: "e.g. sonar-pro, sonar-deep-research", ollama: "e.g. llama3.1, llama2", + "opencode-go": "e.g. gpt-5.5, claude-sonnet-4-6", + "opencode-zen": "e.g. gpt-5.5, claude-sonnet-4-6", openai: "e.g. gpt-4, gpt-4o, gpt-4o-mini, gpt-3.5-turbo", vertex: "e.g. gemini-1.5-pro, text-bison, chat-bison", nebius: "e.g. openai/gpt-oss-120b, google/gemma-2-9b-it-fast, Qwen/Qwen2.5-VL-72B-Instruct", @@ -66,6 +68,8 @@ export const isKeyRequiredByProvider: Record = { parasail: true, elevenlabs: true, ollama: false, + "opencode-go": true, + "opencode-zen": true, openai: true, vertex: true, perplexity: true, diff --git a/ui/lib/constants/icons.tsx b/ui/lib/constants/icons.tsx index 4d7b076b3ff..e1afe629c3d 100644 --- a/ui/lib/constants/icons.tsx +++ b/ui/lib/constants/icons.tsx @@ -367,6 +367,44 @@ export const ProviderIcons = { ); }, + "opencode-go": ({ size = "md", className = "" }: IconProps) => { + const resolvedSize = resolveSize(size); + + return ( + + OpenCode + + + + ); + }, + + "opencode-zen": ({ size = "md", className = "" }: IconProps) => { + const resolvedSize = resolveSize(size); + + return ( + + OpenCode Zen + + + + ); + }, + sgl: ({ className = "" }: IconProps) => { return sgl; }, diff --git a/ui/lib/constants/logs.ts b/ui/lib/constants/logs.ts index 5b71ed97b75..7e02d72274f 100644 --- a/ui/lib/constants/logs.ts +++ b/ui/lib/constants/logs.ts @@ -10,6 +10,8 @@ export const KnownProvidersNames = [ "huggingface", "mistral", "ollama", + "opencode-go", + "opencode-zen", "openai", "openrouter", "parasail", @@ -108,6 +110,8 @@ export const ProviderLabels: Record = { vertex: "Vertex AI", mistral: "Mistral AI", ollama: "Ollama", + "opencode-go": "OpenCode Go", + "opencode-zen": "OpenCode Zen", groq: "Groq", parasail: "Parasail", elevenlabs: "Elevenlabs",