mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-12-05 00:47:15 +08:00
Add the virtual copilot/auto model for accounts whose /meta default tier is enabled, resolved from account plan and published only while the entitlement remains valid. Select concrete models via /auto with scoring and RL multi-turn policies, bounded prompt history, token refresh, duplicate handling, and expiry checks before inference. Rebuild portable history across Chat, Responses, Messages, and Gemini route switches, including stored response and item continuations and Gemini tool-call ID normalization. Keep Auto state scoped by account, caller, and explicit session, and redact session and RL state tokens from logs.
106 lines
5.1 KiB
Go
106 lines
5.1 KiB
Go
package executor
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/MoeForge/moego/json"
|
|
"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"
|
|
x "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage"
|
|
tr "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator"
|
|
)
|
|
|
|
type copilotAutoUsageSink func(usage.Record)
|
|
|
|
func (s copilotAutoUsageSink) HandleUsage(_ context.Context, rec usage.Record) { s(rec) }
|
|
|
|
func TestCopilotAutoPlanFormatPayloadAndUsage(t *testing.T) {
|
|
const model = "gpt-5.1-codex"
|
|
const sessionToken = "private-inference-token-0123456789"
|
|
const stateToken = "private-rl-token-0123456789"
|
|
var meta copilot.AutoMetadata
|
|
if err := json.Unmarshal([]byte(`{"default_tier":"balance","tiers":[{"id":"balance","status":{"enabled":true}}]}`), &meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
auth := copilotTestAuth(t, t.Name(), model, copilot.Responses)
|
|
auth.CopilotCatalog = auth.CopilotCatalog.WithAuto(meta)
|
|
expires := time.Now().Add(time.Hour).Unix()
|
|
var autoCalls, inferenceCalls int
|
|
ctx, ginCtx := copilotLoggingTestContext(t, roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
|
var reply string
|
|
switch req.URL.Path {
|
|
case "/auto":
|
|
autoCalls++
|
|
reply = fmt.Sprintf(`{"selected_model":{"id":%q,"supported_endpoints":["/responses"]},"session_token":%q,"expires_at":%d,"hydra_rl_multi_turn":{"state_token":%q}}`, model, sessionToken, expires, stateToken)
|
|
case copilot.Responses:
|
|
inferenceCalls++
|
|
body, err := io.ReadAll(req.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
wire := ojson.ParseBytes(body)
|
|
if wire.Get("model").String() != model || wire.Get("max_output_tokens").Int() != 512 || wire.Get("tools").Exists() || wire.Get("input.0.role").String() != "user" {
|
|
t.Errorf("unexpected final payload %s", body)
|
|
}
|
|
if req.Header.Get("Copilot-Session-Token") != sessionToken || strings.Contains(string(body), stateToken) {
|
|
t.Error("invalid token placement on inference")
|
|
}
|
|
reply = fmt.Sprintf(`{"id":"resp","object":"response","status":"completed","model":%q,"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":11,"input_tokens_details":{"cached_tokens":4},"output_tokens":2}}`, model)
|
|
default:
|
|
return nil, fmt.Errorf("unexpected endpoint %s", req.URL.Path)
|
|
}
|
|
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(reply)), Request: req}, nil
|
|
}))
|
|
cfg := &config.Config{SDKConfig: config.SDKConfig{RequestLog: true}}
|
|
modelRule := []config.PayloadModelRule{{Name: copilot.AutoModelID}}
|
|
cfg.Payload.Override = []config.PayloadRule{{Models: modelRule, Params: map[string]any{"max_output_tokens": 512}}}
|
|
cfg.Payload.Filter = []config.PayloadFilterRule{{Models: modelRule, Params: []string{"tools"}}}
|
|
e := NewCopilotExecutor(cfg)
|
|
req := x.Request{Model: copilot.AutoModelID, Payload: []byte(`{"model":"copilot/auto","messages":[{"role":"user","content":"hello"}]}`)}
|
|
requestOpts := x.Options{SourceFormat: tr.FormatOpenAI, Headers: http.Header{"X-Session-Id": {"session"}, "Idempotency-Key": {"first"}}}
|
|
opts, err := e.PlanRequestRoute(ctx, auth, req, requestOpts, false)
|
|
if err != nil || autoCalls != 1 || e.RequestToFormat(req, opts) != tr.FormatOpenAIResponse {
|
|
t.Fatalf("route planning requests=%d format=%q err=%v", autoCalls, e.RequestToFormat(req, opts), err)
|
|
}
|
|
// Both deliveries reach the planner before either reaches inference.
|
|
if _, err = e.PlanRequestRoute(ctx, auth, req, requestOpts, false); err != nil || autoCalls != 1 {
|
|
t.Fatalf("duplicate preview: selections=%d err=%v", autoCalls, err)
|
|
}
|
|
records := make(chan usage.Record, 1)
|
|
sink := t.Name()
|
|
usage.RegisterNamedPlugin(sink, copilotAutoUsageSink(func(rec usage.Record) {
|
|
if rec.AuthID == auth.ID {
|
|
records <- rec
|
|
}
|
|
}))
|
|
t.Cleanup(func() { usage.RegisterNamedPlugin(sink, copilotAutoUsageSink(func(usage.Record) {})) })
|
|
n := helps.PayloadConfigEvaluationCount()
|
|
if _, err = e.Execute(ctx, auth, req, opts); err != nil || autoCalls != 1 || inferenceCalls != 1 || helps.PayloadConfigEvaluationCount() != n+1 {
|
|
t.Fatalf("execution selections=%d inferences=%d err=%v", autoCalls, inferenceCalls, err)
|
|
}
|
|
select {
|
|
case rec := <-records:
|
|
if rec.Model != model || rec.ResponseModel != model || rec.Detail.CachedTokens != 4 {
|
|
t.Fatalf("usage model=%s response_model=%s cached_tokens=%d", rec.Model, rec.ResponseModel, rec.Detail.CachedTokens)
|
|
}
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("missing usage record")
|
|
}
|
|
rawRequest, _ := ginCtx.Get("API_REQUEST")
|
|
requestLog, _ := rawRequest.([]byte)
|
|
responseLog, _ := readCapturedAPIResponse(ginCtx)
|
|
if strings.Contains(string(requestLog)+string(responseLog), sessionToken) || strings.Contains(string(requestLog)+string(responseLog), stateToken) ||
|
|
!strings.Contains(string(requestLog), "Copilot-Session-Token: [REDACTED]") {
|
|
t.Fatal("request log did not redact the Auto tokens")
|
|
}
|
|
}
|