mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-12-05 00:47:15 +08:00
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.
392 lines
14 KiB
Go
392 lines
14 KiB
Go
package executor
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"io"
|
|
"net/http"
|
|
|
|
"github.com/MoeForge/moego/ojson"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/internal/auth/copilot"
|
|
"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"
|
|
)
|
|
|
|
func (e *CopilotExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (result cliproxyexecutor.Response, err error) {
|
|
prepared, err := e.prepare(ctx, auth, req, opts, false, false)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
if reply := prepared.cachedToolReply; reply != nil {
|
|
result = reply.Response
|
|
result.Headers, result.Payload = result.Headers.Clone(), bytes.Clone(result.Payload)
|
|
return result, nil
|
|
}
|
|
if finish := prepared.finishToolRetry; finish != nil {
|
|
defer func() {
|
|
if err != nil {
|
|
finish(nil)
|
|
return
|
|
}
|
|
saved := result
|
|
saved.Headers, saved.Payload = saved.Headers.Clone(), bytes.Clone(saved.Payload)
|
|
finish(&helps.CopilotToolReply{Response: saved})
|
|
}()
|
|
}
|
|
prepared, resp, reporter, err := e.openCopilotResponse(ctx, auth, req, opts, prepared, false)
|
|
if err != nil {
|
|
return cliproxyexecutor.Response{}, err
|
|
}
|
|
defer reporter.TrackFailure(ctx, &err)
|
|
defer closeCopilotResponse(resp.Body)
|
|
const maxResponse = 64 << 20
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponse+1))
|
|
bodyTruncated := len(body) > maxResponse
|
|
logBody := body
|
|
if bodyTruncated {
|
|
logBody = body[:maxResponse]
|
|
}
|
|
helps.AppendAPIResponseChunk(ctx, e.cfg, prepared.auto.Redact(logBody))
|
|
if err != nil {
|
|
helps.RecordAPIResponseError(ctx, e.cfg, err)
|
|
return cliproxyexecutor.Response{}, err
|
|
}
|
|
if bodyTruncated || !ojson.ValidBytes(body) {
|
|
errInvalid := statusErr{code: http.StatusBadGateway, msg: "copilot: invalid upstream JSON response"}
|
|
helps.RecordAPIResponseError(ctx, e.cfg, errInvalid)
|
|
return cliproxyexecutor.Response{}, errInvalid
|
|
}
|
|
if failure := copilotResponseError(body); failure != nil {
|
|
helps.RecordAPIResponseError(ctx, e.cfg, failure)
|
|
return cliproxyexecutor.Response{}, failure
|
|
}
|
|
format := cliproxyexecutor.ResponseFormatOrSource(opts)
|
|
var state any
|
|
translatedBody := body
|
|
if prepared.route.Format == sdktranslator.FormatOpenAI && format != prepared.route.Format {
|
|
prepared.capture.Observe(ojson.ParseBytes(body))
|
|
translatedBody = helps.CopilotVisibleChatReasoning(body, false)
|
|
}
|
|
if prepared.route.Format == sdktranslator.FormatOpenAIResponse && format == sdktranslator.FormatClaude {
|
|
translatedBody = helps.CopilotVisibleResponsesForClaude(body)
|
|
}
|
|
out := prepared.responseTranslators.TranslateNonStream(ctx, prepared.route.Format, format, req.Model, prepared.original, prepared.body, translatedBody, &state)
|
|
if len(out) == 0 || helps.ApplyPatchTranslationError(state) != nil {
|
|
errTranslate := statusErr{code: http.StatusBadGateway, msg: "copilot: unable to translate upstream response"}
|
|
helps.RecordAPIResponseError(ctx, e.cfg, errTranslate)
|
|
return cliproxyexecutor.Response{}, errTranslate
|
|
}
|
|
if prepared.responsesCapture != nil {
|
|
prepared.responsesCapture.Observe(ojson.ParseBytes(body), ojson.GetBytesNoCopy(out, "content"))
|
|
}
|
|
if prepared.messagesCapture != nil {
|
|
prepared.messagesCapture.Observe(ojson.GetBytesNoCopy(body, "content"))
|
|
}
|
|
if format == sdktranslator.FormatOpenAIResponse {
|
|
out = helps.EnsureResponsesUsageDetails(out)
|
|
}
|
|
root := ojson.ParseBytes(body)
|
|
e.auto.ObserveDelivery(prepared.auto, prepared.turn, prepared.route.Format, root)
|
|
if prepared.auto != nil && format != prepared.route.Format {
|
|
e.auto.ObserveDelivery(prepared.auto, prepared.turn, format, ojson.ParseBytes(out))
|
|
}
|
|
if prepared.responsesInput.Exists() {
|
|
public := ojson.ParseBytes(out)
|
|
e.auto.ObserveResponse(prepared.auto, prepared.responsesInput, public, public.Get("output"))
|
|
}
|
|
reporter.ObserveResponseModel(body)
|
|
if prepared.route.Format == sdktranslator.FormatClaude {
|
|
reporter.Publish(ctx, helps.ParseClaudeUsage(body))
|
|
} else {
|
|
reporter.Publish(ctx, helps.ParseOpenAIUsage(body))
|
|
}
|
|
return cliproxyexecutor.Response{Payload: out, Headers: resp.Header.Clone(), Incomplete: ojson.GetBytesNoCopy(body, "status").String() == "incomplete"}, nil
|
|
}
|
|
|
|
func (e *CopilotExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (_ *cliproxyexecutor.StreamResult, err error) {
|
|
prepared, err := e.prepare(ctx, auth, req, opts, true, false)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if reply := prepared.cachedToolReply; reply != nil {
|
|
return reply.Stream(ctx), nil
|
|
}
|
|
finish := prepared.finishToolRetry
|
|
if finish != nil {
|
|
defer func() {
|
|
if err != nil {
|
|
finish(nil)
|
|
}
|
|
}()
|
|
}
|
|
prepared, resp, reporter, err := e.openCopilotResponse(ctx, auth, req, opts, prepared, true)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer reporter.TrackFailure(ctx, &err)
|
|
streamLogger := helps.BindAPIResponseStreamLogger(ctx, e.cfg)
|
|
out := make(chan cliproxyexecutor.StreamChunk)
|
|
go e.copilotStream(ctx, req, opts, prepared, resp.Body, reporter, streamLogger, out)
|
|
if finish != nil {
|
|
// Tool continuations already buffer the selected upstream phase. Finish
|
|
// capturing its public frames before the first client can disconnect.
|
|
reply := &helps.CopilotToolReply{Response: cliproxyexecutor.Response{Headers: resp.Header.Clone()}}
|
|
for chunk := range out {
|
|
if chunk.Err != nil {
|
|
return nil, chunk.Err
|
|
}
|
|
chunk.Payload = bytes.Clone(chunk.Payload)
|
|
reply.Chunks = append(reply.Chunks, chunk)
|
|
}
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
finish(reply)
|
|
return reply.Stream(ctx), nil
|
|
}
|
|
return &cliproxyexecutor.StreamResult{Headers: resp.Header.Clone(), Chunks: out}, nil
|
|
}
|
|
|
|
func (e *CopilotExecutor) copilotUsageReporter(ctx context.Context, auth *cliproxyauth.Auth, requestedModel string, prepared copilotPreparedRequest) *helps.UsageReporter {
|
|
model := thinking.ParseSuffix(requestedModel).ModelName
|
|
if prepared.auto != nil {
|
|
physical := prepared.route.Info.ID
|
|
if home := usage.HomeSelectionFromContext(ctx); home != nil {
|
|
home.ResultModel = model
|
|
ctx = usage.WithHomeSelection(ctx, *home)
|
|
physical = copilot.ModelPrefix + physical
|
|
}
|
|
model = physical
|
|
}
|
|
return helps.NewExecutorUsageReporter(ctx, e, model, auth)
|
|
}
|
|
|
|
func (e *CopilotExecutor) copilotStream(ctx context.Context, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, prepared copilotPreparedRequest, body io.ReadCloser, reporter *helps.UsageReporter, streamLogger *helps.APIResponseStreamLogger, out chan<- cliproxyexecutor.StreamChunk) {
|
|
defer close(out)
|
|
defer closeCopilotResponse(body)
|
|
scanner := helps.NewCodexSSEScanner(ctx, body, 16<<20)
|
|
scanner.SetOnLine(func(rawLine []byte) {
|
|
streamLogger.AppendChunk(prepared.auto.Redact(rawLine))
|
|
})
|
|
from, to := prepared.route.Format, cliproxyexecutor.ResponseFormatOrSource(opts)
|
|
var state any
|
|
var usage helps.StreamUsageBuffer
|
|
usage.SetRequestPayload(prepared.body)
|
|
inputTokens := helps.NewClaudeInputTokenState(opts.SourceFormat, from, to, prepared.original)
|
|
translationOriginal := prepared.original
|
|
if from == sdktranslator.FormatOpenAI && to == sdktranslator.FormatClaude && ojson.GetBytesNoCopy(translationOriginal, "stream").Type != ojson.True {
|
|
// ExecuteStream determines the response mode even if the caller reused a non-streaming body.
|
|
// Set the hint only on the response translator's view of the request.
|
|
doc := ojson.NewDoc(translationOriginal)
|
|
_ = doc.Set("stream", true)
|
|
translationOriginal = doc.Bytes()
|
|
}
|
|
var publicOutput helps.CopilotResponsesOutput
|
|
emit := func(chunk cliproxyexecutor.StreamChunk) bool {
|
|
if prepared.auto != nil {
|
|
helps.IterateStreamLines(chunk.Payload, func(line []byte) {
|
|
data := helps.ExtractStreamJSONPayload(line)
|
|
if len(data) == 0 {
|
|
return
|
|
}
|
|
event := ojson.ParseBytes(data)
|
|
if from != to {
|
|
e.auto.ObserveDelivery(prepared.auto, prepared.turn, to, event)
|
|
}
|
|
if !prepared.responsesInput.Exists() {
|
|
return
|
|
}
|
|
output := publicOutput.Observe(event)
|
|
switch event.Get("type").String() {
|
|
case "response.completed", "response.incomplete":
|
|
e.auto.ObserveResponse(prepared.auto, prepared.responsesInput, event.Get("response"), output)
|
|
}
|
|
})
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return false
|
|
case out <- chunk:
|
|
return true
|
|
}
|
|
}
|
|
fail := func(err error) {
|
|
streamLogger.RecordError(err)
|
|
usage.PublishFailure(ctx, reporter, err)
|
|
emit(cliproxyexecutor.StreamChunk{Err: err})
|
|
}
|
|
var signedBlocks *helps.ClaudeContentStream
|
|
if prepared.messagesCapture != nil {
|
|
signedBlocks = &helps.ClaudeContentStream{}
|
|
}
|
|
var visibleClaude *helps.ClaudeContentStream
|
|
if prepared.responsesCapture != nil && to == sdktranslator.FormatClaude {
|
|
visibleClaude = &helps.ClaudeContentStream{}
|
|
}
|
|
var terminal, terminalDelivered, chatFinished bool
|
|
defer func() {
|
|
if errCtx := ctx.Err(); errCtx != nil && !terminalDelivered {
|
|
if model := usage.ResponseModel(); model != "" {
|
|
reporter.SetUpstreamModel(model)
|
|
}
|
|
if !usage.PublishFailure(ctx, reporter, errCtx) {
|
|
reporter.PublishFailure(ctx, errCtx)
|
|
}
|
|
}
|
|
}()
|
|
for scanner.Scan() {
|
|
line := scanner.Bytes()
|
|
data, dataLine := bytes.CutPrefix(line, []byte("data:"))
|
|
if !dataLine {
|
|
continue
|
|
}
|
|
data = bytes.TrimSpace(data)
|
|
if len(data) == 0 {
|
|
continue
|
|
}
|
|
done := bytes.Equal(data, []byte("[DONE]"))
|
|
if !done && !ojson.ValidBytes(data) {
|
|
fail(statusErr{code: http.StatusBadGateway, msg: "copilot: invalid SSE data"})
|
|
return
|
|
}
|
|
if !done {
|
|
if errEvent := copilotResponseError(data); errEvent != nil {
|
|
fail(errEvent)
|
|
return
|
|
}
|
|
}
|
|
typ := ojson.GetBytesNoCopy(data, "type").String()
|
|
switch from {
|
|
case sdktranslator.FormatOpenAI:
|
|
usage.ObserveOpenAIStream(line)
|
|
chatFinished = chatFinished || ojson.GetBytesNoCopy(data, "choices.0.finish_reason").String() != ""
|
|
terminal = done
|
|
case sdktranslator.FormatClaude:
|
|
usage.ObserveClaudeStream(line)
|
|
terminal = typ == "message_stop"
|
|
case sdktranslator.FormatOpenAIResponse:
|
|
usage.ObserveResponsesStream(data)
|
|
terminal = typ == "response.completed" || typ == "response.incomplete"
|
|
}
|
|
var chunks [][]byte
|
|
if from == to && from != sdktranslator.FormatOpenAI {
|
|
if typ == "" {
|
|
continue
|
|
}
|
|
frame := common.SSEEventData(typ, data)
|
|
chunks = prepared.responseTranslators.TranslateStream(ctx, from, to, req.Model, translationOriginal, prepared.body, frame, &state)
|
|
} else if from != to || !done {
|
|
translatedLine := bytes.Clone(line)
|
|
if from == sdktranslator.FormatOpenAI && to != from && !done {
|
|
prepared.capture.Observe(ojson.ParseBytes(data))
|
|
if visible := helps.CopilotVisibleChatReasoning(data, true); !bytes.Equal(visible, data) {
|
|
translatedLine = append([]byte("data: "), visible...)
|
|
}
|
|
}
|
|
if from == sdktranslator.FormatOpenAIResponse && to == sdktranslator.FormatClaude {
|
|
visible := helps.CopilotVisibleResponsesForClaude(data)
|
|
if visible == nil {
|
|
continue
|
|
}
|
|
if !bytes.Equal(visible, data) {
|
|
translatedLine = append([]byte("data: "), visible...)
|
|
}
|
|
}
|
|
chunks = prepared.responseTranslators.TranslateStream(ctx, from, to, req.Model, translationOriginal, prepared.body, translatedLine, &state)
|
|
chunks = inputTokens.FinalizeTranslatedUsage(ctx, to, chunks, &state)
|
|
}
|
|
if helps.ApplyPatchTranslationError(state) != nil {
|
|
fail(statusErr{code: http.StatusBadGateway, msg: "copilot: unable to translate upstream tool call"})
|
|
return
|
|
}
|
|
if !done {
|
|
event := ojson.ParseBytes(data)
|
|
if prepared.responsesCapture != nil {
|
|
var content ojson.Result
|
|
if visibleClaude != nil {
|
|
for _, chunk := range chunks {
|
|
visibleClaude.ObserveSSE(chunk)
|
|
}
|
|
if terminal {
|
|
if raw, ok := visibleClaude.Content(); ok {
|
|
content = ojson.ParseBytes(raw)
|
|
}
|
|
}
|
|
}
|
|
prepared.responsesCapture.Observe(event, content)
|
|
}
|
|
if signedBlocks != nil {
|
|
signedBlocks.ObserveEvent(event)
|
|
if terminal {
|
|
if content, complete := signedBlocks.Content(); complete {
|
|
prepared.messagesCapture.Observe(ojson.ParseBytes(content))
|
|
}
|
|
}
|
|
}
|
|
e.auto.ObserveDelivery(prepared.auto, prepared.turn, from, event)
|
|
}
|
|
for _, chunk := range chunks {
|
|
if len(chunk) > 0 && !bytes.Equal(bytes.TrimSpace(chunk), []byte("[DONE]")) && !emit(cliproxyexecutor.StreamChunk{Payload: chunk}) {
|
|
return
|
|
}
|
|
}
|
|
if terminal {
|
|
terminalDelivered = true
|
|
break
|
|
}
|
|
}
|
|
if errScan := scanner.Err(); errScan != nil {
|
|
fail(errScan)
|
|
return
|
|
}
|
|
if !terminal && ctx.Err() == nil && from == sdktranslator.FormatOpenAI && chatFinished {
|
|
if to != from {
|
|
for _, chunk := range prepared.responseTranslators.TranslateStream(ctx, from, to, req.Model, translationOriginal, prepared.body, []byte("data: [DONE]"), &state) {
|
|
if len(chunk) != 0 && !emit(cliproxyexecutor.StreamChunk{Payload: chunk}) {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
terminal = true
|
|
terminalDelivered = true
|
|
}
|
|
if !terminal {
|
|
if ctx.Err() == nil {
|
|
fail(statusErr{code: http.StatusBadGateway, msg: "copilot: upstream stream ended before a terminal event"})
|
|
}
|
|
return
|
|
}
|
|
if model := usage.ResponseModel(); model != "" {
|
|
reporter.SetUpstreamModel(model)
|
|
}
|
|
if !usage.Publish(ctx, reporter) {
|
|
reporter.EnsurePublished(ctx)
|
|
}
|
|
}
|
|
|
|
func copilotResponseError(body []byte) error {
|
|
root := ojson.ParseBytes(body)
|
|
var code string
|
|
failure := root.Get("error")
|
|
if !failure.Exists() || failure.Type == ojson.Null {
|
|
failure = root.Get("response.error")
|
|
}
|
|
typ := root.Get("type").String()
|
|
if (!failure.Exists() || failure.Type == ojson.Null) && typ != "error" && typ != "response.failed" && root.Get("status").String() != "failed" {
|
|
return nil
|
|
}
|
|
code = failure.Get("code").String()
|
|
if code == "" {
|
|
code = root.Get("code").String()
|
|
}
|
|
if code == "rate_limit_exceeded" || failure.Get("type").String() == "rate_limit_error" {
|
|
return statusErr{code: http.StatusTooManyRequests, msg: "copilot: upstream rate limit"}
|
|
}
|
|
return statusErr{code: http.StatusBadGateway, msg: "copilot: upstream reported a generation error"}
|
|
}
|