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 }