mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-12-05 00:47:15 +08:00
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.
275 lines
11 KiB
Go
275 lines
11 KiB
Go
package executor
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"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"
|
|
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
|
|
x "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/sdk/translator"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
// Earlier phases may already have issued tools that the client executed.
|
|
// A duplicate tool call or terminal repair failure must stop this request.
|
|
type copilotPhaseError struct{ statusErr }
|
|
|
|
var errCopilotRepeatedTool = copilotPhaseError{statusErr{code: http.StatusBadGateway, msg: "copilot: Fusion upstream repeated an answered tool call"}}
|
|
|
|
func (copilotPhaseError) IsRequestStop() bool { return true }
|
|
|
|
func failedCopilotRepair(ctx context.Context, err error) error {
|
|
if ctx.Err() != nil {
|
|
return ctx.Err()
|
|
}
|
|
code := http.StatusBadGateway
|
|
var status x.StatusError
|
|
if errors.As(err, &status) {
|
|
code = status.StatusCode()
|
|
}
|
|
return copilotPhaseError{statusErr{code: code, msg: "copilot: Fusion repair failed"}}
|
|
}
|
|
|
|
func (e *CopilotExecutor) ContinuationAuth(req x.Request, opts x.Options) string {
|
|
// Local OAuth aliases, like Home names, are resolved after owner pinning.
|
|
homeMode := e.cfg != nil && e.cfg.Home.Enabled
|
|
localAliases := e.cfg != nil && len(e.cfg.OAuthModelAlias[copilot.Provider]) > 0
|
|
if req.Model == "" || (!homeMode && !localAliases && copilot.ModelTier(thinking.ParseSuffix(req.Model).ModelName) == "") {
|
|
return ""
|
|
}
|
|
session := cliproxyauth.ExplicitRequestSessionID(opts.Headers, req.Payload, opts.Metadata)
|
|
return e.auto.ContinuationOwner(req.Model, session, req, opts)
|
|
}
|
|
|
|
// Buffer speculative answers and tool continuations before committing any
|
|
// output. All other selected phases can use the native live response body.
|
|
func (e *CopilotExecutor) sendFusionPhase(ctx context.Context, auth *cliproxyauth.Auth, opts x.Options, prepared *copilotPreparedRequest, reporter *helps.UsageReporter, stream, speculative bool) (*http.Response, helps.FusionOutput, error) {
|
|
resp, err := e.send(ctx, auth, opts, prepared, reporter)
|
|
continuation := prepared.auto.HasAnsweredTools()
|
|
if err != nil || (!speculative && !continuation) {
|
|
return resp, helps.FusionOutput{}, err
|
|
}
|
|
defer closeCopilotResponse(resp.Body)
|
|
check := func(data []byte) error {
|
|
if continuation && prepared.auto.RepeatsAnsweredTool(prepared.route.Format, ojson.ParseBytes(data)) {
|
|
return errCopilotRepeatedTool
|
|
}
|
|
return copilotResponseError(data)
|
|
}
|
|
output, err := helps.ReadFusionOutput(ctx, resp.Body, prepared.route.Format, stream, check)
|
|
if err != nil {
|
|
return nil, output, err
|
|
}
|
|
resp.Body = io.NopCloser(bytes.NewReader(output.Body))
|
|
return resp, output, nil
|
|
}
|
|
|
|
// Both entry points commit the selected wire response through the same public
|
|
// translation and replay machinery. Nothing from a speculative review enters it.
|
|
func (e *CopilotExecutor) openCopilotResponse(ctx context.Context, auth *cliproxyauth.Auth, req x.Request, opts x.Options, prepared copilotPreparedRequest, stream bool) (copilotPreparedRequest, *http.Response, *helps.UsageReporter, error) {
|
|
reporter := e.copilotUsageReporter(ctx, auth, req.Model, prepared)
|
|
isDraft := prepared.auto.Step().Role == "draft"
|
|
resp, draft, err := e.sendFusionPhase(ctx, auth, opts, &prepared, reporter, stream, isDraft)
|
|
if !isDraft {
|
|
if err != nil {
|
|
publishCopilotPhase(ctx, prepared.route.Format, stream, draft, reporter, err)
|
|
if prepared.auto.Step().Role == "repair" {
|
|
err = failedCopilotRepair(ctx, err)
|
|
}
|
|
}
|
|
return prepared, resp, reporter, err
|
|
}
|
|
plan := prepared.auto
|
|
reporter.MarkUpstreamComplete()
|
|
publishDraft := func(additional bool, phaseErr error) {
|
|
if additional {
|
|
reporter.MarkAdditionalHomeUsage()
|
|
}
|
|
publishCopilotPhase(ctx, prepared.route.Format, stream, draft, reporter, phaseErr)
|
|
}
|
|
if errCtx := ctx.Err(); errCtx != nil {
|
|
publishDraft(false, errCtx)
|
|
return prepared, nil, nil, errCtx
|
|
}
|
|
pattern := plan.Pattern()
|
|
if err != nil {
|
|
var stopped copilotPhaseError
|
|
if errors.As(err, &stopped) {
|
|
publishDraft(false, err)
|
|
return prepared, nil, nil, err
|
|
}
|
|
var status x.StatusError
|
|
if pattern != "cascade" || (errors.As(err, &status) && copilot.IsCredentialStatus(status.StatusCode())) {
|
|
publishDraft(false, err)
|
|
return prepared, nil, nil, err
|
|
}
|
|
}
|
|
if draft.Tools && err == nil {
|
|
// Capture native history before projecting the tool batch for the client.
|
|
// Responses also needs the public projection to identify the next request.
|
|
var original helps.CopilotResponsesOutput
|
|
var draftBlocks *helps.ClaudeContentStream
|
|
if prepared.capture != nil {
|
|
prepared.capture.DraftTools = true
|
|
}
|
|
if prepared.messagesCapture != nil {
|
|
prepared.messagesCapture.DraftTools = true
|
|
if stream {
|
|
draftBlocks = &helps.ClaudeContentStream{}
|
|
}
|
|
}
|
|
public := draft.ToolBody(prepared.route.Format, stream, func(event ojson.Result) {
|
|
switch {
|
|
case prepared.responsesCapture != nil:
|
|
if output := original.Observe(event); output.Exists() {
|
|
prepared.responsesCapture.DraftOutput = output
|
|
}
|
|
case draftBlocks != nil:
|
|
draftBlocks.ObserveEvent(event)
|
|
case prepared.messagesCapture != nil:
|
|
prepared.messagesCapture.Observe(event.Get("content"))
|
|
case prepared.capture != nil:
|
|
prepared.capture.Observe(event)
|
|
}
|
|
})
|
|
if draftBlocks != nil {
|
|
if content, ok := draftBlocks.Content(); ok {
|
|
prepared.messagesCapture.Observe(ojson.ParseBytes(content))
|
|
}
|
|
}
|
|
// Observing the filtered response again would mark the original as ambiguous.
|
|
prepared.capture, prepared.messagesCapture = nil, nil
|
|
resp.Body = io.NopCloser(bytes.NewReader(public))
|
|
return prepared, resp, reporter, nil
|
|
}
|
|
// Review the same expanded public input the draft received, even if an
|
|
// unrelated response has since displaced the replay cache entry.
|
|
review, draftMessages := plan.NewFusionReview(prepared.fusionInput, opts.SourceFormat, draft.Text)
|
|
var verdict, failure string
|
|
if err != nil {
|
|
failure = "primary_call_failed"
|
|
} else {
|
|
var errReview error
|
|
verdict, errReview = e.reviewFusion(ctx, auth, req, opts, plan, review)
|
|
if errReview != nil {
|
|
failure = "judge_call_failed"
|
|
}
|
|
}
|
|
if errCtx := ctx.Err(); errCtx != nil {
|
|
publishDraft(false, errCtx)
|
|
return prepared, nil, nil, errCtx
|
|
}
|
|
handoff, errHandoff := review.Handoff(pattern, verdict, failure)
|
|
if errHandoff != nil {
|
|
publishDraft(false, errHandoff)
|
|
return prepared, nil, nil, errHandoff
|
|
}
|
|
if handoff == "" {
|
|
return prepared, resp, reporter, nil
|
|
}
|
|
handoff = "<current_datetime>" + e.now().Format("2006-01-02T15:04:05.000-07:00") + "</current_datetime>\n\n" + handoff
|
|
final := plan.NextPhase(2, handoff, draftMessages)
|
|
next, errPrep := e.prepareRoute(ctx, auth, req, opts, stream, false, copilotAttemptRoute{auto: final, route: final.Route(), credential: copilotAutoCredential(auth)})
|
|
if errPrep != nil {
|
|
if pattern == "critique" && ctx.Err() == nil {
|
|
return prepared, resp, reporter, nil
|
|
}
|
|
repairErr := failedCopilotRepair(ctx, errPrep)
|
|
publishDraft(false, repairErr)
|
|
return next, nil, nil, repairErr
|
|
}
|
|
finalReporter := e.copilotUsageReporter(ctx, auth, req.Model, next)
|
|
// Buffer revisions and handoffs with draft tools before exposing any SSE.
|
|
nextResp, finalOutput, errFinal := e.sendFusionPhase(ctx, auth, opts, &next, finalReporter, stream, pattern == "critique" || draftMessages > 0)
|
|
if errFinal == nil && draftMessages > 0 && finalOutput.RepeatsDraftTool(next.body, next.route.Format, stream) {
|
|
// A new call ID does not make an already completed draft action safe
|
|
// to execute twice. The final inference still incurred real usage.
|
|
closeCopilotResponse(nextResp.Body)
|
|
nextResp = nil
|
|
if err == nil && strings.TrimSpace(draft.Text) != "" && ctx.Err() == nil {
|
|
finalReporter.MarkAdditionalHomeUsage()
|
|
publishCopilotPhase(ctx, next.route.Format, stream, finalOutput, finalReporter, nil)
|
|
log.WithField("reason", "repeated_draft_action").Debug("Copilot Fusion kept the draft")
|
|
return prepared, resp, reporter, nil
|
|
}
|
|
errFinal = errCopilotRepeatedTool
|
|
} else if errFinal != nil && pattern == "critique" && ctx.Err() == nil {
|
|
finalReporter.MarkAdditionalHomeUsage()
|
|
publishCopilotPhase(ctx, next.route.Format, stream, finalOutput, finalReporter, errFinal)
|
|
log.WithField("reason", "revision_failed").Debug("Copilot Fusion kept the draft")
|
|
return prepared, resp, reporter, nil
|
|
}
|
|
// The delivered or terminal phase is primary. Earlier inference is still billable.
|
|
publishDraft(true, err)
|
|
if errFinal != nil {
|
|
publishCopilotPhase(ctx, next.route.Format, stream, finalOutput, finalReporter, errFinal)
|
|
if pattern == "cascade" {
|
|
errFinal = failedCopilotRepair(ctx, errFinal)
|
|
}
|
|
}
|
|
return next, nextResp, finalReporter, errFinal
|
|
}
|
|
|
|
func (e *CopilotExecutor) reviewFusion(ctx context.Context, auth *cliproxyauth.Auth, req x.Request, opts x.Options, plan *helps.CopilotAutoPlan, review helps.FusionReview) (string, error) {
|
|
if err := ctx.Err(); err != nil {
|
|
return "", err
|
|
}
|
|
payload, err := review.Request(plan.Pattern())
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.Payload = payload
|
|
opts.SourceFormat, opts.ResponseFormat, opts.OriginalRequest = translator.FormatOpenAI, translator.FormatOpenAI, payload
|
|
reviewer := plan.NextPhase(1, "", 0)
|
|
prepared, err := e.prepareRoute(ctx, auth, req, opts, false, false, copilotAttemptRoute{auto: reviewer, route: reviewer.Route(), credential: copilotAutoCredential(auth)})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
reporter := e.copilotUsageReporter(ctx, auth, req.Model, prepared)
|
|
reporter.MarkAdditionalHomeUsage()
|
|
res, err := e.send(ctx, auth, opts, &prepared, reporter)
|
|
if err != nil {
|
|
reporter.PublishFailure(ctx, err)
|
|
return "", err
|
|
}
|
|
defer closeCopilotResponse(res.Body)
|
|
output, err := helps.ReadFusionOutput(ctx, res.Body, prepared.route.Format, false, copilotResponseError)
|
|
publishCopilotPhase(ctx, prepared.route.Format, false, output, reporter, err)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if output.Tools {
|
|
return "", nil
|
|
}
|
|
return output.Text, nil
|
|
}
|
|
|
|
func publishCopilotPhase(ctx context.Context, format translator.Format, stream bool, output helps.FusionOutput, reporter *helps.UsageReporter, err error) {
|
|
if stream {
|
|
if err != nil {
|
|
output.Usage.PublishFailure(ctx, reporter, err)
|
|
} else if !output.Usage.Publish(ctx, reporter) {
|
|
reporter.EnsurePublished(ctx)
|
|
}
|
|
return
|
|
}
|
|
reporter.ObserveResponseModel(output.Body)
|
|
detail := helps.ParseOpenAIUsage(output.Body)
|
|
if format == translator.FormatClaude {
|
|
detail = helps.ParseClaudeUsage(output.Body)
|
|
}
|
|
if err != nil {
|
|
reporter.PublishFailureWithDetail(ctx, detail, err)
|
|
} else {
|
|
reporter.Publish(ctx, detail)
|
|
}
|
|
}
|