mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-12-05 00:47:15 +08:00
- Cross-tenant session/LCP affinity across model switches, cascade/parent subagent alias extraction and RESP forwarding, automatic subagent custom_agent requestType promotion, credential-scoped reasoning replay isolation, foreign thoughtSignature scrubbing on *ojson.Doc, 14-key payload order, and 270s prompt-cache keepalive guards. - Shared Google RPC array and HTTP 200 in-band error unwrapping/classification, pre-first-byte same-auth micro-retries for 14 TPU transient errors, expanded quota/billing/policy classification with strict HTTP 403/gRPC 7 TOS validation, and read-only SafetySignals logging. - 32-leg continuationToken stream resumption, dynamic deprecatedModelIds rerouting, Orchestrator model synthesis, ModelDetails capability persistence, authenticated rewriteUri grounding redirects, FULL_ELIGIBILITY_CHECK, ClaimAICodeBankedQuotaReset, and validated no-redirect dynamic endpointUrl onboarding. - PKCE S256 OAuth login, downscoped auth/aicode token minting with bounded cache, mutually verified Home RESP aicode-token handoff, grant/digest refresh continuity verification, flat v1alpha *ojson.Doc codec with GOOGLE_ONE_AI fallback experience, businessaicode parent support, and unbroken FinalizePayloadDoc semantic barrier across v1alpha, v1internal, 403 fallback, continuation, and countTokens. - Full v1alpha control-plane integration (fetchConfig with 8-group proto agySurfaceConfig, typed Mendel flags with conflict rejection, fetchLicenses, prod/preprod consistency, and 2 MiB-guarded KV snapshot publication), auto-mode Mendel routing, real-time v1alpha:fetchQuotaStatus credits refresh with read-only dark-launch shadow comparison and exact int64 comparison, and unified pure-Go Hub 2.35.2 UA + HTTP/1.1-only no-ALPN transport.
222 lines
8.1 KiB
Go
222 lines
8.1 KiB
Go
package helps
|
|
|
|
import (
|
|
"context"
|
|
"reflect"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
|
|
"github.com/MoeForge/moego/ojson"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
|
|
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
|
|
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
|
|
)
|
|
|
|
// PayloadFinalizer applies user rules to a fully prepared business payload.
|
|
// Each rebuilt attempt must start from the unconfigured body, not a previous result.
|
|
type PayloadFinalizer func([]byte) []byte
|
|
|
|
var (
|
|
payloadDocProbes sync.Map
|
|
builtinFinalizerCodePtr atomic.Uintptr
|
|
)
|
|
|
|
func payloadFinalizerKeyPtr(f PayloadFinalizer) uintptr {
|
|
if f == nil {
|
|
return 0
|
|
}
|
|
return reflect.ValueOf(f).Pointer()
|
|
}
|
|
|
|
type payloadDocProbe struct {
|
|
doc *ojson.Doc
|
|
root string
|
|
overriddenPaths []string
|
|
filteredPaths []string
|
|
trackRules bool
|
|
}
|
|
|
|
// FinalizeDoc applies the finalizer to doc in place without probing custom wrappers.
|
|
func (f PayloadFinalizer) FinalizeDoc(doc *ojson.Doc) {
|
|
_, _, _ = f.finalizeDocTracked(doc, false)
|
|
}
|
|
|
|
func (f PayloadFinalizer) finalizeDocTracked(doc *ojson.Doc, trackRules bool) (string, []string, []string) {
|
|
if f == nil || doc == nil {
|
|
return "", nil, nil
|
|
}
|
|
if ptr := payloadFinalizerKeyPtr(f); ptr != 0 && ptr == builtinFinalizerCodePtr.Load() {
|
|
var probeBuf [1]byte
|
|
key := &probeBuf[0]
|
|
probe := &payloadDocProbe{doc: doc, trackRules: trackRules}
|
|
payloadDocProbes.Store(key, probe)
|
|
_ = f(probeBuf[:0])
|
|
if _, remaining := payloadDocProbes.LoadAndDelete(key); !remaining {
|
|
return probe.root, probe.overriddenPaths, probe.filteredPaths
|
|
}
|
|
}
|
|
updated := f(doc.Bytes())
|
|
*doc = *ojson.NewDoc(updated)
|
|
return "", nil, nil
|
|
}
|
|
|
|
// NewPayloadFinalizer snapshots matching context before built-in request mutations.
|
|
func NewPayloadFinalizer(cfg *config.Config, executor, model, protocol, root string, original []byte, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, auths ...*cliproxyauth.Auth) PayloadFinalizer {
|
|
var auth *cliproxyauth.Auth
|
|
if len(auths) > 0 {
|
|
auth = auths[0]
|
|
}
|
|
return newPayloadFinalizer(cfg, executor, model, protocol, root, original, req, opts, auth, nil)
|
|
}
|
|
|
|
// NewPayloadFinalizerWithSourceModels includes intermediate resolved model IDs
|
|
// when a provider makes a second model selection after alias resolution.
|
|
func NewPayloadFinalizerWithSourceModels(cfg *config.Config, executor, model, protocol, root string, original []byte, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, sourceModels ...string) PayloadFinalizer {
|
|
return newPayloadFinalizer(cfg, executor, model, protocol, root, original, req, opts, nil, append([]string(nil), sourceModels...))
|
|
}
|
|
|
|
func newPayloadFinalizer(cfg *config.Config, executor, model, protocol, root string, original []byte, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, auth *cliproxyauth.Auth, sourceModels []string) PayloadFinalizer {
|
|
requestedModel := PayloadRequestedModel(opts, req.Model)
|
|
requestPath := PayloadRequestPath(opts)
|
|
headers := opts.Headers.Clone()
|
|
source := append([]byte(nil), original...)
|
|
var formatCallback func(string)
|
|
if opts.Metadata != nil {
|
|
formatCallback, _ = opts.Metadata[cliproxyexecutor.FinalizedResponseFormatCallbackMetadataKey].(func(string))
|
|
}
|
|
fn := PayloadFinalizer(func(body []byte) []byte {
|
|
if len(body) == 0 && cap(body) == 1 {
|
|
key := &body[:1][0]
|
|
if v, ok := payloadDocProbes.LoadAndDelete(key); ok {
|
|
if probe, okProbe := v.(*payloadDocProbe); okProbe && probe != nil && probe.doc != nil {
|
|
probe.root = root
|
|
var hooks payloadRuleHooks
|
|
if probe.trackRules {
|
|
hooks.onOverride = func(overriddenPath string) {
|
|
probe.overriddenPaths = append(probe.overriddenPaths, overriddenPath)
|
|
}
|
|
hooks.onFilter = func(filteredPath string) {
|
|
probe.filteredPaths = append(probe.filteredPaths, filteredPath)
|
|
}
|
|
}
|
|
applyPayloadConfigWithTrackedPathsForExecutorAndAuthDocWithHooks(cfg, executor, model, protocol, opts.SourceFormat.String(), root, probe.doc, source, requestedModel, requestPath, headers, auth, sourceModels, hooks)
|
|
if formatCallback != nil {
|
|
formatCallback(strings.Clone(strings.TrimSpace(probe.doc.Get(buildPayloadPath(root, "response_format")).String())))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
doc := ojson.NewDoc(body)
|
|
_, mutated := applyPayloadConfigWithTrackedPathsForExecutorAndAuthDoc(cfg, executor, model, protocol, opts.SourceFormat.String(), root, doc, source, requestedModel, requestPath, headers, auth, sourceModels)
|
|
out := body
|
|
if mutated {
|
|
out = doc.Bytes()
|
|
}
|
|
if formatCallback != nil {
|
|
formatCallback(strings.Clone(strings.TrimSpace(ojson.GetBytesNoCopy(out, buildPayloadPath(root, "response_format")).String())))
|
|
}
|
|
return out
|
|
})
|
|
builtinFinalizerCodePtr.Store(payloadFinalizerKeyPtr(fn))
|
|
return fn
|
|
}
|
|
|
|
type payloadFinalizerKey struct{}
|
|
|
|
type payloadFinalizerState struct {
|
|
finalize PayloadFinalizer
|
|
mu sync.RWMutex
|
|
root string
|
|
overriddenPaths []string
|
|
filteredPaths []string
|
|
}
|
|
|
|
// WithPayloadFinalizer carries the final barrier through shared request builders.
|
|
func WithPayloadFinalizer(ctx context.Context, finalize PayloadFinalizer) context.Context {
|
|
return context.WithValue(ctx, payloadFinalizerKey{}, &payloadFinalizerState{finalize: finalize})
|
|
}
|
|
|
|
// FinalizePayload runs immediately before serialization or transport framing.
|
|
func FinalizePayload(ctx context.Context, body []byte) []byte {
|
|
if ctx == nil {
|
|
return body
|
|
}
|
|
if state, ok := ctx.Value(payloadFinalizerKey{}).(*payloadFinalizerState); ok && state != nil && state.finalize != nil {
|
|
return state.finalize(body)
|
|
}
|
|
return body
|
|
}
|
|
|
|
// FinalizePayloadDoc runs immediately before serialization or transport framing,
|
|
// mutating doc in place and recording which payload paths matched Payload.Override
|
|
// and Payload.Filter rules during this single rule-engine pass.
|
|
func FinalizePayloadDoc(ctx context.Context, doc *ojson.Doc) {
|
|
if doc == nil || ctx == nil {
|
|
return
|
|
}
|
|
if state, ok := ctx.Value(payloadFinalizerKey{}).(*payloadFinalizerState); ok && state != nil && state.finalize != nil {
|
|
root, overriddenPaths, filteredPaths := state.finalize.finalizeDocTracked(doc, true)
|
|
state.mu.Lock()
|
|
state.root = root
|
|
state.overriddenPaths = overriddenPaths
|
|
state.filteredPaths = filteredPaths
|
|
state.mu.Unlock()
|
|
}
|
|
}
|
|
|
|
func payloadFinalizerPathsMatch(ctx context.Context, path string, selectOverride bool, includeAncestors bool) bool {
|
|
if ctx == nil {
|
|
return false
|
|
}
|
|
path = strings.TrimSpace(path)
|
|
if path == "" {
|
|
return false
|
|
}
|
|
state, ok := ctx.Value(payloadFinalizerKey{}).(*payloadFinalizerState)
|
|
if !ok || state == nil {
|
|
return false
|
|
}
|
|
state.mu.RLock()
|
|
root := state.root
|
|
paths := state.filteredPaths
|
|
if selectOverride {
|
|
paths = state.overriddenPaths
|
|
}
|
|
state.mu.RUnlock()
|
|
target := buildPayloadPath(root, path)
|
|
if target == "" {
|
|
return false
|
|
}
|
|
for _, recorded := range paths {
|
|
if recorded == target || (includeAncestors && strings.HasPrefix(target, recorded+".")) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// PayloadFiltersPath reports whether a matching Payload.Filter rule evaluated
|
|
// during the most recent FinalizePayloadDoc call on ctx targeted path (or an
|
|
// ancestor container of path) under the finalizer's configured root.
|
|
func PayloadFiltersPath(ctx context.Context, path string) bool {
|
|
return payloadFinalizerPathsMatch(ctx, path, false, true)
|
|
}
|
|
|
|
// PayloadFiltersExactPath reports whether a matching Payload.Filter rule
|
|
// evaluated during the most recent FinalizePayloadDoc call on ctx explicitly
|
|
// targeted path (without matching ancestor containers) under the finalizer's
|
|
// configured root.
|
|
func PayloadFiltersExactPath(ctx context.Context, path string) bool {
|
|
return payloadFinalizerPathsMatch(ctx, path, false, false)
|
|
}
|
|
|
|
// PayloadOverridesPath reports whether a matching Payload.Override or
|
|
// Payload.OverrideRaw rule evaluated during the most recent FinalizePayloadDoc
|
|
// call on ctx targeted path (or an ancestor container of path) under the
|
|
// finalizer's configured root.
|
|
func PayloadOverridesPath(ctx context.Context, path string) bool {
|
|
return payloadFinalizerPathsMatch(ctx, path, true, true)
|
|
}
|