Files
CLIProxyAPI/internal/runtime/executor/copilot_executor.go
hkfires 40471d862c feat(copilot): add home catalog snapshots for fusion routing
Snapshot and restore account catalogs and Fusion entitlements for
Home dispatch, bound to the credential, trusted origin, model, and
expiry. Concrete models carry only endpoint and reasoning defaults,
while entitled Fusion tiers carry the ordered directory and aliases.

Resolve Home routes from the restored catalog, expose the required
SDK API, and pin Fusion continuations via published aliases and the
Home caller scope. Replay completed draft tool exchanges to later
phases, suppress repeated draft actions, and report usage for every
Fusion phase, including failures, with additional-phase attribution.
2026-11-30 18:43:49 +08:00

612 lines
27 KiB
Go

package executor
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"maps"
"net/http"
"strings"
"time"
"github.com/MoeForge/moego/ojson"
"github.com/router-for-me/CLIProxyAPI/v8/internal/auth/copilot"
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
"github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps"
"github.com/router-for-me/CLIProxyAPI/v8/internal/thinking"
"github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common"
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
"github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage"
sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator"
log "github.com/sirupsen/logrus"
)
const copilotRouteKey = "copilot_attempt_route"
type CopilotExecutor struct {
cfg *config.Config
turns *helps.CopilotTurnLinks
auto *helps.CopilotAutoRouter
now func() time.Time
}
func NewCopilotExecutor(cfg *config.Config) *CopilotExecutor {
turns := helps.NewCopilotTurnLinks()
return &CopilotExecutor{cfg: cfg, turns: turns, auto: helps.NewCopilotAutoRouter(turns), now: time.Now}
}
// WithClock changes the clock used to check Auto inference-token expiry.
func (e CopilotExecutor) WithClock(now func() time.Time) *CopilotExecutor {
if now != nil {
e.now = now
}
return &e
}
// WithConfig preserves pending tool turns across auth reconciliation and config reload.
func (e CopilotExecutor) WithConfig(cfg *config.Config) *CopilotExecutor {
e.cfg = cfg
return &e
}
func (*CopilotExecutor) Identifier() string { return copilot.Provider }
type copilotAttemptRoute struct {
catalog *copilot.Catalog
route copilot.Route
expiresAt time.Time
auto *helps.CopilotAutoPlan
credential string
toolResult bool
}
func (e *CopilotExecutor) PlanRequestRoute(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, countOnly bool) (cliproxyexecutor.Options, error) {
if auth == nil {
return opts, nil
}
plan, err := e.planRoute(ctx, auth, req, opts, countOnly, nil)
if err != nil {
return opts, err
}
opts.Metadata = maps.Clone(opts.Metadata)
if opts.Metadata == nil {
opts.Metadata = make(map[string]any, 1)
}
opts.Metadata[copilotRouteKey] = plan
return opts, nil
}
func (e *CopilotExecutor) planRoute(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, countOnly bool, prepare func(copilotAttemptRoute) error) (copilotAttemptRoute, error) {
tier := copilot.ModelTier(thinking.ParseSuffix(req.Model).ModelName)
if tier == "" {
return e.resolveRoute(auth, req, time.Now()), nil
}
if opts.Alt == "responses/compact" {
return copilotAttemptRoute{}, statusErr{code: http.StatusBadRequest, msg: "copilot: unsupported Fusion request protocol"}
}
catalog := auth.ActiveCopilotCatalog(time.Now())
if !catalog.HasTier(tier) {
return copilotAttemptRoute{}, statusErr{code: http.StatusNotFound, msg: "copilot: Fusion tier is unavailable for this account"}
}
credential := copilotAutoCredential(auth)
base, _ := auth.Metadata["base_url"].(string)
token, _ := auth.Metadata["access_token"].(string)
if ctx == nil {
ctx = context.Background()
}
sessionID := cliproxyauth.ExplicitRequestSessionID(opts.Headers, req.Payload, opts.Metadata)
preview, _ := opts.Metadata[copilotRouteKey].(copilotAttemptRoute)
var resolved copilotAttemptRoute
err := e.auto.Plan(ctx, auth.ID, credential, sessionID, catalog, req, opts, countOnly, preview.auto, prepare != nil, e.now, func(input copilot.AutoRequest) (copilot.AutoSelection, error) {
client := helps.NewProxyAwareHTTPClient(ctx, e.cfg, auth, 0)
finalize := func(doc *ojson.Doc) {
helps.ApplyPayloadConfigWithRequestDoc(e.cfg, thinking.ParseSuffix(req.Model).ModelName, copilot.Provider, opts.SourceFormat.String(), "", doc, nil, helps.PayloadRequestedModel(opts, req.Model), helps.PayloadRequestPath(opts), opts.Headers)
}
var selection copilot.AutoSelection
var errSelect error
if tier == copilot.Balance {
selection, errSelect = copilot.SelectAuto(ctx, client, base, token, catalog, input, e.now, finalize)
} else {
selection, errSelect = copilot.SelectFusion(ctx, client, base, token, catalog, input, e.now, finalize)
}
var status cliproxyexecutor.StatusError
if errors.As(errSelect, &status) && copilot.IsCredentialStatus(status.StatusCode()) {
if home := usage.HomeSelectionFromContext(ctx); home != nil {
model := thinking.ParseSuffix(req.Model).ModelName
home.ResultModel = model
reporter := helps.NewExecutorUsageReporter(usage.WithHomeSelection(ctx, *home), e, model, auth)
reporter.PublishFailure(ctx, errSelect)
}
}
return selection, errSelect
}, func(auto *helps.CopilotAutoPlan, toolResult bool) error {
resolved = copilotAttemptRoute{auto: auto, credential: credential, toolResult: toolResult}
if auto != nil {
resolved.route = auto.Route()
} else {
// Cold token counts are estimates and do not create an Auto session.
model, endpoint := "gpt-4.1", copilot.Chat
switch opts.SourceFormat {
case sdktranslator.FormatClaude:
model, endpoint = "claude-sonnet-5", copilot.Messages
case sdktranslator.FormatOpenAIResponse, sdktranslator.FormatCodex:
model, endpoint = "gpt-5.1-codex", copilot.Responses
}
resolved.route, _ = (copilot.Model{ID: model, Endpoints: []string{endpoint}}).AutoRoute(nil)
}
if prepare != nil {
return prepare(resolved)
}
return nil
})
return resolved, err
}
func copilotAutoCredential(auth *cliproxyauth.Auth) string {
base, _ := auth.Metadata["base_url"].(string)
return fmt.Sprintf("%s\x00%d\x00%d\x00%s\x00%s", auth.ID, auth.RegistrationEpoch, auth.CredentialVersion, base, cliproxyauth.AccessTokenSHA256(auth))
}
func (e *CopilotExecutor) resolveRoute(auth *cliproxyauth.Auth, req cliproxyexecutor.Request, now time.Time) copilotAttemptRoute {
model := strings.TrimPrefix(thinking.ParseSuffix(req.Model).ModelName, copilot.ModelPrefix)
if e.cfg != nil && e.cfg.Home.Enabled {
var catalog *copilot.Catalog
if auth != nil && auth.CopilotCatalog != nil {
catalog = auth.ActiveCopilotCatalog(now)
if catalog == nil {
return copilotAttemptRoute{}
}
}
info, _ := cliproxyauth.ResolvedModelInfo(req)
route, _ := catalog.HomeRoute(model, info)
return copilotAttemptRoute{catalog: catalog, route: route, expiresAt: catalog.ExpiresAt()}
}
catalog := auth.ActiveCopilotCatalog(now)
route, _ := catalog.Route(model)
return copilotAttemptRoute{catalog: catalog, route: route, expiresAt: catalog.ExpiresAt()}
}
func (*CopilotExecutor) RequestToFormat(_ cliproxyexecutor.Request, opts cliproxyexecutor.Options) sdktranslator.Format {
plan, _ := opts.Metadata[copilotRouteKey].(copilotAttemptRoute)
return plan.route.Format
}
func (e *CopilotExecutor) Refresh(ctx context.Context, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
if auth == nil {
return nil, statusErr{code: http.StatusUnauthorized, msg: "copilot: missing auth record"}
}
githubToken, _ := auth.Metadata["refresh_token"].(string)
if githubToken == "" {
return nil, statusErr{code: http.StatusUnauthorized, msg: "copilot: missing GitHub credential; sign in again"}
}
client := helps.NewProxyAwareHTTPClient(ctx, e.cfg, auth, 30*time.Second)
token, err := copilot.Exchange(ctx, client, githubToken)
if err != nil {
return nil, err
}
base, err := token.API()
if err != nil {
return nil, err
}
updated := auth.Clone()
previousBase, _ := updated.Metadata["base_url"].(string)
updated.Metadata["access_token"] = token.Value
updated.Metadata["base_url"] = base
updated.Metadata["expired"] = time.Unix(token.ExpiresAt, 0).UTC().Format(time.RFC3339)
// Directory discovery runs in the service-owned Copilot queue, never in
// the shared credential refresh workers. An origin change revokes old routes.
if previousBase != base && updated.CopilotCatalog != nil {
updated.CopilotCatalog = copilot.UnavailableCatalog
}
return updated, nil
}
// HttpRequest only sends the inference credential to the account's trusted origin.
func (e *CopilotExecutor) HttpRequest(ctx context.Context, auth *cliproxyauth.Auth, req *http.Request) (*http.Response, error) {
authorizedReq, errPrepare := e.prepareAuthorizedRequest(ctx, auth, req)
if errPrepare != nil {
return nil, errPrepare
}
return e.doHTTPRequest(authorizedReq.Context(), auth, authorizedReq, nil)
}
func (e *CopilotExecutor) prepareAuthorizedRequest(ctx context.Context, auth *cliproxyauth.Auth, req *http.Request) (*http.Request, error) {
if req == nil || req.URL == nil || auth == nil {
return nil, fmt.Errorf("copilot: missing request or auth record")
}
if ctx == nil {
ctx = req.Context()
}
base, _ := auth.Metadata["base_url"].(string)
base = strings.TrimRight(base, "/")
token, _ := auth.Metadata["access_token"].(string)
if token == "" || !copilot.TrustedAPI(base) {
return nil, statusErr{code: http.StatusUnauthorized, msg: "copilot: missing usable credentials"}
}
if req.URL.Scheme+"://"+req.URL.Host != base || req.URL.User != nil {
return nil, fmt.Errorf("copilot: refusing to send a credential to a different origin")
}
req = req.Clone(ctx)
req.Host = ""
if req.Header == nil {
req.Header = make(http.Header)
}
req.Header.Set("Authorization", "Bearer "+token)
return req, nil
}
func (e *CopilotExecutor) doHTTPRequest(ctx context.Context, auth *cliproxyauth.Auth, req *http.Request, reporter *helps.UsageReporter) (*http.Response, error) {
client := *helps.NewProxyAwareHTTPClient(ctx, e.cfg, auth, 0)
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
if reporter != nil {
return reporter.TrackHTTPClient(&client).Do(req)
}
return client.Do(req)
}
type copilotPreparedRequest struct {
cachedToolReply *helps.CopilotToolReply
finishToolRetry func(*helps.CopilotToolReply)
responseTranslators *sdktranslator.Registry
route copilot.Route
turn helps.CopilotTurn
input helps.CopilotTurnInput
capture *helps.CopilotChatCapture
responsesCapture *helps.CopilotResponsesCapture
messagesCapture *helps.CopilotMessagesCapture
responsesInput ojson.Result
fusionInput []byte // The publicly replayable input used for this draft.
auto *helps.CopilotAutoPlan
replayAuth string
replayOpts cliproxyexecutor.Options
original, body []byte
}
func (e *CopilotExecutor) prepare(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, stream, countOnly bool) (copilotPreparedRequest, error) {
if auth == nil {
return copilotPreparedRequest{}, statusErr{code: http.StatusUnauthorized, msg: "copilot: missing auth record"}
}
if copilot.ModelTier(thinking.ParseSuffix(req.Model).ModelName) != "" {
var prepared copilotPreparedRequest
_, errPlan := e.planRoute(ctx, auth, req, opts, countOnly, func(resolved copilotAttemptRoute) error {
var err error
var finish func(*helps.CopilotToolReply)
if resolved.toolResult {
prepared.cachedToolReply, finish, err = e.auto.BeginToolRetry(ctx, resolved.auto, req, opts, stream)
if prepared.cachedToolReply != nil || err != nil {
return err
}
}
prepared, err = e.prepareRoute(ctx, auth, req, opts, stream, countOnly, resolved)
if err != nil && finish != nil {
finish(nil)
} else {
prepared.finishToolRetry = finish
}
return err
})
return prepared, errPlan
}
now := time.Now()
// Re-resolve concrete routes against the current account allowlist.
resolved := e.resolveRoute(auth, req, now)
if plan, planned := opts.Metadata[copilotRouteKey].(copilotAttemptRoute); planned {
if plan.route.Endpoint != resolved.route.Endpoint {
return copilotPreparedRequest{}, statusErr{code: http.StatusNotFound, msg: "copilot: model route changed after refresh"}
}
if plan.catalog == resolved.catalog && !plan.expiresAt.IsZero() && !now.Before(plan.expiresAt) {
return copilotPreparedRequest{}, statusErr{code: http.StatusNotFound, msg: "copilot: expired model route"}
}
}
return e.prepareRoute(ctx, auth, req, opts, stream, countOnly, resolved)
}
func (e *CopilotExecutor) prepareRoute(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, stream, countOnly bool, resolved copilotAttemptRoute) (copilotPreparedRequest, error) {
route := resolved.route
if route.Format == "" {
return copilotPreparedRequest{}, statusErr{code: http.StatusNotFound, msg: "copilot: no supported endpoint for this model and account"}
}
baseModel := route.Info.ID
from, to := opts.SourceFormat, route.Format
responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts)
requestTranslators := helps.CopilotTranslationRegistry(from, to)
responseTranslators := helps.CopilotTranslationRegistry(responseFormat, to)
hasResponse := responseTranslators.HasNonStreamResponseTransformer
if stream {
hasResponse = responseTranslators.HasStreamResponseTransformer
}
if opts.Alt == "responses/compact" || (from != to && !requestTranslators.HasRequestTransformer(from, to)) || (!countOnly && to != responseFormat && !hasResponse(responseFormat, to)) {
return copilotPreparedRequest{}, statusErr{code: http.StatusBadRequest, msg: "copilot: unsupported request or response protocol for this model"}
}
original := opts.OriginalRequest
if len(original) == 0 {
original = req.Payload
}
turnMode := helps.CopilotFixedModel
if resolved.credential != "" {
turnMode = helps.CopilotAutoInference
}
input := helps.ParseCopilotTurnInput(req.Payload, from, turnMode)
working, translationOriginal := req.Payload, original
replayAuth, replayOpts := auth.ID, opts
if resolved.auto != nil {
replayAuth, replayOpts = resolved.auto.ReplayOptions(opts)
var err error
working, err = e.auto.PrepareHistory(resolved.auto, req.Payload, from)
if err != nil {
return copilotPreparedRequest{}, err
}
if bytes.Equal(original, req.Payload) {
translationOriginal = working
} else if translationOriginal, err = e.auto.PrepareHistory(resolved.auto, original, from); err != nil {
return copilotPreparedRequest{}, err
}
} else if (from == sdktranslator.FormatOpenAIResponse || from == sdktranslator.FormatCodex) && to != sdktranslator.FormatOpenAIResponse && ojson.GetBytesNoCopy(working, "previous_response_id").String() != "" {
return copilotPreparedRequest{}, statusErr{code: http.StatusBadRequest, msg: "copilot: this model cannot resolve previous_response_id; resend the full conversation history without previous_response_id"}
}
var publicInput ojson.Result
var fusionInput []byte
step := resolved.auto.Step()
if step.Role == "draft" && !countOnly {
fusionInput = working
}
if step.Role == "revision" || step.Role == "repair" {
publicInput = ojson.GetBytesNoCopy(working, "input")
var err error
if bytes.Equal(working, translationOriginal) {
working, err = resolved.auto.PhaseHistory(working, from)
translationOriginal = working
} else {
working, err = resolved.auto.PhaseHistory(working, from)
if err == nil {
translationOriginal, err = resolved.auto.PhaseHistory(translationOriginal, from)
}
}
if err != nil {
return copilotPreparedRequest{}, err
}
}
if to == sdktranslator.FormatOpenAI {
ctx = context.WithValue(ctx, common.InlineChatToolMediaKey{}, true)
}
originalTo, body, updatesChanged, err := helps.TranslateCopilotRequestPair(ctx, requestTranslators, opts.Headers, e.cfg, from, to, baseModel, translationOriginal, working, stream)
if err != nil {
return copilotPreparedRequest{}, statusErr{code: http.StatusBadRequest, msg: err.Error()}
}
doc := ojson.NewDoc(body)
if errSet := doc.Set("model", baseModel); errSet != nil {
return copilotPreparedRequest{}, statusErr{code: http.StatusBadRequest, msg: "copilot: invalid request payload"}
}
thinkingReq := req
if step.Role != "" {
thinkingReq.Model = route.Info.ID
if step.Effort != "" {
thinkingReq.Model += "(" + step.Effort + ")"
} else {
thinking.StripThinkingFieldsDoc(doc, to.String())
thinkingReq.Payload = thinking.StripThinkingConfig(req.Payload, from.String())
}
}
if errThinking := helps.ApplyCopilotThinking(requestTranslators, doc, route, thinkingReq, opts, stream, updatesChanged); errThinking != nil {
return copilotPreparedRequest{}, errThinking
}
source := ojson.ParseBytes(working)
helps.NormalizeCopilotRequest(doc, route, from, source, stream)
requestedModel := helps.PayloadRequestedModel(opts, req.Model)
var sourceModelIDs []string
if (resolved.catalog != nil || resolved.credential != "") && strings.HasPrefix(req.Model, copilot.ModelPrefix) {
sourceModelIDs = []string{thinking.ParseSuffix(req.Model).ModelName}
}
draft := step.Role == "draft"
canReplay := (draft || to == sdktranslator.FormatOpenAI && from != to || to == sdktranslator.FormatOpenAIResponse && from == sdktranslator.FormatOpenAI) && !helps.CopilotPayloadMayWrite(e.cfg, baseModel, requestedModel, from.String(), to.String(), opts.Headers, sourceModelIDs, "model")
var restored bool
var responsesCapture *helps.CopilotResponsesCapture
if to == sdktranslator.FormatOpenAI {
input.RelayChatToolMedia(doc)
input.UniqueChatToolIDs(doc, from == sdktranslator.FormatClaude && baseModel == "kimi-k3")
if canReplay {
restored = e.turns.RestoreChatReplay(doc, replayAuth, replayOpts, input)
}
}
if to == sdktranslator.FormatOpenAIResponse {
helps.NormalizeCopilotSystemPrompt(doc, route, from, source)
if draft {
// previous_response_id must expand to the public transcript on the next turn.
publicInput = doc.Get("input")
}
if canReplay && from != sdktranslator.FormatClaude {
_, restored = e.turns.RestoreResponsesReplay(doc, replayAuth, replayOpts, ojson.Result{})
} else if from == sdktranslator.FormatClaude && !helps.CopilotPayloadMayWrite(e.cfg, baseModel, requestedModel, from.String(), to.String(), opts.Headers, sourceModelIDs, "model", "input", "instructions", "conversation", "previous_response_id") {
// No later payload rule can retarget this history. Bind the capture
// to both the client transcript and the restored upstream input.
responsesCapture, restored = e.turns.RestoreResponsesReplay(doc, replayAuth, replayOpts, source)
if countOnly || responseFormat != sdktranslator.FormatClaude {
responsesCapture = nil
}
}
}
var messagesCapture *helps.CopilotMessagesCapture
if to == sdktranslator.FormatClaude {
if (from == sdktranslator.FormatOpenAI || draft) && !helps.CopilotPayloadMayWrite(e.cfg, baseModel, requestedModel, from.String(), to.String(), opts.Headers, sourceModelIDs, "model", "messages", "system") {
// Derive the prefix before rolling cache breakpoints. No matching payload rule can rewrite this history.
var chat ojson.Result
if from == sdktranslator.FormatOpenAI {
chat = source
}
messagesCapture, restored = e.turns.PrepareMessagesReplay(doc, chat, replayAuth, replayOpts, draft)
if countOnly || (!draft && responseFormat != sdktranslator.FormatOpenAI) {
messagesCapture = nil
}
}
if shouldEnsureCacheControlDoc(doc, false, false, req.Payload, original) {
// Unlike Claude Code, Copilot also marks tools when a system prefix exists.
injectToolsCacheControlDoc(doc)
injectSystemCacheControlDoc(doc)
injectMessagesCacheControlDoc(doc)
}
stripPromptCacheOptionsDoc(doc)
}
// Rebuild each continuation from the input before user rules. Otherwise a
// replacement or positional filter on the stored prefix would run again.
var responsesInput ojson.Result
if resolved.auto != nil && !countOnly && (responseFormat == sdktranslator.FormatOpenAIResponse || responseFormat == sdktranslator.FormatCodex) {
switch {
case step.Role == "revision" || step.Role == "repair" || (draft && to == sdktranslator.FormatOpenAIResponse):
responsesInput = publicInput
case to == sdktranslator.FormatOpenAIResponse:
responsesInput = doc.Get("input")
case from == sdktranslator.FormatOpenAIResponse || from == sdktranslator.FormatCodex:
responsesInput = source.Get("input")
}
}
if resolved.auto != nil {
// Fusion can select models that reject explicit sampling controls.
_ = doc.Delete("temperature")
_ = doc.Delete("top_p")
_ = doc.Delete("top_k")
}
helps.ApplyPayloadConfigWithRequestDoc(e.cfg, baseModel, to.String(), from.String(), "", doc, originalTo, requestedModel, helps.PayloadRequestPath(opts), opts.Headers, sourceModelIDs...)
if resolved.auto != nil && !countOnly && (doc.Get("model").Type != ojson.String || doc.Get("model").String() != baseModel) {
return copilotPreparedRequest{}, statusErr{code: http.StatusBadRequest, msg: "copilot: payload rules cannot change the selected Fusion model"}
}
if (step.Role == "critic" || step.Role == "escalation") && doc.Get("tools.0").Exists() {
return copilotPreparedRequest{}, statusErr{code: http.StatusBadRequest, msg: "copilot: the Fusion reviewer has no workspace tool executor"}
}
if restored && (doc.Get("model").Type != ojson.String || doc.Get("model").String() != baseModel) {
return copilotPreparedRequest{}, statusErr{code: http.StatusBadRequest, msg: "copilot: private replay cannot be sent to a different model"}
}
if !countOnly && doc.Get("stream").Bool() != stream {
return copilotPreparedRequest{}, statusErr{code: http.StatusBadRequest, msg: "copilot: payload stream mode does not match the requested response mode"}
}
if !countOnly && !stream && to == sdktranslator.FormatClaude && route.NonStreamingOutput > 0 && doc.Get("max_tokens").Int() > int64(route.NonStreamingOutput) {
return copilotPreparedRequest{}, statusErr{code: http.StatusBadRequest, msg: fmt.Sprintf("copilot: max_tokens exceeds this model's non-streaming limit of %d; lower max_tokens or enable streaming", route.NonStreamingOutput)}
}
return copilotPreparedRequest{responseTranslators: responseTranslators, route: route, input: input, original: original, body: doc.Bytes(), messagesCapture: messagesCapture, responsesCapture: responsesCapture, responsesInput: responsesInput, fusionInput: fusionInput, auto: resolved.auto, replayAuth: replayAuth, replayOpts: replayOpts}, nil
}
func (e *CopilotExecutor) send(ctx context.Context, auth *cliproxyauth.Auth, opts cliproxyexecutor.Options, prepared *copilotPreparedRequest, reporter *helps.UsageReporter) (*http.Response, error) {
base, _ := auth.Metadata["base_url"].(string)
if !copilot.TrustedAPI(base) {
return nil, statusErr{code: http.StatusUnauthorized, msg: "copilot: missing trusted API endpoint"}
}
upstreamURL := strings.TrimRight(base, "/") + prepared.route.Endpoint
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, upstreamURL, bytes.NewReader(prepared.body))
if err != nil {
return nil, err
}
httpReq.Header.Set("Content-Type", "application/json")
input := prepared.input
wire := ojson.ParseBytes(prepared.body)
responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts)
draft := prepared.auto.Step().Role == "draft"
if prepared.route.Format == sdktranslator.FormatOpenAI && (draft || responseFormat != sdktranslator.FormatOpenAI) {
prepared.capture = e.turns.NewChatCapture(prepared.replayAuth, prepared.replayOpts, wire)
}
if prepared.route.Format == sdktranslator.FormatOpenAIResponse && (responseFormat == sdktranslator.FormatOpenAI || draft && responseFormat != sdktranslator.FormatClaude) {
prepared.responsesCapture = e.turns.NewResponsesCapture(prepared.replayAuth, prepared.replayOpts, wire)
}
if prepared.auto != nil {
if !prepared.auto.ValidAt(e.now()) {
return nil, copilot.AutoSelectionError{Status: http.StatusBadRequest, Detail: "turn token expired; submit a new user turn"}
}
prepared.turn = prepared.auto.Turn()
if token := prepared.auto.SessionToken(); token != "" {
httpReq.Header.Set("Copilot-Session-Token", token)
}
} else {
prepared.turn = e.turns.Resolve(auth.ID, input, opts, prepared.route.Format, wire)
}
helps.SetCopilotInferenceHeaders(httpReq.Header, prepared.route, wire, input.Initiator, prepared.turn)
if role := prepared.auto.Step().Role; role == "critic" || role == "escalation" {
httpReq.Header.Set("X-Interaction-Type", "conversation-agent")
httpReq.Header.Set("X-Interaction-Id", httpReq.Header.Get("X-Client-Session-Id"))
}
reporter.SetUpstreamModel(prepared.route.Info.ID)
reporter.SetTranslatedRequestMetadata(prepared.body, prepared.route.Format.String())
authorizedReq, errPrepare := e.prepareAuthorizedRequest(ctx, auth, httpReq)
if errPrepare != nil {
return nil, errPrepare
}
authType, authValue := auth.AccountInfo()
helps.RecordAPIRequest(ctx, e.cfg, helps.UpstreamRequestLog{
URL: upstreamURL,
Method: http.MethodPost,
Headers: authorizedReq.Header.Clone(),
Body: prepared.auto.Redact(prepared.body),
Provider: e.Identifier(),
AuthID: auth.ID,
AuthLabel: auth.Label,
AuthType: authType,
AuthValue: authValue,
})
resp, errDo := e.doHTTPRequest(authorizedReq.Context(), auth, authorizedReq, reporter)
if errDo != nil {
helps.RecordAPIResponseError(ctx, e.cfg, errDo)
return nil, errDo
}
helps.RecordAPIResponseMetadata(ctx, e.cfg, resp.StatusCode, resp.Header.Clone())
body, errDecode := helps.DecodeResponseBody(resp.Body, resp.Header)
if errDecode != nil {
helps.RecordAPIResponseError(ctx, e.cfg, errDecode)
return nil, statusErr{code: http.StatusBadGateway, msg: "copilot: invalid upstream content encoding"}
}
resp.Body = body
resp.Header.Del("Copilot-Session-Token")
resp.Header.Del("Content-Encoding")
resp.Header.Del("Content-Length")
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
defer closeCopilotResponse(resp.Body)
payload, errRead := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
payload = prepared.auto.Redact(payload)
helps.AppendAPIResponseChunk(ctx, e.cfg, payload)
if errRead != nil {
helps.RecordAPIResponseError(ctx, e.cfg, errRead)
}
return nil, newOpenAICompatStatusError(resp.StatusCode, resp.Header, payload)
}
return resp, nil
}
func closeCopilotResponse(body io.Closer) {
if err := body.Close(); err != nil {
log.Debug("copilot: failed to close upstream response")
}
}
func (e *CopilotExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) {
prepared, err := e.prepare(ctx, auth, req, opts, false, true)
if err != nil {
return cliproxyexecutor.Response{}, err
}
var count int64
if prepared.route.Format == sdktranslator.FormatClaude {
count, err = helps.CountClaudeInputTokens(prepared.body)
} else {
enc, errTokenizer := helps.TokenizerForModel(prepared.route.Info.ID)
if errTokenizer != nil {
return cliproxyexecutor.Response{}, errTokenizer
}
if prepared.route.Format == sdktranslator.FormatOpenAIResponse {
count, err = countCodexInputTokens(enc, prepared.body)
} else {
count, err = helps.CountOpenAIChatTokens(enc, prepared.body)
}
}
if err != nil {
return cliproxyexecutor.Response{}, err
}
var payload []byte
switch cliproxyexecutor.ResponseFormatOrSource(opts) {
case sdktranslator.FormatGemini:
payload = common.GeminiTokenCountJSON(count)
case sdktranslator.FormatClaude, sdktranslator.FormatOpenAIResponse:
payload = common.ClaudeInputTokensJSON(count)
default:
payload = helps.BuildOpenAIUsageJSON(count)
}
return cliproxyexecutor.Response{Payload: payload, Headers: http.Header{"X-Cpa-Token-Count": {"estimated"}}}, nil
}