diff --git a/README.md b/README.md index 9665e11..630d1b9 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,10 @@ OAuth routes follow separate rules: the selected OAuth tier owns the request, us | Setting | Default | Meaning | | --- | --- | --- | | `retry.max_attempts` | `3` | Retry budget for keyed loops; anonymous and rotation paths have their own selection rules. | -| `retry.timeout_seconds` | `300` | Whole inference budget, including stream consumption. | +| `retry.timeout_seconds` | `300` | Initial inference budget, including stream consumption. Opt-in continuation segments have their own budget. | +| `retry.stream_resume_enabled` | `false` | Best-effort continuation of interrupted anonymous Chat-to-Chat text streams only; never retries after tool calls, client cancellation, upstream error events, or unsupported stream shapes. | +| `retry.stream_resume_max_attempts` | `1` | Maximum continuation segments per stream, from `1` to `10`. Each segment must deliver new output before another continuation is allowed. | +| `retry.stream_resume_timeout` | `60` | Total seconds per continuation segment, including acquisition, request, and body consumption; from `1` to `86400`. | | `performance.attempt_timeout_seconds` | `0` | Optional shorter attempt bound; zero leaves the request timeout. | | `performance.first_event_timeout_seconds` | `0` | Optional first-event wait; zero disables it. | | `performance.connect_timeout_seconds` | `5` | Connection establishment timeout. | @@ -192,6 +195,8 @@ OAuth routes follow separate rules: the selected OAuth tier owns the request, us | `performance.max_conns_per_host` | `0` | Connection cap; zero means unlimited. | | `performance.idle_conn_timeout_seconds` | `120` | Idle connection lifetime. | +Stream continuation is off by default and is not a resumable upstream protocol: it sends a new anonymous request containing the delivered partial answer and a continuation instruction. It preserves downstream response IDs and public model aliases, trims only a small exact text overlap, and cannot guarantee identical wording or perfect deduplication. Reported token usage is summed across all segments, including repeated prompt input. Keyed, cross-protocol, non-streaming, diagnostic, multi-choice, and non-text streams are not continued; resumed tool calls are delivered unchanged and disable further continuation. Validated SSE framing and generic error redaction remain active for every segment. + `proxies` accepts `direct` (dual stack), `direct4` (IPv4 only), `direct6` (IPv6 only), HTTP, HTTPS, SOCKS5, and SOCKS5H URLs. Dual stack uses the normal Go address selection and Happy Eyeballs behavior, not alternating IPv4/IPv6 requests. Single-family direct routes never fall back to the other family. `proxyfile` adds one route per nonempty line, relative to the configuration directory; entries are deduplicated and an empty resolved list still means dual-stack `direct`. Line comments start with `#`, `;`, or `//` at the beginning or after whitespace. Credentials embedded in proxy URLs are secrets. Mark a provider-managed rotating endpoint with `pool+https://proxy.example:8443` or `https://proxy.example:8443#pool`. Each attempt then opens a fresh connection without keep-alive/HTTP/2 reuse; these entries do not use static-node cooldown or health eviction. The provider must actually rotate its exits. Static proxies retain connection reuse, health tracking, and key bindings. `proxy_bindings` can pin a key fingerprint to a configured proxy. diff --git a/README.zh-CN.md b/README.zh-CN.md index 114c16a..4242f2f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -180,7 +180,10 @@ OAuth 另有规则:请求选择 OAuth 路由后,只使用该 Tier 已确认 | 配置项 | 默认值 | 含义 | | --- | --- | --- | | `retry.max_attempts` | `3` | Key 重试循环预算;匿名与轮转有各自选择规则。 | -| `retry.timeout_seconds` | `300` | 整个推理请求预算,含流式消费。 | +| `retry.timeout_seconds` | `300` | 首段推理预算,含流式消费;显式启用的续传段使用独立预算。 | +| `retry.stream_resume_enabled` | `false` | 尽力续传意外中断的匿名 Chat → Chat 文本流;工具调用、客户端取消、上游错误事件或不支持的流结构后不续传。 | +| `retry.stream_resume_max_attempts` | `1` | 每个流最多续传段数,范围 `1`–`10`;每段必须送出新内容才可再次续传。 | +| `retry.stream_resume_timeout` | `60` | 每个续传段的总秒数,含出口获取、请求与正文消费,范围 `1`–`86400`。 | | `performance.attempt_timeout_seconds` | `0` | 可选的较短单次尝试上限;零沿用请求超时。 | | `performance.first_event_timeout_seconds` | `0` | 可选的首事件等待上限;零关闭。 | | `performance.connect_timeout_seconds` | `5` | 建立连接超时。 | @@ -192,6 +195,8 @@ OAuth 另有规则:请求选择 OAuth 路由后,只使用该 Tier 已确认 | `performance.max_conns_per_host` | `0` | 连接数上限;零表示不限。 | | `performance.idle_conn_timeout_seconds` | `120` | 空闲连接寿命。 | +流式续传默认关闭,也不是上游原生断点恢复:它把已送出的部分回答和续写指令放入新的匿名请求。下游响应 ID 与公开模型别名保持不变,仅裁剪短小的精确文本重叠,无法保证措辞一致或完全去重。Token 用量按各段实际报告累加,含重复输入的 Prompt。Key 通道、跨协议、非流式、诊断、多 choice 和非文本流不续传;续传段的工具调用仍原样送出,且禁止进一步续传。每一段仍校验完整 SSE 帧并使用通用错误信息,避免泄露上游错误中的秘密。 + `proxies` 支持 `direct`(双栈)、`direct4`(仅 IPv4)、`direct6`(仅 IPv6)、HTTP、HTTPS、SOCKS5、SOCKS5H URL。双栈沿用 Go 的地址选择与 Happy Eyeballs,不代表 IPv4/IPv6 轮流发送;单栈直连不会回退另一地址族。`proxyfile` 从配置目录相对路径读取,每个非空行一个路由,合并后去重;最终为空时仍使用双栈 `direct`。行首或空白后的 `#`、`;`、`//` 表示注释。代理 URL 中的账号密码属于敏感信息。 供应商负责轮换出口时,可写成 `pool+https://proxy.example:8443` 或 `https://proxy.example:8443#pool`。每次尝试新建连接,不复用 keep-alive/HTTP/2,也不采用静态节点的冷却和健康淘汰。实际出口轮换由供应商提供。静态代理保留连接复用、健康跟踪与 Key 绑定;`proxy_bindings` 可按 Key 指纹绑定已配置代理。 diff --git a/config.example.json b/config.example.json index 6bb5a54..c6d8801 100644 --- a/config.example.json +++ b/config.example.json @@ -22,7 +22,10 @@ }, "retry": { "max_attempts": 3, - "timeout_seconds": 300 + "timeout_seconds": 300, + "stream_resume_enabled": false, + "stream_resume_max_attempts": 1, + "stream_resume_timeout": 60 }, "models": { "refresh_seconds": 300, diff --git a/internal/admin/server.go b/internal/admin/server.go index d31158d..7803f37 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -212,6 +212,13 @@ type LoggingUpdate struct { FilePath *string `json:"file_path,omitempty"` } +type RetryUpdate struct { + config.RetryConfig + StreamResumeEnabled *bool `json:"stream_resume_enabled,omitempty"` + StreamResumeMaxAttempts *int `json:"stream_resume_max_attempts,omitempty"` + StreamResumeTimeout *int `json:"stream_resume_timeout,omitempty"` +} + // ConfigUpdate is the body of PUT /api/config. Secrets carry either a new // value or the ID of the existing one. The WebUI username and password are // not changed here; they go through /api/account. @@ -227,7 +234,7 @@ type ConfigUpdate struct { ProxyFile string `json:"proxyfile"` ProxyBindings map[string]string `json:"proxy_bindings,omitempty"` Upstream config.UpstreamConfig `json:"upstream"` - Retry config.RetryConfig `json:"retry"` + Retry RetryUpdate `json:"retry"` Models ModelsUpdate `json:"models"` Performance config.PerformanceConfig `json:"performance"` Logging LoggingUpdate `json:"logging"` @@ -291,7 +298,7 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Warp: update.Warp, Proxies: proxies, ProxyFile: update.ProxyFile, ProxyBindings: proxyBindings, KeysDirect: current.KeysDirect, - Upstream: update.Upstream, Retry: update.Retry, Models: update.Models.ModelsConfig, Performance: update.Performance, Logging: update.Logging.LoggingConfig, Prefer: update.Prefer, + Upstream: update.Upstream, Retry: update.Retry.RetryConfig, Models: update.Models.ModelsConfig, Performance: update.Performance, Logging: update.Logging.LoggingConfig, Prefer: update.Prefer, Reasoning: reasoning, WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes}, } @@ -303,6 +310,18 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { candidate.ZenOAuth = latest.ZenOAuth candidate.ServerKeyMetadata = latest.ServerKeyMetadata candidate.Rotation = latest.Rotation + candidate.Retry.StreamResumeEnabled = latest.Retry.StreamResumeEnabled + if update.Retry.StreamResumeEnabled != nil { + candidate.Retry.StreamResumeEnabled = *update.Retry.StreamResumeEnabled + } + candidate.Retry.StreamResumeMaxAttempts = latest.Retry.StreamResumeMaxAttempts + if update.Retry.StreamResumeMaxAttempts != nil { + candidate.Retry.StreamResumeMaxAttempts = *update.Retry.StreamResumeMaxAttempts + } + candidate.Retry.StreamResumeTimeout = latest.Retry.StreamResumeTimeout + if update.Retry.StreamResumeTimeout != nil { + candidate.Retry.StreamResumeTimeout = *update.Retry.StreamResumeTimeout + } candidate.KeysDirect = latest.KeysDirect if update.KeysDirect != nil { candidate.KeysDirect = *update.KeysDirect diff --git a/internal/config/config.go b/internal/config/config.go index 8a34f07..1e62401 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -186,8 +186,11 @@ func (environment *PromptEnvironmentConfig) Normalize() error { // for how many rotating proxies may be drawn. TimeoutSeconds is the deadline // of the whole client request, retries included. type RetryConfig struct { - MaxAttempts int `json:"max_attempts"` - TimeoutSeconds int `json:"timeout_seconds"` + MaxAttempts int `json:"max_attempts"` + TimeoutSeconds int `json:"timeout_seconds"` + StreamResumeEnabled bool `json:"stream_resume_enabled"` + StreamResumeMaxAttempts int `json:"stream_resume_max_attempts"` + StreamResumeTimeout int `json:"stream_resume_timeout"` } // ModelsConfig controls model discovery and routing. RefreshSeconds is the @@ -350,7 +353,7 @@ func Load(path string) (Config, error) { Anonymous: false, Warp: WarpConfig{PoolSize: 2, Stack: string(warp.DefaultStack)}, Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Go: "https://opencode.ai/zen/go", Anonymous: "https://opencode.ai/inference"}, - Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 300}, + Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 300, StreamResumeMaxAttempts: 1, StreamResumeTimeout: 60}, Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}}, Performance: PerformanceConfig{MaxIdleConns: 2048, MaxIdleConnsPerHost: 256, MaxConnsPerHost: 0, IdleConnTimeoutSeconds: 120, ConnectTimeoutSeconds: 5, FailureCooldownSeconds: 15}, Logging: LoggingConfig{Level: "info", RingSize: 2000}, @@ -465,6 +468,18 @@ func Normalize(path string, cfg Config) (Config, error) { if cfg.Retry.TimeoutSeconds < 1 { return Config{}, errors.New("retry.timeout_seconds must be at least 1") } + if cfg.Retry.StreamResumeMaxAttempts == 0 { + cfg.Retry.StreamResumeMaxAttempts = 1 + } + if cfg.Retry.StreamResumeMaxAttempts < 1 || cfg.Retry.StreamResumeMaxAttempts > 10 { + return Config{}, errors.New("retry.stream_resume_max_attempts must be between 1 and 10") + } + if cfg.Retry.StreamResumeTimeout == 0 { + cfg.Retry.StreamResumeTimeout = 60 + } + if cfg.Retry.StreamResumeTimeout < 1 || cfg.Retry.StreamResumeTimeout > 86400 { + return Config{}, errors.New("retry.stream_resume_timeout must be between 1 and 86400 seconds") + } if cfg.Models.RefreshSeconds < 1 { return Config{}, errors.New("models.refresh_seconds must be at least 1") } diff --git a/internal/gateway/continue.go b/internal/gateway/continue.go new file mode 100644 index 0000000..afc50c2 --- /dev/null +++ b/internal/gateway/continue.go @@ -0,0 +1,223 @@ +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) +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 3785384..e30701a 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -402,6 +402,10 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { stream := jsonutil.BoolAt(payload, "stream") requestCtx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second) defer cancel() + var streamState *anonymousStreamState + if stream && external == wire.Chat && g.cfg.Retry.StreamResumeEnabled && !isDiagnosticRequest(r.Context()) { + requestCtx, streamState = withAnonymousStreamState(requestCtx) + } resp, upstreamRoute, err := g.doUpstream(requestCtx, route, bodies, ids) if err != nil { // The error branch never forwards the last response body, so close @@ -506,7 +510,15 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { if flusher, ok := w.(http.Flusher); ok { streamWriter = &deferredStreamWriter{ResponseWriter: w, flusher: flusher, status: resp.StatusCode} } - usage, usageReported, err = wire.ForwardStream(r.Context(), streamWriter, streamBody, upstreamRoute.Protocol, publicModel) + var resumer wire.StreamResumer + if streamState != nil && upstreamRoute.Anonymous && upstreamRoute.Tier == config.TierZen && upstreamRoute.Protocol == wire.Chat { + resumer = &gatewayStreamResumer{ + g: g, requestCtx: requestCtx, clientCtx: r.Context(), streamState: streamState, + continuationTimeout: time.Duration(g.cfg.Retry.StreamResumeTimeout) * time.Second, + route: upstreamRoute, ids: ids, zenBody: bodies[config.TierZen], + } + } + usage, usageReported, err = wire.ForwardStreamResumable(r.Context(), streamWriter, streamBody, upstreamRoute.Protocol, publicModel, resumer, g.cfg.Retry.StreamResumeMaxAttempts) } else { w.WriteHeader(resp.StatusCode) usage, usageReported, err = wire.TranscodeStream(r.Context(), w, streamBody, upstreamRoute.Protocol, external, publicModel) diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 48cb3fe..f9a5d5a 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -528,6 +528,9 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b blocked = g.anonymous.blockedExits(time.Now()) break } + if skipAnonymousStreamNode(ctx, node) { + continue + } proxies++ var nodeResp *http.Response var nodeErr error @@ -571,6 +574,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, "anonymous", "anonymous", true, node.proxy, resp, err, duration) if err == nil && resp.StatusCode/100 == 2 { g.observeAnonymousResult(ctx, node, resp, nil) + rememberAnonymousStream(ctx, node, resp.Body) g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) return resp, nil, attempts } diff --git a/internal/gateway/warp.go b/internal/gateway/warp.go index f0abd64..0df2bb9 100644 --- a/internal/gateway/warp.go +++ b/internal/gateway/warp.go @@ -304,6 +304,7 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, "anonymous", "anonymous", true, warpProxy(egress), resp, err, duration) if err == nil && status/100 == 2 { g.anonymous.NoteSuccess() + rememberAnonymousStream(ctx, nil, resp.Body) g.logger.Debug("anonymous WARP upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", egress, "status", status, "duration_ms", duration.Milliseconds()) return resp, nil, attempts } diff --git a/internal/protocol/stream_resume.go b/internal/protocol/stream_resume.go new file mode 100644 index 0000000..347924b --- /dev/null +++ b/internal/protocol/stream_resume.go @@ -0,0 +1,424 @@ +package protocol + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "unicode/utf8" + + "opencode2api/internal/jsonutil" +) + +const maxResumePartialBytes = 512 << 10 + +const maxResumeOverlapRunes = 200 + +type StreamResumer interface { + ResumeSegment(partial, reasoning string) (io.Reader, error) +} + +type StreamResumeObserver interface { + ResumeSkipped(reason string) +} + +type resumeStreamState struct { + writer http.ResponseWriter + flusher http.Flusher + model string + modelCaptured bool + responseID string + created any + committed bool + resumable bool + toolSeen bool + partialTooLarge bool + segmentDelivered bool + text strings.Builder + reasoning strings.Builder + previousUsage Usage + observer *streamUsageTracker + resumed bool + overlapTail string + pending []map[string]any + pendingBytes int + pendingText []rune + trimPending bool +} + +func ForwardStreamResumable(ctx context.Context, writer http.ResponseWriter, reader io.Reader, protocol Protocol, model string, resumer StreamResumer, maxResumes int) (Usage, bool, error) { + if resumer == nil || maxResumes <= 0 || protocol != Chat { + return ForwardStream(ctx, writer, reader, protocol, model) + } + flusher, ok := writer.(http.Flusher) + if !ok { + return Usage{}, false, fmt.Errorf("response writer does not support streaming") + } + state := &resumeStreamState{writer: writer, flusher: flusher, model: model, resumable: true} + var total Usage + reported := false + for resumes := 0; ; resumes++ { + observer := streamUsageObserver(Chat) + state.observer = observer + state.previousUsage = total + state.resumed = resumes > 0 + state.segmentDelivered = false + state.trimPending = state.resumed && state.text.Len() > 0 + state.overlapTail = resumeTextTail(state.text.String()) + observer.forward = state.forward + _, copyErr := io.Copy(observer, reader) + var pendingWriteErr *ClientWriteError + if !ClientCanceled(ctx, copyErr) && !errors.As(copyErr, &pendingWriteErr) { + if flushErr := state.flushPending(); flushErr != nil { + copyErr = flushErr + } + } + total = addResumeUsage(total, observer.Finish()) + reported = reported || observer.Reported() + if errors.Is(copyErr, errStreamNormalTermination) { + closeResumeReader(reader) + return total, reported, nil + } + if ClientCanceled(ctx, copyErr) { + closeResumeReader(reader) + if copyErr == nil { + copyErr = ctx.Err() + } + return total, reported, copyErr + } + var writeErr *ClientWriteError + if errors.As(copyErr, &writeErr) { + closeResumeReader(reader) + return total, reported, copyErr + } + cause := copyErr + if cause == nil { + cause = observer.ParseError() + } + if cause == nil { + cause = errSSEUnexpectedEOF + } + reason := "resume_limit" + switch { + case observer.ParseError() != nil: + reason = "invalid_stream" + case observer.error: + reason = "upstream_error" + case !state.resumable: + reason = "unsupported_stream" + case state.toolSeen: + reason = "tool_seen" + case state.partialTooLarge: + reason = "partial_too_large" + case !state.segmentDelivered: + reason = "no_new_output" + case resumes < maxResumes: + closeResumeReader(reader) + next, resumeErr := resumer.ResumeSegment(state.text.String(), state.reasoning.String()) + if resumeErr == nil && next != nil { + reader = next + continue + } + if next != nil { + closeResumeReader(next) + } + if ClientCanceled(ctx, resumeErr) { + if resumeErr == nil { + resumeErr = ctx.Err() + } + return total, reported, resumeErr + } + reason = "resume_failed" + } + if observer, ok := resumer.(StreamResumeObserver); ok { + observer.ResumeSkipped(reason) + } + closeResumeReader(reader) + if !state.committed { + writer.Header().Del("X-Accel-Buffering") + WriteError(writer, Chat, http.StatusBadGateway, "upstream SSE stream failed", "upstream_error", "") + return total, reported, cause + } + emitter := bridgeStreamEmitter(writer, flusher, Chat, state.model) + if emitErr := emitUnexpectedStreamError(emitter, cause); emitErr != nil { + return total, reported, emitErr + } + return total, reported, cause + } +} + +func closeResumeReader(reader io.Reader) { + if closer, ok := reader.(io.Closer); ok { + _ = closer.Close() + } +} + +func addResumeUsage(previous, segment Usage) Usage { + return Usage{ + Input: previous.Input + segment.Input, Output: previous.Output + segment.Output, + Total: previous.Total + segment.Total, Cached: previous.Cached + segment.Cached, + CacheCreation: previous.CacheCreation + segment.CacheCreation, Reasoning: previous.Reasoning + segment.Reasoning, + } +} + +func (state *resumeStreamState) forward(frame []byte) error { + var data string + err := readSSE(bytes.NewReader(frame), func(eventName, value string) error { + data = value + if eventName != "" && eventName != "message" { + state.resumable = false + if state.resumed { + return errors.New("continuation has an unsupported SSE event") + } + } + return nil + }) + if err != nil { + return err + } + if data == "" { + return state.write(frame) + } + if data == "[DONE]" { + if err := state.flushPending(); err != nil { + return err + } + return state.write(frame) + } + var payload map[string]any + if err := json.Unmarshal([]byte(data), &payload); err != nil { + return err + } + choices, valid := payload["choices"].([]any) + object := jsonutil.StringAt(payload, "object") + if !valid || len(choices) > 1 || len(choices) == 0 && len(jsonutil.MapAt(payload, "usage")) == 0 || jsonutil.StringAt(payload, "type") != "" || object != "" && object != "chat.completion.chunk" { + state.resumable = false + if state.resumed { + return errors.New("continuation is not a single-choice Chat stream") + } + } + var delta map[string]any + finished := false + if len(choices) == 1 { + choice, ok := choices[0].(map[string]any) + indexValid := true + if index, present := choice["index"]; present { + number, ok := index.(float64) + indexValid = ok && number == 0 + } + if !ok || !indexValid { + state.resumable = false + if state.resumed { + return errors.New("continuation has an unsupported Chat choice") + } + } + delta = jsonutil.MapAt(choice, "delta") + finished = jsonutil.StringAt(choice, "finish_reason") != "" + if stop, present := choice["finish_reason"]; present && stop != nil { + if _, ok := stop.(string); !ok { + state.resumable = false + if state.resumed { + return errors.New("continuation has an unsupported Chat finish reason") + } + } + } + if finished { + state.resumable = false + } + if delta == nil { + state.resumable = false + if state.resumed { + return errors.New("continuation has no Chat delta") + } + } + for key, value := range delta { + valid := true + switch key { + case "role", "content", "reasoning", "reasoning_content", "reasoning_signature", "signature": + if value != nil { + _, valid = value.(string) + } + case "tool_calls": + if value != nil { + _, valid = value.([]any) + } + case "function_call": + if value != nil { + _, valid = value.(map[string]any) + } + default: + valid = false + } + if !valid { + state.resumable = false + if state.resumed { + return errors.New("continuation has unsupported Chat delta fields") + } + } + } + if calls := jsonutil.SliceAt(delta, "tool_calls"); len(calls) > 0 { + state.toolSeen = true + } + if call := jsonutil.MapAt(delta, "function_call"); len(call) > 0 { + state.toolSeen = true + } + } + if !state.resumed { + if state.responseID == "" { + state.responseID = jsonutil.StringAt(payload, "id") + } + if model := jsonutil.StringAt(payload, "model"); model != "" && !state.modelCaptured { + state.model = model + state.modelCaptured = true + } + if state.created == nil { + state.created = payload["created"] + } + if err := state.write(frame); err != nil { + return err + } + state.record(delta) + return nil + } + if state.responseID != "" { + payload["id"] = state.responseID + } + if state.model != "" { + payload["model"] = state.model + } + if state.created != nil { + payload["created"] = state.created + } + delete(delta, "role") + delete(delta, "reasoning") + delete(delta, "reasoning_content") + delete(delta, "reasoning_signature") + delete(delta, "signature") + if usage := jsonutil.MapAt(payload, "usage"); len(usage) > 0 { + cumulative := addResumeUsage(state.previousUsage, state.observer.usage) + payload["usage"] = openAIUsage(cumulative) + if cumulative.CacheCreation > 0 { + payload["usage"].(map[string]any)["cache_creation_input_tokens"] = cumulative.CacheCreation + } + } + if len(choices) == 1 && !finished && len(delta) == 0 && len(jsonutil.MapAt(payload, "usage")) == 0 { + return nil + } + if !state.trimPending { + return state.deliver(payload) + } + state.pending = append(state.pending, payload) + state.pendingBytes += len(frame) + for _, character := range jsonutil.StringAt(delta, "content") { + if len(state.pendingText) >= maxResumeOverlapRunes { + break + } + state.pendingText = append(state.pendingText, character) + } + if len(state.pendingText) >= maxResumeOverlapRunes || len(state.pendingText) >= utf8.RuneCountInString(state.overlapTail) || state.pendingBytes >= 1<<20 || len(state.pending) >= 64 || state.toolSeen || finished { + return state.flushPending() + } + return nil +} + +func (state *resumeStreamState) flushPending() error { + state.trimPending = false + overlap := resumeOverlap(string(state.pendingText), state.overlapTail) + for _, payload := range state.pending { + choices := jsonutil.SliceAt(payload, "choices") + if len(choices) == 1 && overlap > 0 { + choice, _ := choices[0].(map[string]any) + delta := jsonutil.MapAt(choice, "delta") + text := jsonutil.StringAt(delta, "content") + for overlap > 0 && text != "" { + _, width := utf8.DecodeRuneInString(text) + text = text[width:] + overlap-- + } + if _, present := delta["content"]; present { + delta["content"] = text + } + } + if err := state.deliver(payload); err != nil { + state.pending = nil + state.pendingText = nil + state.pendingBytes = 0 + return err + } + } + state.pending = nil + state.pendingText = nil + state.pendingBytes = 0 + return nil +} + +func (state *resumeStreamState) deliver(payload map[string]any) error { + encoded, err := json.Marshal(payload) + if err != nil { + return err + } + frame := append([]byte("data: "), encoded...) + frame = append(frame, '\n', '\n') + if err := state.write(frame); err != nil { + return err + } + choices := jsonutil.SliceAt(payload, "choices") + if len(choices) == 1 { + choice, _ := choices[0].(map[string]any) + state.record(jsonutil.MapAt(choice, "delta")) + } + return nil +} + +func (state *resumeStreamState) record(delta map[string]any) { + text := jsonutil.StringAt(delta, "content") + reasoning := jsonutil.StringAt(delta, "reasoning_content") + if reasoning == "" { + reasoning = jsonutil.StringAt(delta, "reasoning") + } + if text != "" || reasoning != "" { + state.segmentDelivered = true + } + if len(text) > maxResumePartialBytes-state.text.Len() || len(reasoning) > maxResumePartialBytes-state.reasoning.Len() { + state.partialTooLarge = true + return + } + state.text.WriteString(text) + state.reasoning.WriteString(reasoning) +} + +func (state *resumeStreamState) write(frame []byte) error { + written, err := state.writer.Write(frame) + if err == nil && written != len(frame) { + err = io.ErrShortWrite + } + if err != nil { + return &ClientWriteError{Err: err} + } + state.committed = true + state.flusher.Flush() + return nil +} + +func resumeTextTail(text string) string { + start := len(text) + for count := 0; start > 0 && count < maxResumeOverlapRunes; count++ { + _, width := utf8.DecodeLastRuneInString(text[:start]) + start -= width + } + return text[start:] +} + +func resumeOverlap(text, tail string) int { + prefix, suffix := []rune(text), []rune(tail) + for length := min(len(prefix), len(suffix), maxResumeOverlapRunes); length >= 4; length-- { + if string(prefix[:length]) == string(suffix[len(suffix)-length:]) { + return length + } + } + return 0 +} diff --git a/webui/index.html b/webui/index.html index 524d578..9f07597 100644 --- a/webui/index.html +++ b/webui/index.html @@ -1059,6 +1059,23 @@ +
+ +

+ 仅 Chat → Chat;工具调用、取消或上游错误后不续传。每段独立计时,Token 用量累加,可能增加请求成本。 +

+
+
+ + +
+
+ + +
diff --git a/webui/js/i18n.js b/webui/js/i18n.js index f33c694..2b65baf 100644 --- a/webui/js/i18n.js +++ b/webui/js/i18n.js @@ -345,6 +345,10 @@ const DICTIONARY = { "config.upstream.activeProbes": "Enable active background probes for free models (disabled by default to save quota)", "config.upstream.attempts": "Max attempts per Key Tier", "config.upstream.timeout": "Request timeout (seconds)", + "config.upstream.streamResume": "Continue interrupted anonymous Chat text streams (off by default)", + "config.upstream.streamResumeHint": "Chat → Chat only; no continuation after tools, cancellation, or upstream errors. Each segment has a separate deadline; token usage is summed and may increase request costs.", + "config.upstream.streamResumeAttempts": "Maximum continuation segments", + "config.upstream.streamResumeTimeout": "Total timeout per continuation segment (seconds)", "config.upstream.refresh": "Model refresh interval (seconds)", "config.upstream.protocols": "Model protocol overrides (JSON)", "config.upstream.aliases": "Public model aliases (JSON: public name → upstream ID)", @@ -975,6 +979,10 @@ const DICTIONARY = { "config.upstream.activeProbes": "Bật probe chủ động ngầm cho mô hình miễn phí (mặc định tắt để tiết kiệm hạn mức)", "config.upstream.attempts": "Số lần thử tối đa cho mỗi Key Tier", "config.upstream.timeout": "Timeout của request (giây)", + "config.upstream.streamResume": "Tiếp tục luồng Chat ẩn danh bị ngắt (mặc định tắt)", + "config.upstream.streamResumeHint": "Chỉ Chat → Chat; không tiếp tục sau công cụ, hủy hoặc lỗi upstream. Mỗi đoạn có thời hạn riêng; token được cộng dồn và có thể tăng chi phí.", + "config.upstream.streamResumeAttempts": "Số đoạn tiếp tục tối đa", + "config.upstream.streamResumeTimeout": "Tổng thời hạn mỗi đoạn tiếp tục (giây)", "config.upstream.refresh": "Làm mới mô hình (giây)", "config.upstream.protocols": "Ghi đè giao thức mô hình (JSON)", "config.upstream.aliases": "Bí danh mô hình (JSON: tên công khai → ID upstream)", @@ -1570,6 +1578,10 @@ const DICTIONARY = { "Abilita i probe attivi in background per i modelli gratuiti (disabilitato per impostazione predefinita)", "config.upstream.attempts": "Tentativi massimi per Key Tier", "config.upstream.timeout": "Timeout richiesta (secondi)", + "config.upstream.streamResume": "Continua gli stream Chat anonimi interrotti (disattivato per impostazione predefinita)", + "config.upstream.streamResumeHint": "Solo Chat → Chat; nessuna continuazione dopo strumenti, annullamento o errori upstream. Ogni segmento ha una scadenza separata; i token vengono sommati e i costi possono aumentare.", + "config.upstream.streamResumeAttempts": "Segmenti di continuazione massimi", + "config.upstream.streamResumeTimeout": "Timeout totale per segmento di continuazione (secondi)", "config.upstream.refresh": "Intervallo di refresh modelli (secondi)", "config.upstream.protocols": "Override protocollo modello (JSON)", "config.upstream.aliases": "Alias pubblici (JSON: nome pubblico → ID upstream)", diff --git a/webui/js/pages/config.js b/webui/js/pages/config.js index d9d9288..7b504ad 100644 --- a/webui/js/pages/config.js +++ b/webui/js/pages/config.js @@ -103,6 +103,9 @@ function fillConfig(value) { $("#c-up-go").value = value.upstream.go; $("#c-attempts").value = value.retry.max_attempts; $("#c-timeout").value = value.retry.timeout_seconds; + $("#c-stream-resume").checked = !!value.retry.stream_resume_enabled; + $("#c-stream-resume-attempts").value = value.retry.stream_resume_max_attempts || 1; + $("#c-stream-resume-timeout").value = value.retry.stream_resume_timeout || 60; $("#c-refresh").value = value.models.refresh_seconds; $("#c-protocols").value = JSON.stringify(value.models.protocols || {}, null, 2); $("#c-model-aliases").value = JSON.stringify(value.models.aliases || {}, null, 2); @@ -170,7 +173,14 @@ async function save(event) { proxyfile: $("#c-proxyfile").value, prefer: $("#c-prefer").value, upstream: { ...current.upstream, zen: $("#c-up-zen").value, go: $("#c-up-go").value }, - retry: { max_attempts: numberValue("#c-attempts"), timeout_seconds: numberValue("#c-timeout") }, + retry: { + ...current.retry, + max_attempts: numberValue("#c-attempts"), + timeout_seconds: numberValue("#c-timeout"), + stream_resume_enabled: $("#c-stream-resume").checked, + stream_resume_max_attempts: numberValue("#c-stream-resume-attempts"), + stream_resume_timeout: numberValue("#c-stream-resume-timeout"), + }, models: { ...current.models, refresh_seconds: numberValue("#c-refresh"),