Files
CLIProxyAPI/internal/runtime/executor/helps/copilot_auto.go
hkfires c1483b0e89 fix(copilot): pin continuation owner and fail over route errors
Track output item IDs and resolve item_reference inputs to their
owning credential, including for local OAuth model aliases, so
stored Responses continuations stay pinned to the issuing account.

Treat credential-status failures from Copilot route planning as
credential-scoped upstream attempts and route them through the
normal failure pipeline in sync, count, streaming, and Home
execution, enabling cooldown and failover instead of aborting.
2026-11-30 19:52:32 +08:00

602 lines
20 KiB
Go

package helps
import (
"bytes"
"context"
"maps"
"net/http"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/MoeForge/moego/ojson"
"github.com/google/uuid"
"github.com/router-for-me/CLIProxyAPI/v8/internal/auth/copilot"
"github.com/router-for-me/CLIProxyAPI/v8/internal/cache"
"github.com/router-for-me/CLIProxyAPI/v8/internal/thinking"
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
"github.com/router-for-me/CLIProxyAPI/v8/sdk/translator"
"github.com/tiktoken-go/tokenizer"
)
const (
copilotAutoHistoryWindow = 5
copilotAutoPromptTokens = 512
// The longest O200kBase token occupies 128 bytes.
copilotAutoHistoryBytes = copilotAutoPromptTokens * 128
copilotAutoRefreshLead = time.Minute
)
type copilotAutoUser struct {
text string
image bool
key uuid.UUID
digest uuid.UUID
index int
}
type CopilotAutoPlan struct {
selection *copilot.AutoSelection
phase int
handoff string
originalTrailing int // Messages after the original task, before the first inference.
draftMessages int // Draft history to project as completed public tool exchanges.
ownerScope uuid.UUID
ownerAliasScopes []uuid.UUID
owner string
turn CopilotTurn
replay uuid.UUID
firstUser uuid.UUID
parent, requestKey uuid.UUID
tools *copilotToolHistory // Shared by all phases of this user turn.
copilotAutoState
}
type copilotToolHistory struct {
delivered sync.Map // Native and client-visible call IDs.
continued atomic.Bool
retries map[uuid.UUID]*copilotToolAttempt // Guarded by the router's tool retry lock.
}
func (p *CopilotAutoPlan) HasAnsweredTools() bool {
return p != nil && p.tools != nil && p.tools.continued.Load()
}
func (p *CopilotAutoPlan) RepeatsAnsweredTool(format translator.Format, event ojson.Result) bool {
var repeated bool
copilotOutputIDs(format, event, func(kind, id string) {
if kind == "call:" && !repeated {
_, repeated = p.tools.delivered.Load(id)
}
})
return repeated
}
func (p *CopilotAutoPlan) Route() copilot.Route {
if p.selection.Plan != nil {
return p.selection.Plan.Steps[p.phase].Route
}
return p.selection.Route
}
func (p *CopilotAutoPlan) Step() copilot.FusionStep {
if p == nil || p.selection.Plan == nil {
return copilot.FusionStep{}
}
return p.selection.Plan.Steps[p.phase]
}
func (p *CopilotAutoPlan) Pattern() string {
if p == nil || p.selection.Plan == nil {
return ""
}
return p.selection.Plan.Pattern
}
func (p *CopilotAutoPlan) NextPhase(index int, handoff string, draftMessages int) *CopilotAutoPlan {
next := *p
next.phase, next.handoff, next.draftMessages = index, handoff, draftMessages
next.turn.interaction, next.turn.task, next.replay = uuid.New(), uuid.New(), uuid.New()
return &next
}
func (p *CopilotAutoPlan) SessionToken() string { return p.selection.SessionToken }
func (p *CopilotAutoPlan) Turn() CopilotTurn { return p.turn }
func (p *CopilotAutoPlan) ValidAt(now time.Time) bool { return p.selection.ExpiresAt.After(now) }
func (p *CopilotAutoPlan) Redact(data []byte) []byte {
if p == nil {
return data
}
for _, token := range []string{p.selection.SessionToken, p.selection.RL.StateToken} {
if token != "" && bytes.Contains(data, []byte(token)) {
data = bytes.ReplaceAll(data, []byte(token), []byte("[REDACTED]"))
}
}
return data
}
func (p *CopilotAutoPlan) ReplayOptions(opts cliproxyexecutor.Options) (string, cliproxyexecutor.Options) {
opts.Metadata = maps.Clone(opts.Metadata)
if opts.Metadata == nil {
opts.Metadata = make(map[string]any, 1)
}
opts.Metadata[cliproxyexecutor.CanonicalSessionIDMetadataKey] = p.turn.session.String()
if p.Step().Role == "draft" {
// Hidden draft output belongs only to this phase, even when a later
// user turn happens to select the same physical model.
return p.turn.interaction.String(), opts
}
return p.replay.String(), opts
}
type copilotAutoSession struct {
lock chan struct{}
active *CopilotAutoPlan
pending *CopilotAutoPlan
}
type copilotAutoState struct {
anchor *copilot.AutoScores
policy copilot.AutoPolicy
turnsSinceAnchor int
window int
remaining int
recent []copilotAutoUser
lastUser uuid.UUID
}
// The session lock serializes decisions for a conversation. The bounded turn
// indexes let duplicates and interleaved tool branches reuse their own plan.
type CopilotAutoRouter struct {
toolRetries copilotToolRetries
turns *CopilotTurnLinks
sessions *cache.BoundedLRU[uuid.UUID, *copilotAutoSession]
requests *cache.BoundedLRU[uuid.UUID, *CopilotAutoPlan]
plans *cache.BoundedLRU[uuid.UUID, *CopilotAutoPlan]
responses *cache.BoundedLRU[uuid.UUID, *copilotAutoResponse]
items *cache.BoundedLRU[uuid.UUID, *copilotAutoItem]
}
func NewCopilotAutoRouter(turns *CopilotTurnLinks) *CopilotAutoRouter {
return &CopilotAutoRouter{
turns: turns,
sessions: cache.NewBoundedLRU[uuid.UUID, *copilotAutoSession](512, nil),
requests: cache.NewBoundedLRU[uuid.UUID, *CopilotAutoPlan](2048, nil),
plans: cache.NewBoundedLRU[uuid.UUID, *CopilotAutoPlan](2048, nil),
responses: cache.NewBoundedLRU[uuid.UUID, *copilotAutoResponse](128, nil),
items: cache.NewBoundedLRU[uuid.UUID, *copilotAutoItem](2048, nil),
}
}
// Plan can preview the format for an interceptor. Execution reuses the preview
// while its parent is current and publishes it only after use succeeds.
func (r *CopilotAutoRouter) Plan(
ctx context.Context, owner, credential, sessionID string, catalog *copilot.Catalog, req cliproxyexecutor.Request, opts cliproxyexecutor.Options,
countOnly bool, preview *CopilotAutoPlan, commit bool, now func() time.Time,
selectModel func(copilot.AutoRequest) (copilot.AutoSelection, error), use func(*CopilotAutoPlan, bool) error,
) error {
caller := metadataString(opts.Metadata, cliproxyexecutor.CallerScopeMetadataKey)
tier := copilot.ModelTier(thinking.ParseSuffix(req.Model).ModelName)
ownerScope := copilotOwnerScope(caller, sessionID, tier)
scope := uuid.NewSHA1(ownerScope, []byte(credential))
stable := sessionID != ""
source := req.Payload
var referenced *CopilotAutoPlan
switch opts.SourceFormat {
case translator.FormatOpenAIResponse, translator.FormatCodex:
var err error
if source, referenced, err = r.resolveResponseReferences(scope, uuid.Nil, source); err != nil {
return err
}
case translator.FormatGemini:
var err error
if source, err = normalizeCopilotGeminiCallIDs(source); err != nil {
return copilot.AutoSelectionError{Status: http.StatusBadRequest, Detail: err.Error()}
}
}
input := ParseCopilotTurnInput(source, opts.SourceFormat, copilotAutoSelection)
if n := len(input.users); referenced != nil && n > 1 && input.users[n-2].digest != referenced.lastUser {
// An older referenced item can precede a newer, fully inlined branch tip.
referenced = nil
}
var previous *CopilotAutoPlan
if input.previous != "" {
parent := r.response(scope, input.previous)
if parent == nil {
return copilotAutoHistoryError()
}
previous = parent.plan
}
if input.Initiator == "agent" {
if parent := r.parentPlan(scope, input.history, input.toolResultIDs, input.previous); parent != nil {
if countOnly || parent.selection.ExpiresAt.After(now()) {
// Selection has resolved the client's IDs, including name-only Gemini results.
toolResult := commit && !countOnly && len(input.toolResultIDs) > 0
if toolResult {
parent.tools.continued.Store(true)
}
return use(parent, toolResult)
}
return copilot.AutoSelectionError{Status: http.StatusBadRequest, Detail: "tool turn token expired; resend the full conversation history in a new turn"}
}
if previous != nil || len(input.toolResultIDs) > 0 {
return copilot.AutoSelectionError{Status: http.StatusBadRequest, Detail: "cannot identify the originating tool turn; resend its call IDs and conversation history"}
}
}
requestKey := copilotAutoRequestKey(scope, stable, input, opts)
sessionKey := scope
if !stable || input.Initiator == "agent" {
sessionKey = requestKey
}
var state *copilotAutoSession
switch {
case countOnly:
if previous != nil {
return use(previous, false)
}
if referenced != nil {
return use(referenced, false)
}
state, _ = r.sessions.Get(sessionKey)
if state == nil {
return use(nil, false)
}
case sessionKey == uuid.Nil:
state = &copilotAutoSession{lock: make(chan struct{}, 1)}
default:
state = r.sessions.GetOrAdd(sessionKey, func() *copilotAutoSession {
return &copilotAutoSession{lock: make(chan struct{}, 1)}
})
}
select {
case state.lock <- struct{}{}:
defer func() { <-state.lock }()
case <-ctx.Done():
return ctx.Err()
}
active := state.active
if active != nil && active.turn.scope != scope {
active = nil
}
if previous != nil {
active = previous
} else if referenced != nil {
active = referenced
}
if countOnly {
return use(active, false)
}
if plan, ok := r.requests.Get(requestKey); ok {
if !plan.selection.ExpiresAt.After(now()) {
return copilot.AutoSelectionError{Status: http.StatusBadRequest, Detail: "turn token expired; submit a new user turn"}
}
return use(plan, false)
}
if len(input.users) == 0 {
return copilot.AutoSelectionError{Status: http.StatusBadRequest, Detail: "needs a user message or a known continuation; resend the full conversation history"}
}
users := input.users
if active != nil {
if previous != nil || len(users) == 1 {
digest := active.lastUser
for i := range users {
digest = uuid.NewSHA1(digest, users[i].key[:])
users[i].digest = digest
}
users = append(slices.Clone(active.recent), users...)
} else if users[len(users)-2].digest != active.lastUser {
// A divergent full transcript can re-anchor on its own supplied history.
active = nil
}
}
var parent uuid.UUID
if active != nil {
parent = active.turn.interaction
}
plan := preview
if plan == nil && requestKey != uuid.Nil && state.pending != nil && state.pending.requestKey == requestKey {
plan = state.pending
}
if plan == nil || plan.turn.scope != scope || plan.parent != parent || !plan.ValidAt(now()) {
var err error
plan, err = active.advance(tier, input, users, scope, stable, now, selectModel)
if err != nil {
return err
}
if plan.Step().Role == "draft" {
plan.originalTrailing = len(fusionHistory(source, opts.SourceFormat)) - input.users[len(input.users)-1].index - 1
}
plan.parent, plan.requestKey = parent, requestKey
plan.owner, plan.ownerScope = owner, ownerScope
names := catalog.FusionAliases(tier)
if len(names) == 0 {
// Older dispatches only identify the name used to open this turn.
names = []string{thinking.ParseSuffix(PayloadRequestedModel(opts, req.Model)).ModelName}
}
for _, name := range names {
alias := strings.ToLower(strings.TrimSpace(name))
if alias == "" || copilot.ModelTier(alias) != "" {
continue
}
plan.ownerAliasScopes = append(plan.ownerAliasScopes, copilotOwnerScope(caller, sessionID, "alias:"+alias))
}
}
if !commit {
state.pending = plan
return use(plan, false)
}
if state.pending == plan {
state.pending = nil
}
if err := use(plan, false); err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
state.active = plan
if requestKey != uuid.Nil {
r.requests.GetOrAdd(requestKey, func() *CopilotAutoPlan { return plan })
}
r.plans.GetOrAdd(plan.turn.interaction, func() *CopilotAutoPlan { return plan })
return nil
}
func (r *CopilotAutoRouter) parentPlan(scope, history uuid.UUID, calls []string, previous string) *CopilotAutoPlan {
for _, id := range calls {
if id == "" {
return nil
}
}
if parent, ok := r.turns.turnForCalls(scope, history, calls, previous); ok {
plan, _ := r.plans.Get(parent.interaction)
return plan
}
return nil
}
func copilotAutoRequestKey(scope uuid.UUID, stable bool, input CopilotTurnInput, opts cliproxyexecutor.Options) uuid.UUID {
if key := strings.TrimSpace(opts.Headers.Get("Idempotency-Key")); key != "" {
return uuid.NewSHA1(scope, []byte("idempotency:"+key+":"+input.transcript.String()+":"+input.previous))
}
// An appended user message changes the transcript even when its text is
// identical. A standalone prompt needs an explicit request identifier.
if input.previous != "" || (stable && len(input.users) > 1) {
return uuid.NewSHA1(scope, []byte("transcript:"+input.transcript.String()+":"+input.previous))
}
if id := metadataString(opts.Metadata, cliproxyexecutor.RequestIDMetadataKey); id != "" {
return uuid.NewSHA1(scope, []byte("request:"+id))
}
return uuid.Nil
}
func (active *CopilotAutoPlan) advance(tier string, input CopilotTurnInput, users []copilotAutoUser, scope uuid.UUID, stable bool, now func() time.Time, selectModel func(copilot.AutoRequest) (copilot.AutoSelection, error)) (*CopilotAutoPlan, error) {
// Every response keeps the policy and user window at its own branch tip.
var s copilotAutoState
if active != nil {
s = active.copilotAutoState
}
fresh := active != nil && active.selection.ExpiresAt.After(now().Add(copilotAutoRefreshLead))
turns := s.turnsSinceAnchor + 1
session := scope
if active != nil {
session = active.turn.session
} else if !stable {
session = uuid.New()
}
var selection *copilot.AutoSelection
switch {
case tier != copilot.Balance:
candidate, err := selectModel(copilot.AutoRequest{SessionID: session.String(), Tier: tier, Prompt: users[len(users)-1].text})
if err != nil {
return nil, err
}
selection = &candidate
case fresh && (s.remaining > 0 || (s.anchor == nil && active.selection.RL.StateToken == "")):
selection = active.selection
s.remaining = max(0, s.remaining-1)
s.turnsSinceAnchor = turns
default:
request := copilot.AutoRequest{SessionID: session.String(), Tier: tier, Fusion: true}
window := copilotAutoHistoryWindow
if active != nil && active.selection.RL.StateToken != "" {
request.RL.StateToken = active.selection.RL.StateToken
if !fresh && s.remaining > 0 {
advance := false
request.RL.Advance = &advance
}
} else if s.anchor != nil {
currentWindow := s.window
request.Drift = &copilot.AutoDrift{Intent: "drift_check", TurnsSinceAnchor: turns, SkipWindow: &currentWindow, Anchor: s.anchor}
window = s.policy.ContextWindow
} else {
request.Drift = &copilot.AutoDrift{Intent: "anchor"}
}
request.Prompt, request.HasImage = copilotAutoPrompt(users, window)
candidate, err := selectModel(request)
if err != nil {
return nil, err
}
s.policy = candidate.Policy
if fresh && request.Drift != nil && request.Drift.Intent == "drift_check" && candidate.RL.StateToken == "" && candidate.Scores != nil &&
active.selection.ExpiresAt.After(now().Add(copilotAutoRefreshLead)) && !candidate.Policy.Escalates(*s.anchor, *candidate.Scores) {
selection = active.selection
// The current window is the next interval to skip. A stable
// check advertises the expanded window at the following lookup.
s.remaining, s.turnsSinceAnchor = s.window, turns
expanded := float64(s.window) * s.policy.BackoffCoefficient
s.window = s.policy.MaxSkip
if expanded < float64(s.window) {
s.window = int(expanded)
}
} else {
selection = &candidate
s.window, s.remaining, s.turnsSinceAnchor = 0, 0, 0
s.anchor = candidate.Scores
if candidate.RL.StateToken != "" {
s.anchor = nil
s.remaining = candidate.RL.SkipTurns
} else if s.anchor != nil {
s.window, s.remaining = candidate.Policy.InitialSkip, candidate.Policy.AnchorSkip
}
}
}
turn := CopilotTurn{scope: scope, session: session, history: input.history, interaction: uuid.New(), task: uuid.New()}
plan := &CopilotAutoPlan{selection: selection, turn: turn, tools: &copilotToolHistory{}}
if active != nil && active.Route().Info.ID == plan.Route().Info.ID && active.Route().Endpoint == plan.Route().Endpoint {
plan.replay, plan.firstUser = active.replay, active.firstUser
} else {
plan.replay, plan.firstUser = uuid.New(), users[len(users)-1].digest
}
// Retain only history that could fit on a later lookup. Complete incoming
// transcripts remain authoritative if the caller supplies them.
s.recent = copilotAutoRecentUsers(users)
s.lastUser = users[len(users)-1].digest
plan.copilotAutoState = s
return plan, nil
}
func copilotAutoRecentUsers(users []copilotAutoUser) []copilotAutoUser {
var recent []copilotAutoUser
budget := copilotAutoHistoryBytes
for i := len(users) - 1; i >= 0 && len(recent) < copilotAutoPromptTokens; i-- {
if strings.TrimSpace(users[i].text) == "" {
continue
}
cost := len(users[i].text) + 2
if cost > budget {
break
}
recent = append(recent, users[i])
budget -= cost
}
slices.Reverse(recent)
return recent
}
func copilotAutoPrompt(users []copilotAutoUser, window int) (string, bool) {
current := users[len(users)-1]
if len(users) == 1 || window == 0 || len(current.text) >= copilotAutoHistoryBytes {
return current.text, current.image
}
encoder, err := tokenizer.Get(tokenizer.O200kBase)
if err != nil {
return current.text, current.image
}
count, err := encoder.Count(current.text)
if err != nil || count >= copilotAutoPromptTokens {
return current.text, current.image
}
budget := copilotAutoPromptTokens - count
selected := []string{current.text}
for i := len(users) - 2; i >= 0 && len(selected) <= window; i-- {
text := users[i].text
if strings.TrimSpace(text) == "" {
continue
}
if len(text) > budget*128 {
break
}
count, err = encoder.Count(text)
// The separator occupies one token independently of its neighbors.
if err != nil || count+1 > budget {
break
}
selected = append(selected, text)
budget -= count + 1
}
slices.Reverse(selected)
return strings.Join(selected, "\n\n"), current.image
}
func copilotOwnerScope(caller, sessionID, tier string) uuid.UUID {
return uuid.NewSHA1(uuid.NameSpaceURL, []byte("copilot-owner:"+tier+"\x00"+caller+"\x00"+sessionID))
}
// ObserveDelivery indexes the public turn under both the private credential
// scope and a caller-scoped owner lookup used before round-robin selection.
func (r *CopilotAutoRouter) ObserveDelivery(p *CopilotAutoPlan, turn CopilotTurn, format translator.Format, root ojson.Result) {
if !r.turns.Observe(turn, format, root) || p == nil {
return
}
copilotOutputIDs(format, root, func(kind, id string) {
if kind == "call:" && id != "" {
p.tools.delivered.Store(strings.Clone(id), struct{}{})
}
})
r.plans.GetOrAdd(p.turn.interaction, func() *CopilotAutoPlan { return p })
owner := p.turn
owner.scope = p.ownerScope
r.turns.Observe(owner, format, root)
for _, aliasScope := range p.ownerAliasScopes {
owner.scope = aliasScope
r.turns.Observe(owner, format, root)
}
}
func (r *CopilotAutoRouter) ContinuationOwner(model, sessionID string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) string {
payload := req.Payload
if opts.SourceFormat == translator.FormatGemini {
var err error
payload, err = normalizeCopilotGeminiCallIDs(payload)
if err != nil {
return ""
}
}
input := ParseCopilotTurnInput(payload, opts.SourceFormat, copilotAutoSelection)
var references []string
if opts.SourceFormat == translator.FormatOpenAIResponse || opts.SourceFormat == translator.FormatCodex {
for _, item := range ojson.GetBytesNoCopy(payload, "input").Array() {
if item.Get("type").String() == "item_reference" {
references = append(references, item.Get("id").String())
}
}
}
if input.Initiator != "agent" && input.previous == "" && len(references) == 0 {
return ""
}
caller := metadataString(opts.Metadata, cliproxyexecutor.CallerScopeMetadataKey)
model = strings.ToLower(strings.TrimSpace(model))
base := thinking.ParseSuffix(model).ModelName
keys := []string{copilot.ModelTier(base)}
if keys[0] == "" {
// Home resolves a published base name before a literal suffixed alias.
keys[0] = "alias:" + base
if base != model {
keys = append(keys, "alias:"+model)
}
}
for _, key := range keys {
scope := copilotOwnerScope(caller, sessionID, key)
owner := ""
if p := r.parentPlan(scope, input.history, input.toolResultIDs, input.previous); p != nil {
owner = p.owner
}
// Resolve only opaque ownership here. History expansion remains private
// to the selected credential and validates every reference again.
valid := true
for _, id := range references {
link, ok := r.turns.links.Get(uuid.NewSHA1(scope, []byte("item:"+id)))
if id == "" || !ok || link.ambiguous.Load() {
valid = false
break
}
p, ok := r.plans.Get(link.turn.interaction)
if !ok || (owner != "" && owner != p.owner) {
valid = false
break
}
owner = p.owner
}
if valid && owner != "" {
return owner
}
}
return ""
}