Documentation
¶
Overview ¶
Package proxy implements the dual-loop proxy orchestration core with channel retry, session leasing, and failure classification.
Package proxy implements the proxy orchestration core (). Dual loops: outer channel retry + inner endpoint iteration. Session lease with sticky bindings and concurrency limiting.
Index ¶
- Constants
- Variables
- func ApplyKeyProxyOverride(base *platform.ProxyConfig, keyProxyURL *string) *platform.ProxyConfig
- func BuildForcedChannelUnavailableMessage(forcedChannelID *int64) string
- func BuildUpstreamURL(siteURL, path string) string
- func CanRetryChannelSelection(retryCount int, maxRetries int, forcedChannelID *int64) bool
- func ContainsPathTraversal(path string) bool
- func DetectCliProfile(input types.DetectInput) types.DetectedProfile
- func EnsureRequestID(ctx context.Context, fallback string) (context.Context, string)
- func FirstByteTimeoutMs(proxyFirstByteTimeoutSec int) int64
- func GetProxyMaxChannelAttempts(cfgMaxChannelAttempts int) int
- func GetProxyMaxChannelRetries(maxChannelAttempts int) int
- func GetTesterForcedChannelID(headers map[string]string, clientIP string) *int64
- func IsLoopbackClientIP(ip string) bool
- func IsMetapiControlHeader(name string) bool
- func IsObservedFirstByteTimeoutError(err error) bool
- func IsResponsesOnlySite(platform, siteURL string, customHeaders map[string]string) bool
- func IsSessionScopedChannel(extraConfig *string, oauthProvider *string) bool
- func IsTrustedTesterRequest(headers map[string]string, clientIP string) bool
- func MaxBufferedResponseBodyBytes() int64
- func NewStreamTransport() *http.Transport
- func PathForEndpoint(endpoint UpstreamEndpoint) string
- func ReadBufferedResponseBody(r io.Reader) ([]byte, error)
- func RegisterDetectionProfile(p *types.CliProfileDefinition)
- func RegisterFallbackProfile(p *types.CliProfileDefinition)
- func RequestIDFromContext(ctx context.Context) string
- func ResponsesOnlyChatUnsupportedMessage(downstreamPath string) string
- func SelectProxyChannelForAttempt(ctx context.Context, router TokenRouterInterface, ...) (*routing.SelectedChannel, error)
- func ShouldAbortSameSiteEndpointFallback(status int, upstreamErrorText string) bool
- func ShouldDowngradeToNextEndpoint(status int, rawErrText string) bool
- func ShouldForceUpstreamStream(pref SiteProtocolPreference, upstreamPath string, isCompact bool) bool
- func ShouldRetryProxyRequest(status int, upstreamErrorText string) bool
- func WithRequestID(ctx context.Context, requestID string) context.Context
- type ChannelLoadSnapshot
- type ChannelSelectionInput
- type CliProfileCapabilities
- type CliProfileDefinition
- type CliProfileID
- type DetectInput
- type DetectedProfile
- type DownstreamClientContext
- type EndpointCandidateOptions
- type ExecutorDispatchInput
- type ExecutorDispatchResult
- type FailureResult
- type ProxyChannelCoordinator
- type ProxyLogEntry
- type RouteRefreshWorkflow
- type RuntimeExecutor
- func (e *RuntimeExecutor) Dispatch(ctx context.Context, input ExecutorDispatchInput) (*ExecutorDispatchResult, error)
- func (e *RuntimeExecutor) Do(req *http.Request) (*http.Response, error)
- func (e *RuntimeExecutor) DoStreamWithObservedFirstByte(ctx context.Context, req *http.Request, firstByteTimeoutMs int64) (*http.Response, error)
- func (e *RuntimeExecutor) DoWithObservedFirstByte(ctx context.Context, req *http.Request, firstByteTimeoutMs int64) (*http.Response, error)
- func (e *RuntimeExecutor) WithObservedFirstByte(ctx context.Context, input ExecutorDispatchInput, firstByteTimeoutMs int64) (*ExecutorDispatchResult, int64, error)
- type SiteConcurrencyLimiter
- type SiteProtocolPreference
- type SiteSlot
- type TokenRouterInterface
- type UpstreamEndpoint
- type UsageSummary
Constants ¶
const ( TesterRequestHeader = "x-metapi-tester-request" TesterForcedChannelHeader = "x-metapi-tester-forced-channel-id" )
Tester header constants.
const ( ProfileGeneric = types.ProfileGeneric ProfileCodex = types.ProfileCodex ProfileClaudeCode = types.ProfileClaudeCode ProfileGeminiCli = types.ProfileGeminiCli )
Variables ¶
var DefaultSiteConcurrencyLimiter = NewSiteConcurrencyLimiter()
DefaultSiteConcurrencyLimiter is the process-global site limiter used by the proxy data plane when UpstreamConfig does not inject a custom instance.
var ErrBufferedResponseBodyTooLarge = errors.New("upstream response body exceeded buffered limit")
var ErrObservedFirstByteTimeout = errors.New("first byte timeout")
ErrObservedFirstByteTimeout is returned by DoWithObservedFirstByte when the first-byte / response-header deadline fires before headers arrive.
Unit note: firstByteTimeoutMs is milliseconds. Config field PROXY_FIRST_BYTE_TIMEOUT_SEC is seconds; convert with FirstByteTimeoutMs.
Functions ¶
func ApplyKeyProxyOverride ¶
func ApplyKeyProxyOverride(base *platform.ProxyConfig, keyProxyURL *string) *platform.ProxyConfig
Empty / whitespace keyProxyURL returns base unchanged (inherit).
func BuildForcedChannelUnavailableMessage ¶
BuildForcedChannelUnavailableMessage builds a human-readable message for forced channel unavailability.
func BuildUpstreamURL ¶
BuildUpstreamURL constructs an upstream URL from a site URL and path.
func CanRetryChannelSelection ¶
CanRetryChannelSelection checks if a channel retry is possible. Returns false if a forced channel is set (no fallback), or if max retries reached.
func ContainsPathTraversal ¶ added in v0.16.7
ContainsPathTraversal reports whether a request path contains a ".." segment. Callers pass percent-decoded paths (net/http decodes the request target into r.URL.Path before handlers run, so %2e%2e arrives as ".."), which makes a plain segment scan sufficient for both literal and encoded traversal. Single-dot segments are not traversal on their own and are left alone so legitimate paths are never altered.
func DetectCliProfile ¶
func DetectCliProfile(input types.DetectInput) types.DetectedProfile
DetectCliProfile detects the CLI profile from the input. Returns the first matching profile, or generic as fallback.
func EnsureRequestID ¶
EnsureRequestID returns ctx carrying a non-empty request id when possible. Prefer the existing chi/Metapi id; only copies an explicit fallback when neither context source already has a value.
func FirstByteTimeoutMs ¶
FirstByteTimeoutMs converts ProxyFirstByteTimeoutSec (seconds) to the internal first-byte observation unit (milliseconds). Values <= 0 disable first-byte observation (returns 0).
Matches original TS: firstByteTimeoutMs = proxyFirstByteTimeoutSec * 1000.
func GetProxyMaxChannelAttempts ¶
GetProxyMaxChannelAttempts returns the configured max channel attempts (min 1).
func GetProxyMaxChannelRetries ¶
GetProxyMaxChannelRetries returns max channel retries (attempts - 1, min 0).
func GetTesterForcedChannelID ¶
GetTesterForcedChannelID extracts the forced channel ID from tester headers.
func IsLoopbackClientIP ¶
IsLoopbackClientIP checks if a client IP is loopback.
func IsMetapiControlHeader ¶
IsMetapiControlHeader reports whether a custom header is a Metapi control signal that must not be forwarded upstream (responses-only / stream preference marks).
func IsObservedFirstByteTimeoutError ¶
IsObservedFirstByteTimeoutError reports whether err is a first-byte timeout.
func IsResponsesOnlySite ¶
IsResponsesOnlySite reports whether the site is responses-only.
func IsSessionScopedChannel ¶
IsSessionScopedChannel checks if a channel uses session-scoped credentials.
func IsTrustedTesterRequest ¶
IsTrustedTesterRequest checks if the request is from a trusted tester (loopback + header).
func MaxBufferedResponseBodyBytes ¶
func MaxBufferedResponseBodyBytes() int64
MaxBufferedResponseBodyBytes returns the configured max non-streaming upstream response size in bytes from the startup-loaded config singleton. Falls back to DefaultProxyMaxBufferedResponseBytes when config is not yet loaded (e.g. tests that bypass TestMain) or when the operator left the value at zero/negative (Load already clamps, but GetSafe guards anyway). Reading a struct field per request is materially cheaper than re-parsing os.Getenv + strconv.ParseInt on every proxied request — this function is on the hot path called from upstream.go, upstream_stream.go, executor.go.
func NewStreamTransport ¶ added in v0.16.18
NewStreamTransport returns the shared baseline transport with a ResponseHeaderTimeout bound for the SSE header phase. Used by the executor's stream client and by fallback stream clients that must not cap a flowing stream's total duration while still bounding the header wait. Dial/TLS/idle bounds and the idle pool come from the internal/httpclient baseline instead of an unconfigured default transport.
func PathForEndpoint ¶
func PathForEndpoint(endpoint UpstreamEndpoint) string
PathForEndpoint returns the canonical upstream path for a known endpoint type. Unknown endpoints return "".
func RegisterDetectionProfile ¶
func RegisterDetectionProfile(p *types.CliProfileDefinition)
RegisterDetectionProfile adds a profile to the detection chain. Profiles must be registered in priority order: claude_code -> codex -> gemini_cli.
func RegisterFallbackProfile ¶
func RegisterFallbackProfile(p *types.CliProfileDefinition)
RegisterFallbackProfile registers a profile for map lookup only (not in detection chain).
func RequestIDFromContext ¶
RequestIDFromContext returns the Metapi request/trace id when present. Falls back to chi's middleware.GetReqID so ingress middleware and attempt loops share the same correlation value without extra wiring.
func ResponsesOnlyChatUnsupportedMessage ¶
ResponsesOnlyChatUnsupportedMessage is the clear client error when a chat/completions (or messages) client hits a responses-only site and transform is not available. Used when DISABLE_CROSS_PROTOCOL_FALLBACK is true and body cannot be rewritten.
func SelectProxyChannelForAttempt ¶
func SelectProxyChannelForAttempt( ctx context.Context, router TokenRouterInterface, coord *ProxyChannelCoordinator, routeRefresher RouteRefreshWorkflow, input ChannelSelectionInput, ) (*routing.SelectedChannel, error)
SelectProxyChannelForAttempt selects a channel for the current attempt. Paths: tester forced -> normal selection (first attempt may retry selection once when the store returned no channels).
routeRefresher is retained in the signature for handler wiring, but is never populated in production (RouteRefreshWorkflow has no wired implementer), so no refresh step runs here.
func ShouldAbortSameSiteEndpointFallback ¶
ShouldAbortSameSiteEndpointFallback decides whether to abort endpoint fallback within the same site. Used by the endpoint flow to stop trying other endpoints when the failure looks systemic (rate limit, gateway error, etc.).
Scope note : this aborts *endpoint-list* fallback on one selected channel/site attempt — it does NOT mark sibling channels failed and does NOT expand request-local excludeChannelIDs. Channel failover remains channel-scoped via SelectNextChannel / conductor exclude lists.
func ShouldDowngradeToNextEndpoint ¶
ShouldDowngradeToNextEndpoint reports whether an upstream error indicates the current protocol/path is wrong and a different endpoint candidate should be tried.
func ShouldForceUpstreamStream ¶
func ShouldForceUpstreamStream(pref SiteProtocolPreference, upstreamPath string, isCompact bool) bool
Forces stream when: - site PreferStream / ResponsesOnly and path is responses (non-compact) - platform-level ShouldForceResponsesUpstreamStream (codex/sub2api) — callers may combine with transform/openai/responses helpers
func ShouldRetryProxyRequest ¶
ShouldRetryProxyRequest classifies an upstream failure for channel-level retry decisions. Returns true if the proxy should retry with a different channel or the same channel.
Decision matrix:
- Status inside the operator-tunable retry ranges: retryable. The default ranges (routing.DefaultRetryStatusRangesSpec) reproduce exactly the historical hardcoded verdicts: >= 500, 408/409/425/429, and 401/403 (auth faults an OAuth token refresh may resolve). Operators can narrow or widen the set at runtime (proxy_retry_status_ranges setting).
- Error text matches model-unsupported patterns: retryable (try another channel)
- Error text matches non-retryable request patterns: non-retryable (bad request)
- Error text matches retryable channel-local patterns: retryable
- 400/404/422: non-retryable (unless error text overrides)
- Other: non-retryable
Types ¶
type ChannelLoadSnapshot ¶
type ChannelLoadSnapshot struct {
ChannelID int64
SessionScoped bool
ConcurrencyLimit int
ActiveLeaseCount int
WaitingCount int
LoadRatio float64
Saturated bool
}
ChannelLoadSnapshot is a snapshot of channel load.
type ChannelSelectionInput ¶
type ChannelSelectionInput struct {
RequestedModel string
DownstreamPolicy routing.DownstreamRoutingPolicy
// ExcludeChannelIDs is a request-local list of already-tried channel IDs.
// Scope is channel-only: callers must not expand this to all channels of a
// site. Same-site siblings stay eligible unless routing policy (cooldown /
// site breaker / credential-scoped usage-limit) independently filters them.
//
ExcludeChannelIDs []int64
RetryCount int
ForcedChannelID *int64
}
ChannelSelectionInput is the input for SelectProxyChannelForAttempt.
type CliProfileCapabilities ¶
type CliProfileCapabilities = types.CliProfileCapabilities
Re-export types for convenience so callers don't need to import proxy/types.
type CliProfileDefinition ¶
type CliProfileDefinition = types.CliProfileDefinition
Re-export types for convenience so callers don't need to import proxy/types.
type CliProfileID ¶
type CliProfileID = types.CliProfileID
Re-export types for convenience so callers don't need to import proxy/types.
type DetectInput ¶
type DetectInput = types.DetectInput
Re-export types for convenience so callers don't need to import proxy/types.
type DetectedProfile ¶
type DetectedProfile = types.DetectedProfile
Re-export types for convenience so callers don't need to import proxy/types.
type DownstreamClientContext ¶
type DownstreamClientContext struct {
ClientKind string
ClientAppID string
ClientAppName string
ClientConfidence string
SessionID string
TraceHint string
Capabilities CliProfileCapabilities
}
DownstreamClientContext holds the detected downstream client context.
func DetectClientContext ¶
func DetectClientContext(downstreamPath string, headers map[string]string, body any) DownstreamClientContext
DetectClientContext detects the downstream client context from request metadata.
type EndpointCandidateOptions ¶
type EndpointCandidateOptions struct {
// DisableCrossProtocolFallback limits candidates to the primary endpoint only.
// When ResponsesOnly is set, primary is forced to responses regardless of
// downstream path (chat/messages clients are rewritten to responses).
DisableCrossProtocolFallback bool
// Preference is the site protocol preference (responses-only / stream).
Preference SiteProtocolPreference
}
EndpointCandidateOptions controls multi-protocol candidate ordering.
type ExecutorDispatchInput ¶
type ExecutorDispatchInput struct {
SiteURL string
TargetURL string
Method string
Headers map[string]string
Body []byte
Signal <-chan struct{}
}
ExecutorDispatchInput is the input for dispatching an HTTP request.
type ExecutorDispatchResult ¶
type ExecutorDispatchResult struct {
Status int
Headers map[string]string
Body []byte
BodyReader io.ReadCloser
}
ExecutorDispatchResult is the result of dispatching an HTTP request.
type FailureResult ¶
FailureResult is a content-based failure detection result.
func DetectProxyFailure ¶
func DetectProxyFailure(rawText string, usage *UsageSummary) *FailureResult
DetectProxyFailure detects proxy failures from response content. This is PURELY content-based — it does NOT look at HTTP status codes. Called AFTER a non-stream response body is received.
Detection: 1. Keyword matching: if config.ProxyErrorKeywords is non-empty, checks case-insensitive 2. Empty content check: if ProxyEmptyContentFailEnabled and no completion tokens + no output
type ProxyChannelCoordinator ¶
type ProxyChannelCoordinator struct{}
ProxyChannelCoordinator tracks per-channel session load for routing.
Sticky-session leases (AcquireChannelLease / BindStickyChannel, the waiter queue, and lease keepalive/expiry goroutines) are DEFERRED: no caller in the proxy acquires leases today, so that machinery was removed in chore/rm-dead-proxy-routing and can be reintroduced from git history when sticky sessions are wired up. Until then every load snapshot reports zero active leases and zero waiters.
func NewProxyChannelCoordinator ¶
func NewProxyChannelCoordinator() *ProxyChannelCoordinator
NewProxyChannelCoordinator creates a new coordinator. The session-channel concurrency limit is read from the runtime-settings snapshot on every acquire so a settings change hot-applies without a restart.
func (*ProxyChannelCoordinator) GetActiveChannelIDs ¶
func (c *ProxyChannelCoordinator) GetActiveChannelIDs() []int64
GetActiveChannelIDs returns channel IDs with active leases. Leases are deferred (see ProxyChannelCoordinator), so this is always empty.
func (*ProxyChannelCoordinator) GetChannelLoadSnapshot ¶
func (c *ProxyChannelCoordinator) GetChannelLoadSnapshot( channelID int64, extraConfig *string, oauthProvider *string, ) ChannelLoadSnapshot
GetChannelLoadSnapshot returns a snapshot of a channel's load. Leases are deferred (see ProxyChannelCoordinator), so active and waiting counts are always zero.
func (*ProxyChannelCoordinator) Reset ¶
func (c *ProxyChannelCoordinator) Reset()
Reset resets all state (for testing).
type ProxyLogEntry ¶
type ProxyLogEntry struct {
RouteID *int64
ChannelID *int64
AccountID *int64
DownstreamAPIKeyID *int64
ModelRequested string
ModelActual *string
Status string
HTTPStatus int
IsStream *bool
FirstByteLatencyMs *int64
LatencyMs int64
PromptTokens *int64
CompletionTokens *int64
TotalTokens *int64
EstimatedCost float64
BillingDetails any
ClientFamily string
ClientAppID string
ClientAppName string
ClientConfidence string
ErrorMessage *string
RetryCount int
// RequestID correlates multi-channel retry/failover attempts for one client call.
// Same value as chi X-Request-Id / middleware.GetReqID for the ingress request.
RequestID string
UpstreamPath *string
UsageSource string
}
ProxyLogEntry is a single proxy log row.
type RouteRefreshWorkflow ¶
RouteRefreshWorkflow is the interface for route refresh.
type RuntimeExecutor ¶
type RuntimeExecutor struct {
// contains filtered or unexported fields
}
RuntimeExecutor dispatches upstream HTTP requests.
func NewRuntimeExecutor ¶
func NewRuntimeExecutor(requestTimeout time.Duration) *RuntimeExecutor
NewRuntimeExecutor creates a new RuntimeExecutor with the given timeout. The client refuses cross-origin redirects (and https→http) to block SSRF via 302 to a different host / private / metadata endpoint.
func (*RuntimeExecutor) Dispatch ¶
func (e *RuntimeExecutor) Dispatch(ctx context.Context, input ExecutorDispatchInput) (*ExecutorDispatchResult, error)
Dispatch sends an HTTP request to the upstream.
func (*RuntimeExecutor) Do ¶
Do sends an HTTP request through the executor's client, returning the raw *http.Response. Unlike Dispatch, this does NOT read the body — callers (especially streaming handlers) must close resp.Body themselves.
func (*RuntimeExecutor) DoStreamWithObservedFirstByte ¶ added in v0.16.18
func (e *RuntimeExecutor) DoStreamWithObservedFirstByte( ctx context.Context, req *http.Request, firstByteTimeoutMs int64, ) (*http.Response, error)
DoStreamWithObservedFirstByte is the SSE variant of DoWithObservedFirstByte: identical first-byte observation, but dispatched through the stream client, which carries no whole-request timeout. A healthy stream may therefore keep running while chunks flow; a stalled stream is aborted by the relay's idle guard (PROXY_STREAM_IDLE_TIMEOUT_SEC) instead of the blunt whole-request cap that would also kill long-but-healthy streams.
func (*RuntimeExecutor) DoWithObservedFirstByte ¶
func (e *RuntimeExecutor) DoWithObservedFirstByte( ctx context.Context, req *http.Request, firstByteTimeoutMs int64, ) (*http.Response, error)
DoWithObservedFirstByte sends req and observes first-byte (response header) latency. Unlike WithObservedFirstByte it does NOT buffer the body, so callers (including streaming handlers) must close resp.Body themselves.
When firstByteTimeoutMs > 0 and the deadline fires before headers arrive, it returns (nil, ErrObservedFirstByteTimeout). firstByteTimeoutMs is milliseconds (see FirstByteTimeoutMs).
After headers arrive the first-byte timer is stopped so the body stream is not cancelled by the observation deadline.
func (*RuntimeExecutor) WithObservedFirstByte ¶
func (e *RuntimeExecutor) WithObservedFirstByte( ctx context.Context, input ExecutorDispatchInput, firstByteTimeoutMs int64, ) (*ExecutorDispatchResult, int64, error)
WithObservedFirstByte dispatches a request and observes the first-byte latency. Returns a special result with status=0 if the first-byte timeout fires. firstByteTimeoutMs is milliseconds (see FirstByteTimeoutMs).
type SiteConcurrencyLimiter ¶
type SiteConcurrencyLimiter struct {
// contains filtered or unexported fields
}
SiteConcurrencyLimiter caps concurrent upstream dispatches per site. It is orthogonal to ProxyChannelCoordinator channel leases: a request may hold both a site slot and a channel lease independently.
Semantics (sites.max_concurrency / Site.MaxConcurrency): - limit <= 0 → unlimited (always acquire; no tracking) - limit > 0 → at most that many concurrent held slots per siteID
On saturation callers must skip to the next channel/site and must NOT mark the channel expired or record a routing failure cascade.
func NewSiteConcurrencyLimiter ¶
func NewSiteConcurrencyLimiter() *SiteConcurrencyLimiter
NewSiteConcurrencyLimiter creates an empty site-scoped limiter.
func (*SiteConcurrencyLimiter) ActiveCount ¶
func (l *SiteConcurrencyLimiter) ActiveCount(siteID int64) int
ActiveCount returns the number of currently held slots for siteID. Unlimited / unknown sites report 0.
func (*SiteConcurrencyLimiter) TryAcquire ¶
func (l *SiteConcurrencyLimiter) TryAcquire(siteID int64, maxConcurrency int64) (*SiteSlot, bool)
TryAcquire attempts to take one concurrency slot for siteID.
Returns (slot, true) when the call may proceed. slot is never nil on success; for unlimited sites the slot is a no-op (Release is still safe). Returns (nil, false) when the site is saturated — caller should skip this site/channel without recording failure.
type SiteProtocolPreference ¶
type SiteProtocolPreference = profiles.SiteProtocolPreference
SiteProtocolPreference re-exports profiles.SiteProtocolPreference for callers that already depend on proxy (handler layer).
func DetectSiteProtocolPreference ¶
func DetectSiteProtocolPreference(platform, siteURL string, customHeaders map[string]string) SiteProtocolPreference
DetectSiteProtocolPreference resolves responses-only / stream preference for a site.
func DetectSiteProtocolPreferenceFromSite ¶
func DetectSiteProtocolPreferenceFromSite(platform, siteURL string, customHeadersJSON *string) SiteProtocolPreference
DetectSiteProtocolPreferenceFromSite is a convenience for store.Site-like fields.
type SiteSlot ¶
type SiteSlot struct {
// contains filtered or unexported fields
}
SiteSlot is a held (or no-op) site concurrency permit. Always call Release exactly once when the upstream attempt finishes.
type TokenRouterInterface ¶
type TokenRouterInterface interface {
SelectChannel(ctx context.Context, requestedModel string, policy routing.DownstreamRoutingPolicy) (*routing.SelectedChannel, error)
SelectNextChannel(ctx context.Context, requestedModel string, excludeChannelIDs []int64, policy routing.DownstreamRoutingPolicy) (*routing.SelectedChannel, error)
SelectPreferredChannel(ctx context.Context, requestedModel string, preferredChannelID int64, policy routing.DownstreamRoutingPolicy, excludeChannelIDs []int64) (*routing.SelectedChannel, error)
RecordSuccess(ctx context.Context, channelID int64, latencyMs float64, cost float64, modelName *string, actualAccountID *int64) error
RecordFailure(ctx context.Context, channelID int64, failureCtx routing.SiteRuntimeFailureContext, actualAccountID *int64) error
}
TokenRouterInterface is the interface for channel selection. This allows the proxy layer to depend on routing without circular imports.
type UpstreamEndpoint ¶
type UpstreamEndpoint string
UpstreamEndpoint represents an upstream API endpoint type.
const ( EndpointChat UpstreamEndpoint = "chat" // /v1/chat/completions EndpointMessages UpstreamEndpoint = "messages" // /v1/messages (Anthropic) EndpointResponses UpstreamEndpoint = "responses" // /v1/responses (Codex) )
func EndpointFromPath ¶
func EndpointFromPath(path string) (UpstreamEndpoint, bool)
EndpointFromPath maps a downstream path to a known chat-family endpoint. Non chat-family paths return ("", false).
func ResolveEndpointCandidates ¶
func ResolveEndpointCandidates(downstreamPath string, disableCrossProtocolFallback bool) []UpstreamEndpoint
For responses-only sites, prefer ResolveEndpointCandidatesWithOptions.
func ResolveEndpointCandidatesWithOptions ¶
func ResolveEndpointCandidatesWithOptions(downstreamPath string, opts EndpointCandidateOptions) []UpstreamEndpoint
Policy: - responses-only site → only EndpointResponses (even if client called chat/messages) - prefer-responses → responses first, then remaining chat-family endpoints - disableCrossProtocolFallback → single primary (responses when responses-only) - non chat-family path → nil (caller uses original path)
type UsageSummary ¶
UsageSummary is a lightweight usage summary for failure detection.