mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 16:04:01 +00:00
224 lines
8.2 KiB
Go
224 lines
8.2 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"opencode2api/internal/config"
|
|
"opencode2api/internal/identity"
|
|
"opencode2api/internal/models"
|
|
wire "opencode2api/internal/protocol"
|
|
"opencode2api/internal/telemetry"
|
|
)
|
|
|
|
const maxContinuationPartialBytes = 512 << 10
|
|
|
|
const continuationInstruction = "Continue exactly where you stopped. Do not repeat anything already written."
|
|
|
|
const reasoningContinuationInstruction = "The previous response was interrupted after the following reasoning. Continue the task without repeating this reasoning and provide the final answer:\n\n"
|
|
|
|
type anonymousStreamStateKey struct{}
|
|
|
|
type anonymousStreamState struct {
|
|
node *anonymousNode
|
|
body io.ReadCloser
|
|
failed map[*anonymousNode]bool
|
|
}
|
|
|
|
func withAnonymousStreamState(ctx context.Context) (context.Context, *anonymousStreamState) {
|
|
state := &anonymousStreamState{failed: make(map[*anonymousNode]bool)}
|
|
return context.WithValue(ctx, anonymousStreamStateKey{}, state), state
|
|
}
|
|
|
|
func rememberAnonymousStream(ctx context.Context, node *anonymousNode, body io.ReadCloser) {
|
|
if state, ok := ctx.Value(anonymousStreamStateKey{}).(*anonymousStreamState); ok {
|
|
state.node, state.body = node, body
|
|
}
|
|
}
|
|
|
|
func skipAnonymousStreamNode(ctx context.Context, node *anonymousNode) bool {
|
|
state, _ := ctx.Value(anonymousStreamStateKey{}).(*anonymousStreamState)
|
|
return state != nil && state.failed[node] && node != nil && node.proxy != nil && !node.proxy.pool
|
|
}
|
|
|
|
type gatewayStreamResumer struct {
|
|
g *Gateway
|
|
requestCtx context.Context
|
|
clientCtx context.Context
|
|
streamState *anonymousStreamState
|
|
continuationTimeout time.Duration
|
|
route models.Route
|
|
ids identity.RequestIDs
|
|
zenBody []byte
|
|
attemptOffset int
|
|
}
|
|
|
|
func (resumer *gatewayStreamResumer) ResumeSegment(partial, reasoning string) (io.Reader, error) {
|
|
if resumer.clientCtx == nil || resumer.requestCtx == nil || resumer.streamState == nil {
|
|
return nil, errors.New("stream continuation requires request state")
|
|
}
|
|
if isDiagnosticRequest(resumer.requestCtx) {
|
|
return nil, errors.New("diagnostic streams cannot be continued")
|
|
}
|
|
if _, pinned := relayOverrideFrom(resumer.requestCtx); pinned {
|
|
return nil, errors.New("relay-pinned streams cannot be continued")
|
|
}
|
|
if err := resumer.clientCtx.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
if resumer.continuationTimeout <= 0 {
|
|
return nil, errors.New("stream continuation timeout is disabled")
|
|
}
|
|
if !resumer.route.Anonymous || resumer.route.Tier != config.TierZen || resumer.route.Protocol != wire.Chat || resumer.route.ProtocolFor(config.TierZen) != wire.Chat {
|
|
return nil, errors.New("stream continuation requires an anonymous Chat route")
|
|
}
|
|
if resumer.g.catalog != nil {
|
|
diagnostic := resumer.g.catalog.Diagnostic(resumer.route.ID, wire.Chat, false, false, true)
|
|
if diagnostic.RouteError != "" || !diagnostic.Anonymous || diagnostic.NativeProtocols[config.TierZen] != wire.Chat {
|
|
return nil, errors.New("stream continuation route is no longer available as Chat")
|
|
}
|
|
}
|
|
body, err := buildContinuationBody(resumer.zenBody, partial, reasoning)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
resumer.releaseFailedStream()
|
|
ctx, cancelClient := context.WithCancelCause(context.WithoutCancel(resumer.requestCtx))
|
|
ctx, cancelTimeout := context.WithTimeoutCause(ctx, resumer.continuationTimeout, context.DeadlineExceeded)
|
|
stopClient := context.AfterFunc(resumer.clientCtx, func() { cancelClient(resumer.clientCtx.Err()) })
|
|
cleanup := func() {
|
|
stopClient()
|
|
cancelTimeout()
|
|
cancelClient(nil)
|
|
}
|
|
if err := resumer.clientCtx.Err(); err != nil {
|
|
cleanup()
|
|
return nil, err
|
|
}
|
|
if meta := telemetry.MetaFromContext(ctx); meta != nil {
|
|
resumer.attemptOffset = max(resumer.attemptOffset, meta.Attempts)
|
|
meta.Legs = append(meta.Legs, "cont:attempt")
|
|
}
|
|
response, fetchErr, attempts := resumer.g.doAnonymousUpstream(ctx, resumer.route, map[config.Tier][]byte{config.TierZen: body}, resumer.ids, resumer.attemptOffset)
|
|
resumer.attemptOffset += attempts
|
|
var buffered *bufio.Reader
|
|
var prefix []byte
|
|
if fetchErr == nil && response != nil && response.Body != nil && response.StatusCode/100 == 2 && strings.Contains(strings.ToLower(response.Header.Get("Content-Type")), "text/event-stream") {
|
|
buffered = bufio.NewReader(response.Body)
|
|
prefix, fetchErr = readFirstEvent(buffered)
|
|
}
|
|
cause := context.Cause(ctx)
|
|
if cause != nil {
|
|
fetchErr = cause
|
|
}
|
|
if fetchErr != nil {
|
|
cleanup()
|
|
if response != nil && response.Body != nil {
|
|
_ = response.Body.Close()
|
|
}
|
|
resumer.ResumeSkipped("resume_fetch_failed")
|
|
return nil, fetchErr
|
|
}
|
|
if response == nil || response.Body == nil || response.StatusCode/100 != 2 || !strings.Contains(strings.ToLower(response.Header.Get("Content-Type")), "text/event-stream") {
|
|
cleanup()
|
|
if response != nil && response.Body != nil {
|
|
_ = response.Body.Close()
|
|
}
|
|
resumer.ResumeSkipped("resume_invalid_response")
|
|
return nil, errors.New("stream continuation did not return a successful SSE response")
|
|
}
|
|
if meta := telemetry.MetaFromContext(ctx); meta != nil {
|
|
meta.Legs = append(meta.Legs, "cont:resume")
|
|
}
|
|
if resumer.g.logger != nil {
|
|
resumer.g.logger.Info("anonymous stream continued", "component", "stream", "event", "stream_continued", "request_id", resumer.ids.Request, "model", resumer.route.ID, "attempts", resumer.attemptOffset)
|
|
}
|
|
reader := wire.RenameStreamReader(io.MultiReader(bytes.NewReader(prefix), buffered), wire.Chat, requestShapeFrom(ctx).renames)
|
|
return &continuationBody{Reader: reader, body: response.Body, cleanup: cleanup}, nil
|
|
}
|
|
|
|
func (resumer *gatewayStreamResumer) releaseFailedStream() {
|
|
state := resumer.streamState
|
|
if state.body != nil {
|
|
if body, ok := state.body.(*warpBody); ok && !body.diagnostic && body.lease != nil {
|
|
body.lease.pool.Fail(body.lease.lease, "stream interrupted")
|
|
}
|
|
_ = state.body.Close()
|
|
state.body = nil
|
|
}
|
|
if state.node != nil && !isDiagnosticRequest(resumer.requestCtx) {
|
|
resumer.g.anonymous.MarkFailure(state.node, nil, io.ErrUnexpectedEOF)
|
|
if state.failed == nil {
|
|
state.failed = make(map[*anonymousNode]bool)
|
|
}
|
|
state.failed[state.node] = true
|
|
}
|
|
state.node = nil
|
|
}
|
|
|
|
func (resumer *gatewayStreamResumer) ResumeSkipped(reason string) {
|
|
if meta := telemetry.MetaFromContext(resumer.requestCtx); meta != nil {
|
|
meta.Legs = append(meta.Legs, "cont:"+reason)
|
|
}
|
|
if resumer.g.logger != nil {
|
|
resumer.g.logger.Debug("anonymous stream continuation skipped", "component", "stream", "event", "stream_continuation_skipped", "request_id", resumer.ids.Request, "reason", reason)
|
|
}
|
|
}
|
|
|
|
type continuationBody struct {
|
|
io.Reader
|
|
body io.ReadCloser
|
|
cleanup func()
|
|
once sync.Once
|
|
}
|
|
|
|
func (body *continuationBody) Close() error {
|
|
var err error
|
|
body.once.Do(func() {
|
|
body.cleanup()
|
|
err = body.body.Close()
|
|
})
|
|
return err
|
|
}
|
|
|
|
func buildContinuationBody(original []byte, partial, reasoning string) ([]byte, error) {
|
|
if partial == "" && reasoning == "" {
|
|
return nil, errors.New("stream continuation requires delivered output")
|
|
}
|
|
if len(partial) > maxContinuationPartialBytes || len(reasoning) > maxContinuationPartialBytes {
|
|
return nil, errors.New("stream continuation output exceeds its limit")
|
|
}
|
|
var payload map[string]any
|
|
if err := json.Unmarshal(original, &payload); err != nil {
|
|
return nil, errors.New("stream continuation base is not a Chat request")
|
|
}
|
|
if choices, exists := payload["n"]; exists {
|
|
if count, ok := choices.(float64); !ok || count != 1 {
|
|
return nil, errors.New("stream continuation requires a single Chat choice")
|
|
}
|
|
}
|
|
if _, exists := payload["input"]; exists {
|
|
return nil, errors.New("stream continuation cannot replay a non-Chat request")
|
|
}
|
|
messages, ok := payload["messages"].([]any)
|
|
if !ok || len(messages) == 0 {
|
|
return nil, errors.New("stream continuation base has no Chat messages")
|
|
}
|
|
if partial != "" {
|
|
messages = append(messages, map[string]any{"role": "assistant", "content": partial})
|
|
messages = append(messages, map[string]any{"role": "user", "content": continuationInstruction})
|
|
} else {
|
|
messages = append(messages, map[string]any{"role": "user", "content": reasoningContinuationInstruction + reasoning})
|
|
}
|
|
payload["messages"] = messages
|
|
payload["stream"] = true
|
|
return json.Marshal(payload)
|
|
}
|