Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.
openai: accept foreign compaction in Responses history (#19003)
Eva H678722224b3d
diff --git a/openai/responses.go b/openai/responses.goindex a9fb61dea..0a88f8b8d 100644--- a/openai/responses.go+++ b/openai/responses.go@@ -611,12 +611,47 @@ func FromResponsesRequest(r ResponsesRequest, thinking ...*model.Thinking) (*api// Handle array of input items// Track pending reasoning to merge with the next assistant messagevar pendingThinking string+ flushThinking := func() {+ if pendingThinking == "" {+ return+ }+ if len(messages) > 0 && messages[len(messages)-1].Role == "assistant" && len(messages[len(messages)-1].ToolCalls) > 0 {+ last := &messages[len(messages)-1]+ if last.Thinking != "" {+ last.Thinking += "\n"+ }+ last.Thinking += pendingThinking+ } else {+ messages = append(messages, api.Message{Role: "assistant", Thinking: pendingThinking})+ }+ pendingThinking = ""+ }for i, item := range r.Input.Items {+ switch v := item.(type) {+ case ResponsesInputMessage:+ if v.Role != "assistant" {+ flushThinking()+ }+ case ResponsesReasoningInput, ResponsesWebSearchCall, ResponsesFunctionCall, ResponsesToolSearchCall:+ // These items can carry the preceding reasoning.+ default:+ flushThinking()+ }switch v := item.(type) {case ResponsesReasoningInput:- // Store thinking to merge with the next assistant message- pendingThinking = v.EncryptedContent+ // Ollama writes the same text to summary and encrypted_content. Only+ // the summary is portable; another provider's ciphertext is opaque.+ var parts []string+ for _, part := range v.Summary {+ parts = append(parts, part.Text)+ }+ if summary := strings.Join(parts, "\n"); summary != "" {+ if pendingThinking != "" {+ pendingThinking += "\n"+ }+ pendingThinking += summary+ }case ResponsesAgentMessageInput:content, _, err := convertResponsesContent(v.Content)if err != nil {@@ -659,7 +694,10 @@ func FromResponsesRequest(r ResponsesRequest, thinking ...*model.Thinking) (*apilastMsg.Content += msg.ContentlastMsg.Images = append(lastMsg.Images, msg.Images...)if msg.Thinking != "" {- lastMsg.Thinking = msg.Thinking+ if lastMsg.Thinking != "" {+ lastMsg.Thinking += "\n"+ }+ lastMsg.Thinking += msg.Thinking}merged = truebreak@@ -750,13 +788,7 @@ func FromResponsesRequest(r ResponsesRequest, thinking ...*model.Thinking) (*api}}- // If there's trailing reasoning without a following message, emit it- if pendingThinking != "" {- messages = append(messages, api.Message{- Role: "assistant",- Thinking: pendingThinking,- })- }+ flushThinking()options := make(map[string]any)@@ -859,7 +891,10 @@ func appendResponseToolCall(messages []api.Message, toolCall api.ToolCall, pendilast := &messages[len(messages)-1]last.ToolCalls = append(last.ToolCalls, toolCall)if *pendingThinking != "" {- last.Thinking = *pendingThinking+ if last.Thinking != "" {+ last.Thinking += "\n"+ }+ last.Thinking += *pendingThinking*pendingThinking = ""}return messagesdiff --git a/openai/responses_compact.go b/openai/responses_compact.goindex 0f516b72e..e5254ef49 100644--- a/openai/responses_compact.go+++ b/openai/responses_compact.go@@ -163,9 +163,9 @@ func PrepareStandaloneCompaction(body []byte) (*ResponsesCompactionPlan, error)return newResponsesCompactionPlan(req, items)}-// ExpandResponsesCompactionInput replaces the newest Ollama compaction item-// with its summary and retained messages. Items on either side of the-// compaction item remain in their original order.+// ExpandResponsesCompactionInput omits foreign compaction state and replaces the+// newest Ollama compaction item with its summary and retained messages. Other+// input items remain in their original order.func ExpandResponsesCompactionInput(body []byte) ([]byte, bool, error) {req, items, err := decodeRawResponsesRequest(body)if err != nil {@@ -176,12 +176,12 @@ func ExpandResponsesCompactionInput(body []byte) ([]byte, bool, error) {return body, changed, err}- input, err := json.Marshal(items)+ input, err := marshalCompactionInput(items)if err != nil {return nil, false, err}req.Fields["input"] = input- rewritten, err := json.Marshal(req.Fields)+ rewritten, err := marshalCompactionInput(req.Fields)return rewritten, true, err}@@ -267,21 +267,68 @@ func expandOllamaCompactionItems(items []json.RawMessage) ([]json.RawMessage, boreturn items, false, nil}- payload, err := decodeOllamaCompactionItem(items[boundary])- if err != nil {- return nil, false, err+ retained := make([]json.RawMessage, 0, len(items))+ var payload OllamaCompactionPayload+ boundary = -1+ for _, item := range items {+ if rawInputItemType(item) == "compaction" {+ var wire ResponsesCompactionItem+ if err := json.Unmarshal(item, &wire); err != nil {+ return nil, false, fmt.Errorf("invalid compaction item: %w", err)+ }+ if isForeignCompactionItem(wire) {+ continue+ }+ var err error+ payload, err = decodeOllamaCompactionItem(item)+ if err != nil {+ return nil, false, err+ }+ // The newest Ollama summary supersedes earlier Ollama summaries.+ boundary = len(retained)+ continue+ }+ retained = append(retained, item)}+ if boundary < 0 {+ if len(retained) == 0 {+ return nil, false, errors.New("input contains no items after removing foreign compaction state; resend conversation history")+ }+ return retained, true, nil+ }+expanded, err := payloadToResponsesItems(payload)if err != nil {return nil, false, err}- rewritten := make([]json.RawMessage, 0, len(items)-1+len(expanded))- rewritten = append(rewritten, items[:boundary]...)+ rewritten := make([]json.RawMessage, 0, len(retained)+len(expanded))+ rewritten = append(rewritten, retained[:boundary]...)rewritten = append(rewritten, expanded...)- rewritten = append(rewritten, items[boundary+1:]...)+ rewritten = append(rewritten, retained[boundary:]...)return rewritten, true, nil}+// Only a successfully parsed discriminator identifies native state. Its version+// and fields are validated by decodeOllamaCompactionItem.+func isForeignCompactionItem(item ResponsesCompactionItem) bool {+ var payload struct {+ Type string `json:"type"`+ }+ return json.Unmarshal([]byte(item.EncryptedContent), &payload) != nil || payload.Type != OllamaCompactionPayloadType+}++// Preserve literal HTML-sensitive characters in client input and other fields+// when rewriting a request for local conversion or cloud forwarding.+func marshalCompactionInput(value any) ([]byte, error) {+ var buf bytes.Buffer+ encoder := json.NewEncoder(&buf)+ encoder.SetEscapeHTML(false)+ if err := encoder.Encode(value); err != nil {+ return nil, err+ }+ return bytes.TrimSuffix(buf.Bytes(), []byte("\n")), nil+}+func decodeOllamaCompactionItem(item json.RawMessage) (OllamaCompactionPayload, error) {var wire ResponsesCompactionItemif err := json.Unmarshal(item, &wire); err != nil {diff --git a/openai/responses_compact_foreign_test.go b/openai/responses_compact_foreign_test.gonew file mode 100644index 000000000..3705de621--- /dev/null+++ b/openai/responses_compact_foreign_test.go@@ -0,0 +1,174 @@+package openai++import (+ "bytes"+ "encoding/json"+ "reflect"+ "strings"+ "testing"+)++func TestResponsesForeignCompactionPreservesReadableHistory(t *testing.T) {+ for _, encrypted := range []string{+ "opaque-provider-state",+ `{"type":"other_provider","summary":"must not become instructions"}`,+ `{"type":42,"state":"opaque"}`,+ `{"type":{"provider":"other"},"state":"opaque"}`,+ "", " ",+ `{"summary":"no discriminator"}`,+ `{"type":"ollama_compaction","version":1,"summary":"truncated"`,+ `{"broken":,"type":"ollama_compaction"}`,+ `{"type":"ollama_compaction","version":1,"summary":"valid"} {}`,+ "\ufeff" + `{"type":"ollama_compaction","version":1,"summary":"native-looking"}`,+ } {+ t.Run(encrypted, func(t *testing.T) {+ visible := []json.RawMessage{+ json.RawMessage(`{"role":"user","content":"Remember kiwi-42"}`),+ json.RawMessage(`{"type":"custom_tool_call","call_id":"call_1","namespace":"workspace.tools","name":"read","input":"notes.txt"}`),+ json.RawMessage(`{"type":"custom_tool_call_output","call_id":"call_1","output":"kiwi-42"}`),+ json.RawMessage(`{"role":"user","content":"What was the code?"}`),+ }+ foreign, err := json.Marshal(ResponsesCompactionItem{Type: "compaction", EncryptedContent: encrypted})+ if err != nil {+ t.Fatal(err)+ }+ input := []json.RawMessage{visible[0], foreign, visible[1], foreign, visible[2], visible[3]}+ body, err := json.Marshal(map[string]any{+ "model": "test", "input": input,+ })+ if err != nil {+ t.Fatal(err)+ }++ rewritten, changed, err := ExpandResponsesCompactionInput(body)+ if err != nil || !changed {+ t.Fatalf("expand: changed=%v err=%v", changed, err)+ }+ var expanded struct {+ Input []json.RawMessage `json:"input"`+ }+ if err := json.Unmarshal(rewritten, &expanded); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(expanded.Input, visible) {+ t.Fatalf("readable history changed: %s", rewritten)+ }+ })+ }+}++func TestResponsesForeignAndOllamaCompaction(t *testing.T) {+ body, err := json.Marshal(map[string]any{"model": "test", "input": []any{+ ResponsesCompactionItem{Type: "compaction", EncryptedContent: `{"type":"ollama_compaction","version":1,"summary":"superseded summary"}`},+ ResponsesCompactionItem{Type: "compaction", EncryptedContent: "foreign-before"},+ map[string]any{"role": "user", "content": "retained prefix"},+ ResponsesCompactionItem{Type: "compaction", EncryptedContent: `{"type":"ollama_compaction","version":1,"summary":"The retained code is kiwi-42."}`},+ ResponsesCompactionItem{Type: "compaction", EncryptedContent: "foreign-after"},+ map[string]any{"role": "user", "content": "continue"},+ }})+ if err != nil {+ t.Fatal(err)+ }+ expanded, changed, err := ExpandResponsesCompactionInput(body)+ if err != nil || !changed {+ t.Fatalf("expand: changed=%v err=%v", changed, err)+ }+ var request ResponsesRequest+ if err := json.Unmarshal(expanded, &request); err != nil {+ t.Fatal(err)+ }+ chat, err := FromResponsesRequest(request)+ if err != nil {+ t.Fatal(err)+ }+ if len(chat.Messages) != 4 || chat.Messages[0].Content != "retained prefix" || chat.Messages[2].Content != "The retained code is kiwi-42." || chat.Messages[3].Content != "continue" {+ t.Fatalf("messages=%+v", chat.Messages)+ }+}++func TestResponsesCompactionRejectsInvalidNativeState(t *testing.T) {+ for _, payload := range []string{+ `{"type":"ollama_compaction","version":2,"summary":"future"}`,+ `{"Type":"ollama_compaction","version":2,"summary":"future"}`,+ `{"type":"ollama_compaction","summary":"missing version"}`,+ `{"type":"ollama_compaction","version":"1","summary":"invalid version"}`,+ `{"type":"ollama_compaction","version":1,"summary":""}`,+ `{"type":"ollama_compaction","version":1,"summary":42}`,+ `{"type":"ollama_compaction","version":1,"summary":"valid","unknown":true}`,+ `{"type":"ollama_compaction","version":1,"summary":"valid","retained":"invalid"}`,+ } {+ t.Run(payload, func(t *testing.T) {+ input := []any{+ map[string]any{"role": "user", "content": "continue"},+ ResponsesCompactionItem{Type: "compaction", EncryptedContent: payload},+ ResponsesCompactionItem{Type: "compaction", EncryptedContent: "foreign-after"},+ }+ body, err := json.Marshal(map[string]any{"model": "test", "input": input})+ if err != nil {+ t.Fatal(err)+ }+ if _, _, err := ExpandResponsesCompactionInput(body); err == nil {+ t.Fatal("invalid native compaction was accepted")+ }+ if _, err := PrepareStandaloneCompaction(body); err == nil {+ t.Fatal("standalone compaction accepted invalid native state")+ }+ triggered, err := json.Marshal(map[string]any{"model": "test", "stream": true, "input": append(input, ResponsesCompactionTrigger{Type: "compaction_trigger"})})+ if err != nil {+ t.Fatal(err)+ }+ if _, requested, err := PrepareTriggeredCompaction(triggered); !requested || err == nil {+ t.Fatalf("triggered compaction: requested=%v err=%v", requested, err)+ }+ })+ }+}++func TestResponsesInputCompactionRequiresExpansion(t *testing.T) {+ var request ResponsesRequest+ if err := json.Unmarshal([]byte(`{"model":"test","input":[{"type":"compaction","encrypted_content":"foreign"},{"role":"user","content":"continue"}]}`), &request); err != nil {+ t.Fatal(err)+ }+ if len(request.Input.Items) != 2 {+ t.Fatalf("parsing expanded compaction: %+v", request.Input.Items)+ }+ if _, err := FromResponsesRequest(request); err == nil || !strings.Contains(err.Error(), "must be expanded") {+ t.Fatalf("conversion must require expansion, got %v", err)+ }+}++func TestResponsesCompactionPreservesHTMLCharacters(t *testing.T) {+ body := []byte(`{"model":"test","instructions":"<system> A & B </system>","tools":[{"type":"function","name":"run","parameters":{"description":"x < y && y > z"}}],"input":[{"type":"compaction","encrypted_content":"foreign"},{"role":"user","content":"<tag> A & B </tag>"},{"type":"function_call","call_id":"call_1","name":"run","arguments":"{\"command\":\"a < b && c > d\"}"}]}`)+ expanded, changed, err := ExpandResponsesCompactionInput(body)+ if err != nil || !changed {+ t.Fatalf("expand: changed=%v err=%v", changed, err)+ }+ for _, escape := range []string{`\u003c`, `\u003e`, `\u0026`} {+ if bytes.Contains(expanded, []byte(escape)) {+ t.Errorf("HTML character escaped: %s", expanded)+ }+ }+ var before, after map[string]json.RawMessage+ if err := json.Unmarshal(body, &before); err != nil {+ t.Fatal(err)+ }+ if err := json.Unmarshal(expanded, &after); err != nil {+ t.Fatal(err)+ }+ var input []json.RawMessage+ if err := json.Unmarshal(before["input"], &input); err != nil {+ t.Fatal(err)+ }+ var retained []json.RawMessage+ if err := json.Unmarshal(after["input"], &retained); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(retained, input[1:]) {+ t.Fatalf("retained input changed: %s", expanded)+ }+ delete(before, "input")+ delete(after, "input")+ if !reflect.DeepEqual(after, before) {+ t.Fatalf("request fields changed: %s", expanded)+ }+}diff --git a/openai/responses_compact_test.go b/openai/responses_compact_test.goindex b0f1a4fbd..a6efa8e1d 100644--- a/openai/responses_compact_test.go+++ b/openai/responses_compact_test.go@@ -839,11 +839,35 @@ func TestExpandResponsesCompactionInputPreservesCodexRetainedPrefix(t *testing.T}}-func TestExpandResponsesCompactionInputRejectsForeignPayload(t *testing.T) {- body := []byte(`{"model":"test","input":[{"type":"compaction","encrypted_content":"opaque-provider-state"}]}`)- _, changed, err := ExpandResponsesCompactionInput(body)- if changed || err == nil || !strings.Contains(err.Error(), "not an Ollama payload") {- t.Fatalf("changed=%v err=%v", changed, err)+// Accepting retained items does not mean a foreign checkpoint was recovered.+// Each destination is responsible for validating the retained item schemas.+func TestExpandResponsesCompactionInputRequiresRemainingItems(t *testing.T) {+ for _, tt := range []struct {+ name string+ remaining string+ wantErr bool+ }{+ {"no remaining items", "", true},+ {"only foreign checkpoints", `,{"type":"compaction","encrypted_content":"other-provider"}`, true},+ {"Codex retained user", `,{"role":"user","content":"continue"}`, false},+ {"search metadata only", `,{"type":"web_search_call","id":"ws_1","status":"completed"}`, false},+ {"encrypted reasoning only", `,{"type":"reasoning","summary":[],"encrypted_content":"opaque"}`, false},+ {"empty message", `,{"role":"user","content":" "}`, false},+ {"empty routed agent message", `,{"type":"agent_message","author":"worker","recipient":"root","content":[]}`, false},+ {"orphan empty tool result", `,{"type":"function_call_output","call_id":"missing-call","output":""}`, false},+ {"incomplete tool definition", `,{"type":"tool_search_output","tools":[{}]}`, false},+ {"provider call", `,{"type":"shell_call","call_id":"call_1","action":{"commands":["true"]}}`, false},+ } {+ t.Run(tt.name, func(t *testing.T) {+ body := []byte(`{"model":"test","input":[{"type":"compaction","encrypted_content":"opaque-provider-state"}` + tt.remaining + `]}`)+ _, changed, err := ExpandResponsesCompactionInput(body)+ if (err != nil) != tt.wantErr || changed == tt.wantErr {+ t.Errorf("expand: changed=%v err=%v, wantErr=%v", changed, err, tt.wantErr)+ }+ if tt.wantErr && (err == nil || !strings.Contains(err.Error(), "resend conversation history")) {+ t.Errorf("expected empty-history recovery error, got %v", err)+ }+ })}}@@ -915,7 +939,8 @@ func TestCompactionMessageAgentMessage(t *testing.T) {"recipient": "/root/worker","content": [{"type": "input_text", "text": "Message Type: NEW_TASK\nPayload:\n"},- {"type": "encrypted_content", "encrypted_content": "analyze the parser"}+ {"type": "encrypted_content", "encrypted_content": "analyze the parser"},+ {"type": "input_image", "image_url": "data:image/png;base64,Zml4dHVyZQ=="}]}`), &item)if err != nil {@@ -928,7 +953,7 @@ func TestCompactionMessageAgentMessage(t *testing.T) {}want := AgentMessageEnvelopeFormat + "Message Type: NEW_TASK\nPayload:\nanalyze the parser"want = fmt.Sprintf(want, "/root", "/root/worker")- if kind != "message" || msg.Role != "user" || msg.Content != want {+ if kind != "message" || msg.Role != "user" || msg.Content != want || len(msg.Images) != 0 {t.Fatalf("kind=%q msg=%#v", kind, msg)}}diff --git a/openai/responses_test.go b/openai/responses_test.goindex 0b09cc57b..1d69c4c66 100644--- a/openai/responses_test.go+++ b/openai/responses_test.go@@ -2,6 +2,7 @@ package openaiimport ("encoding/json"+ "reflect""strings""testing""time"@@ -1716,7 +1717,7 @@ func TestFromResponsesRequest_FunctionCallMerge(t *testing.T) {"model": "gpt-oss:20b","input": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "think and act"}]},- {"type": "reasoning", "id": "rs_1", "encrypted_content": "Let me think...", "summary": []},+ {"type": "reasoning", "id": "rs_1", "encrypted_content": "Let me think...", "summary": [{"type":"summary_text","text":"Let me think..."}]},{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "I thought about it."}]},{"type": "function_call", "call_id": "call_1", "name": "do_thing", "arguments": "{}"}]@@ -1761,7 +1762,7 @@ func TestFromResponsesRequest_FunctionCallMerge(t *testing.T) {"model": "gpt-oss:20b","input": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "complex task"}]},- {"type": "reasoning", "id": "rs_1", "encrypted_content": "Thinking first...", "summary": []},+ {"type": "reasoning", "id": "rs_1", "encrypted_content": "Thinking first...", "summary": [{"type":"summary_text","text":"Thinking first..."}]},{"type": "message", "role": "assistant", "content": ""},{"type": "function_call", "call_id": "call_1", "name": "think_action", "arguments": "{}"},{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "Now doing more."}]},@@ -2116,6 +2117,73 @@ func TestResponsesStreamConverter_Reasoning(t *testing.T) {}func TestFromResponsesRequest_ReasoningMerge(t *testing.T) {+ t.Run("web search carries consecutive reasoning into the answer", func(t *testing.T) {+ for _, encrypted := range []string{"first thought", "opaque-provider-reasoning"} {+ request := ResponsesRequest{Input: ResponsesInput{Items: []ResponsesInputItem{+ ResponsesInputMessage{Role: "user", Content: []ResponsesContent{ResponsesTextContent{Type: "input_text", Text: "search"}}},+ ResponsesReasoningInput{EncryptedContent: encrypted, Summary: []ResponsesReasoningSummary{{Type: "summary_text", Text: "first thought"}}},+ ResponsesWebSearchCall{Type: "web_search_call"},+ ResponsesReasoningInput{Summary: []ResponsesReasoningSummary{{Type: "summary_text", Text: "second thought"}, {Type: "summary_text", Text: "third thought"}}},+ ResponsesReasoningInput{EncryptedContent: "opaque-without-summary"},+ ResponsesInputMessage{Role: "assistant", Content: []ResponsesContent{ResponsesTextContent{Type: "input_text", Text: "the answer"}}},+ }}}+ chat, err := FromResponsesRequest(request)+ if err != nil {+ t.Fatal(err)+ }+ want := []api.Message{{Role: "user", Content: "search"}, {Role: "assistant", Content: "the answer", Thinking: "first thought\nsecond thought\nthird thought"}}+ if !reflect.DeepEqual(chat.Messages, want) {+ t.Fatalf("messages=%+v, want=%+v", chat.Messages, want)+ }+ }+ })++ t.Run("reasoning preserves a pending tool pair", func(t *testing.T) {+ for _, assistant := range []string{"", `,{"role":"assistant","content":"Checking the result"}`} {+ var req ResponsesRequest+ body := `{"model":"test","input":[+ {"type":"reasoning","encrypted_content":"first native thought","summary":[{"type":"summary_text","text":"first native thought"}]},+ {"type":"function_call","call_id":"call_1","name":"shell","arguments":"{}"},+ {"type":"reasoning","summary":[{"type":"summary_text","text":"Remember kiwi-42"}],"encrypted_content":"opaque"}` + assistant + `,+ {"type":"function_call_output","call_id":"call_1","output":"done"}+ ]}`+ if err := json.Unmarshal([]byte(body), &req); err != nil {+ t.Fatal(err)+ }+ chat, err := FromResponsesRequest(req)+ if err != nil {+ t.Fatal(err)+ }+ if len(chat.Messages) != 2 || len(chat.Messages[0].ToolCalls) != 1 || chat.Messages[0].ToolCalls[0].ID != "call_1" || chat.Messages[1].ToolCallID != "call_1" {+ t.Fatalf("tool pair split: %+v", chat.Messages)+ }+ if strings.Contains(chat.Messages[0].Content, "Remember kiwi-42") || chat.Messages[0].Thinking != "first native thought\nRemember kiwi-42" {+ t.Fatalf("reasoning lost: %+v", chat.Messages[0])+ }+ if assistant != "" && !strings.Contains(chat.Messages[0].Content, "Checking the result") {+ t.Fatalf("assistant text lost: %+v", chat.Messages[0])+ }+ }+ })+ t.Run("successive calls preserve both reasoning items", func(t *testing.T) {+ var req ResponsesRequest+ if err := json.Unmarshal([]byte(`{"model":"test","input":[+ {"type":"reasoning","encrypted_content":"first native thought","summary":[{"type":"summary_text","text":"first native thought"}]},+ {"type":"function_call","call_id":"call_1","name":"first","arguments":"{}"},+ {"type":"reasoning","summary":[{"type":"summary_text","text":"second readable thought"}]},+ {"type":"function_call","call_id":"call_2","name":"second","arguments":"{}"}+ ]}`), &req); err != nil {+ t.Fatal(err)+ }+ chat, err := FromResponsesRequest(req)+ if err != nil {+ t.Fatal(err)+ }+ if len(chat.Messages) != 1 || len(chat.Messages[0].ToolCalls) != 2 || chat.Messages[0].Thinking != "first native thought\nsecond readable thought" || chat.Messages[0].Content != "" {+ t.Fatalf("reasoning or tool calls lost: %+v", chat.Messages)+ }+ })+t.Run("reasoning merged with following message", func(t *testing.T) {reqJSON := `{"model": "qwen3",@@ -2154,8 +2222,8 @@ func TestFromResponsesRequest_ReasoningMerge(t *testing.T) {if assistantMsg.Content != "The answer is 4" {t.Errorf("Messages[1].Content = %q, want %q", assistantMsg.Content, "The answer is 4")}- if assistantMsg.Thinking != "Let me think about this math problem..." {- t.Errorf("Messages[1].Thinking = %q, want %q", assistantMsg.Thinking, "Let me think about this math problem...")+ if assistantMsg.Thinking != "Thinking about math" {+ t.Errorf("Messages[1].Thinking = %q, want %q", assistantMsg.Thinking, "Thinking about math")}})@@ -2164,7 +2232,7 @@ func TestFromResponsesRequest_ReasoningMerge(t *testing.T) {"model": "qwen3","input": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "what is the weather?"}]},- {"type": "reasoning", "id": "rs_123", "encrypted_content": "I need to call a tool for this...", "summary": []},+ {"type": "reasoning", "id": "rs_123", "encrypted_content": "I need to call a tool for this...", "summary": [{"type":"summary_text","text":"I need to call a tool for this..."}]},{"type": "function_call", "call_id": "call_abc", "name": "get_weather", "arguments": "{\"city\":\"Paris\"}"}]}`@@ -2243,8 +2311,8 @@ func TestFromResponsesRequest_ReasoningMerge(t *testing.T) {if chatReq.Messages[1].Content != "The answer is 4." {t.Errorf("Messages[1].Content = %q, want \"The answer is 4.\"", chatReq.Messages[1].Content)}- if chatReq.Messages[1].Thinking != "This is a simple arithmetic problem. 2+2=4." {- t.Errorf("Messages[1].Thinking = %q, want \"This is a simple arithmetic problem. 2+2=4.\"",+ if chatReq.Messages[1].Thinking != "Calculating 2+2" {+ t.Errorf("Messages[1].Thinking = %q, want \"Calculating 2+2\"",chatReq.Messages[1].Thinking)}@@ -2261,10 +2329,10 @@ func TestFromResponsesRequest_ReasoningMerge(t *testing.T) {"model": "qwen3","input": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "What is the weather in Paris?"}]},- {"type": "reasoning", "id": "rs_001", "encrypted_content": "I need to call the weather API for Paris.", "summary": []},+ {"type": "reasoning", "id": "rs_001", "encrypted_content": "I need to call the weather API for Paris.", "summary": [{"type":"summary_text","text":"I need to call the weather API for Paris."}]},{"type": "function_call", "call_id": "call_abc", "name": "get_weather", "arguments": "{\"city\":\"Paris\"}"},{"type": "function_call_output", "call_id": "call_abc", "output": "Sunny, 72°F"},- {"type": "reasoning", "id": "rs_002", "encrypted_content": "The weather API returned sunny and 72°F. I should format this nicely.", "summary": []},+ {"type": "reasoning", "id": "rs_002", "encrypted_content": "The weather API returned sunny and 72°F. I should format this nicely.", "summary": [{"type":"summary_text","text":"The weather API returned sunny and 72°F. I should format this nicely."}]},{"type": "message", "role": "assistant", "content": [{"type": "input_text", "text": "It's sunny and 72°F in Paris!"}]},{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "What about London?"}]}]@@ -2335,7 +2403,7 @@ func TestFromResponsesRequest_ReasoningMerge(t *testing.T) {"model": "qwen3","input": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "think about this"}]},- {"type": "reasoning", "id": "rs_123", "encrypted_content": "Still thinking...", "summary": []}+ {"type": "reasoning", "id": "rs_123", "encrypted_content": "Still thinking...", "summary": [{"type":"summary_text","text":"Still thinking..."}]}]}`diff --git a/server/responses_compact_test.go b/server/responses_compact_test.goindex 29f5aad85..b67f23cdf 100644--- a/server/responses_compact_test.go+++ b/server/responses_compact_test.go@@ -16,8 +16,11 @@ import ("github.com/gin-gonic/gin"+ "github.com/ollama/ollama/api""github.com/ollama/ollama/internal/proxy"+ "github.com/ollama/ollama/middleware""github.com/ollama/ollama/openai"+ "github.com/ollama/ollama/types/model")func TestIsCompactionContextLimit(t *testing.T) {@@ -654,3 +657,361 @@ func TestResponsesCompactionPayloadIsExpandedBeforeCloudPassthrough(t *testing.Tt.Fatalf("expanded state is incomplete: %s", forwarded)}}++func TestResponsesForeignCompactionCloudForwarding(t *testing.T) {+ for _, tt := range []struct {+ name string+ items []string+ }{+ {"metadata only", nil},+ {"retained user", []string{`{"role":"user","content":"continue"}`}},+ {"incomplete tool definition", []string{`{"type":"tool_search_output","tools":[{}]}`}},+ {"image URL", []string{`{"role":"user","content":[{"type":"input_image","image_url":"https://example.invalid/image.png","detail":"high"}]}`}},+ {"image file ID", []string{`{"role":"user","content":[{"type":"input_image","file_id":"file-fixture"}]}`}},+ {"file with text", []string{`{"role":"user","content":[{"type":"input_text","text":"Read the file"},{"type":"input_file","file_id":"file-fixture","filename":"notes.txt"}]}`}},+ {"reasoning summary", []string{`{"type":"reasoning","summary":[{"type":"summary_text","text":"Remember kiwi-42"}],"encrypted_content":"opaque-reasoning-state"}`}},+ {"provider tool with text", []string{+ `{"role":"user","content":"Continue from this computer action"}`,+ `{"type":"computer_call","call_id":"call_1","action":{"type":"click","x":10,"y":20}}`,+ }},+ {"provider content with text", []string{`{"role":"user","content":[{"type":"input_text","text":"Transcribe this audio"},{"type":"input_audio","input_audio":{"data":"fixture","format":"wav"}}]}`}},+ {"provider tool output with text", []string{`{"type":"function_call_output","call_id":"call_1","output":[{"type":"input_text","text":"Recorded kiwi-42"},{"type":"input_audio","input_audio":{"data":"fixture","format":"wav"}}]}`}},+ {"audio only", []string{`{"role":"user","content":[{"type":"input_audio","input_audio":{"data":"Zml4dHVyZQ==","format":"wav"}}]}`}},+ {"audio tool output", []string{`{"type":"function_call_output","call_id":"call_1","output":[{"type":"input_audio","input_audio":{"data":"Zml4dHVyZQ==","format":"wav"}}]}`}},+ {"provider tool result", []string{+ `{"type":"local_shell_call","call_id":"call_1","action":{"type":"exec","command":["pwd"]}}`,+ `{"type":"local_shell_call_output","call_id":"call_1","output":"/workspace"}`,+ }},+ {"computer screenshot", []string{`{"type":"computer_call_output","call_id":"call_1","output":{"type":"computer_screenshot","image_url":"data:image/png;base64,Zml4dHVyZQ=="}}`}},+ {"shell output", []string{`{"type":"shell_call_output","call_id":"call_1","output":[{"stdout":"kiwi-42\n","stderr":"","outcome":{"type":"exit","exit_code":0}}]}`}},+ {"shell pair with empty result", []string{+ `{"type":"shell_call","id":"sc_1","call_id":"call_1","status":"completed","action":{"commands":["true"]}}`,+ `{"type":"shell_call_output","call_id":"call_1","output":[{"stdout":"","stderr":"","outcome":{"type":"exit","exit_code":0}}]}`,+ }},+ {"local shell pair with empty result", []string{+ `{"type":"local_shell_call","id":"lsc_1","call_id":"call_1","status":"completed","action":{"type":"exec","command":["true"],"env":{}}}`,+ `{"type":"local_shell_call_output","id":"call_1","output":""}`,+ }},+ {"function pair with empty result", []string{+ `{"type":"function_call","call_id":"call_1","name":"run","arguments":"{}"}`,+ `{"type":"function_call_output","call_id":"call_1","output":""}`,+ }},+ } {+ t.Run(tt.name, func(t *testing.T) {+ for _, foreign := range []bool{false, true} {+ t.Run(fmt.Sprintf("foreign=%t", foreign), func(t *testing.T) {+ local, capture := newCompactionTestServer(t, func(_ int, w http.ResponseWriter, _ *http.Request, _ []byte) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = io.WriteString(w, `{"id":"resp_next","object":"response","status":"completed","model":"fixture","output":[]}`)+ })+ retained := []json.RawMessage{+ json.RawMessage(`{"type":"web_search_call","id":"ws_1","status":"completed"}`),+ }+ for _, item := range tt.items {+ retained = append(retained, json.RawMessage(item))+ }+ retained = append(retained, json.RawMessage(`{"type":"reasoning","summary":[],"encrypted_content":"other-opaque-state"}`))+ input := append([]json.RawMessage(nil), retained[:1]...)+ if foreign {+ input = append(input, json.RawMessage(`{"type":"compaction","encrypted_content":"opaque-provider-state"}`))+ }+ input = append(input, retained[1:]...)+ request, err := json.Marshal(map[string]any{"model": "fixture:cloud", "stream": false, "input": input})+ if err != nil {+ t.Fatal(err)+ }+ status, _, body := postCompactionRequest(t, local, "/v1/responses", string(request))+ if status != http.StatusOK {+ t.Fatalf("status=%d body=%s", status, body)+ }+ paths, bodies := capture.snapshot()+ if len(paths) != 1 || paths[0] != "/v1/responses" {+ t.Fatalf("paths=%v", paths)+ }+ var forwarded struct {+ Input []json.RawMessage `json:"input"`+ }+ if err := json.Unmarshal(bodies[0], &forwarded); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(forwarded.Input, retained) {+ t.Fatalf("retained input changed: got=%s want=%s", forwarded.Input, retained)+ }+ })+ }+ })+ }+}++func TestResponsesForeignCompactionLocalInputs(t *testing.T) {+ gin.SetMode(gin.TestMode)+ for _, tt := range []struct {+ name string+ item string+ wantErr string+ wantMessages []api.Message+ wantPrompt []string+ // Historical reasoning stays in Thinking, which these renderers may omit.+ wantOmitted []string+ wantThinking []string+ }{+ {+ name: "image file ID", item: `{"role":"user","content":[{"type":"input_image","file_id":"file-fixture"}]}`,+ wantMessages: []api.Message{{Role: "user"}},+ },+ {+ name: "file ID beside text", item: `{"role":"user","content":[{"type":"input_text","text":"Read this image"},{"type":"input_image","file_id":"file-fixture"}]}`,+ wantMessages: []api.Message{{Role: "user", Content: "Read this image"}},+ },+ {+ name: "file reference", item: `{"role":"user","content":[{"type":"input_file","file_id":"file-fixture"}]}`,+ wantErr: "file inputs",+ },+ {+ name: "audio input", item: `{"role":"user","content":[{"type":"input_audio","input_audio":{"data":"Zml4dHVyZQ==","format":"wav"}}]}`,+ wantErr: "unknown content type: input_audio",+ },+ {+ name: "unsupported shell call", item: `{"type":"shell_call","call_id":"call_1","action":{"commands":["true"]}}`,+ wantErr: "shell_call",+ },+ {+ name: "unsupported local shell call", item: `{"type":"local_shell_call","call_id":"call_1","action":{"type":"exec","command":["true"]}}`,+ wantErr: "local_shell_call",+ },+ {+ name: "summary only", item: `{"type":"reasoning","summary":[{"type":"summary_text","text":"Remember kiwi-42"}]}`,+ wantMessages: []api.Message{{Role: "assistant", Thinking: "Remember kiwi-42"}},+ wantOmitted: []string{"Remember kiwi-42"},+ },+ {+ name: "summary with encrypted content", item: `{"type":"reasoning","summary":[{"type":"summary_text","text":"Remember kiwi-42"}],"encrypted_content":"opaque-reasoning-state"}`,+ wantMessages: []api.Message{{Role: "assistant", Thinking: "Remember kiwi-42"}},+ wantOmitted: []string{"Remember kiwi-42"},+ },+ {+ name: "summary before user message", item: `{"type":"reasoning","summary":[{"type":"summary_text","text":"Remember kiwi-42"}]},{"role":"user","content":"continue"}`,+ wantMessages: []api.Message{{Role: "assistant", Thinking: "Remember kiwi-42"}, {Role: "user", Content: "continue"}},+ wantPrompt: []string{"continue"},+ wantOmitted: []string{"Remember kiwi-42"},+ },+ {+ name: "consecutive summaries", item: `{"type":"reasoning","summary":[{"type":"summary_text","text":"Remember kiwi-42"}]},{"type":"reasoning","summary":[{"type":"summary_text","text":"Remember plum-73"}]}`,+ wantMessages: []api.Message{{Role: "assistant", Thinking: "Remember kiwi-42\nRemember plum-73"}},+ wantOmitted: []string{"Remember kiwi-42", "Remember plum-73"},+ },+ {+ name: "summary between tool call and result", item: `{"type":"function_call","call_id":"call_1","name":"run","arguments":"{}"},{"type":"reasoning","summary":[{"type":"summary_text","text":"Remember kiwi-42"}]},{"type":"function_call_output","call_id":"call_1","output":""},{"role":"user","content":"continue"}`,+ wantMessages: []api.Message{+ {Role: "assistant", Thinking: "Remember kiwi-42", ToolCalls: []api.ToolCall{{ID: "call_1", Function: api.ToolCallFunction{Name: "run", Arguments: api.NewToolCallFunctionArguments()}}}},+ {Role: "tool", ToolCallID: "call_1"},+ {Role: "user", Content: "continue"},+ },+ wantPrompt: []string{"continue"},+ wantOmitted: []string{"Remember kiwi-42"},+ },+ {+ name: "encrypted reasoning without summary", item: `{"type":"reasoning","summary":[],"encrypted_content":"opaque-reasoning-state"},{"role":"user","content":"continue"}`,+ wantMessages: []api.Message{{Role: "user", Content: "continue"}},+ wantPrompt: []string{"continue"},+ },+ {+ name: "web search with consecutive reasoning", item: `{"role":"user","content":"search"},{"type":"reasoning","summary":[{"type":"summary_text","text":"first thought"}],"encrypted_content":"first thought"},{"type":"web_search_call","id":"ws_1","status":"completed"},{"type":"reasoning","summary":[{"type":"summary_text","text":"second thought"}],"encrypted_content":"opaque-reasoning-state"},{"role":"assistant","content":"the answer"}`,+ wantMessages: []api.Message{{Role: "user", Content: "search"}, {Role: "assistant", Content: "the answer", Thinking: "first thought\nsecond thought"}},+ wantPrompt: []string{"search", "the answer"},+ wantThinking: []string{"first thought", "second thought"},+ },+ {+ name: "readable handoff message control", item: `{"role":"assistant","content":"Remember kiwi-42"},{"role":"user","content":"continue"}`,+ wantMessages: []api.Message{{Role: "assistant", Content: "Remember kiwi-42"}, {Role: "user", Content: "continue"}},+ wantPrompt: []string{"Remember kiwi-42", "continue"},+ },+ {+ name: "native thinking and summary", item: `{"type":"reasoning","summary":[{"type":"summary_text","text":"Remember kiwi-42"}],"encrypted_content":"Remember kiwi-42"},{"role":"assistant","content":"remembered"}`,+ wantMessages: []api.Message{{Role: "assistant", Content: "remembered", Thinking: "Remember kiwi-42"}},+ wantPrompt: []string{"remembered"},+ },+ {+ name: "agent image", item: `{"type":"agent_message","content":[{"type":"input_image","image_url":"data:image/png;base64,Zml4dHVyZQ=="}]}`,+ wantMessages: []api.Message{{Role: "user"}},+ },+ } {+ t.Run(tt.name, func(t *testing.T) {+ for _, foreign := range []bool{false, true} {+ t.Run(fmt.Sprintf("foreign=%t", foreign), func(t *testing.T) {+ s := &Server{}+ router := gin.New()+ var captured *api.ChatRequest+ router.POST("/v1/responses", s.responsesCompactionMiddleware(), middleware.ResponsesMiddleware(), func(c *gin.Context) {+ captured = new(api.ChatRequest)+ if err := json.NewDecoder(c.Request.Body).Decode(captured); err != nil {+ t.Fatal(err)+ }+ c.Status(http.StatusNoContent)+ })+ input := tt.item+ if foreign {+ input = `{"type":"compaction","encrypted_content":"opaque-provider-state"},` + input+ }+ request := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"fixture","input":[`+input+`]}`))+ request.Header.Set("Content-Type", "application/json")+ response := httptest.NewRecorder()+ router.ServeHTTP(response, request)+ if tt.wantErr != "" {+ if response.Code != http.StatusBadRequest || captured != nil || !strings.Contains(response.Body.String(), tt.wantErr) {+ t.Fatalf("status=%d captured=%+v body=%s", response.Code, captured, response.Body.String())+ }+ return+ }+ if response.Code != http.StatusNoContent || captured == nil {+ t.Fatalf("status=%d captured=%+v, want messages=%+v", response.Code, captured, tt.wantMessages)+ }+ if !reflect.DeepEqual(captured.Messages, tt.wantMessages) {+ t.Errorf("messages=%+v, want=%+v", captured.Messages, tt.wantMessages)+ }+ if len(tt.wantPrompt)+len(tt.wantOmitted)+len(tt.wantThinking) > 0 {+ for _, renderer := range []string{"qwen3-coder", "qwen3.5"} {+ t.Run(renderer, func(t *testing.T) {+ prompt, err := renderPrompt(&Model{Config: model.ConfigV2{Renderer: renderer}}, captured.Messages, captured.Tools, &api.ThinkValue{Value: true})+ if err != nil {+ t.Fatal(err)+ }+ for _, text := range tt.wantPrompt {+ if strings.Count(prompt, text) != 1 {+ t.Errorf("expected %q once in rendered prompt: %q", text, prompt)+ }+ }+ for _, text := range append([]string{"opaque-reasoning-state", "opaque-provider-state"}, tt.wantOmitted...) {+ if strings.Contains(prompt, text) {+ t.Errorf("unexpected %q in rendered prompt: %q", text, prompt)+ }+ }+ for _, text := range tt.wantThinking {+ wantCount := 0+ if renderer == "qwen3.5" {+ wantCount = 1+ }+ if strings.Count(prompt, text) != wantCount {+ t.Errorf("expected %q %d times in rendered prompt: %q", text, wantCount, prompt)+ }+ }+ })+ }+ }+ })+ }+ })+ }+}++func TestResponsesCompactionRejectsInvalidStateBeforeInference(t *testing.T) {+ for _, modelName := range []string{"fixture", "fixture:cloud"} {+ for _, mode := range []struct {+ name string+ path string+ trigger bool+ }{+ {"continuation", "/v1/responses", false},+ {"standalone", "/v1/responses/compact", false},+ {"triggered", "/v1/responses", true},+ } {+ for _, tt := range []struct {+ name string+ input string+ error string+ }{+ {"foreign only", `{"type":"compaction","encrypted_content":"foreign"}`, "no items"},+ {"native invalid version", `{"role":"user","content":"continue"},{"type":"compaction","encrypted_content":"{\"type\":\"ollama_compaction\",\"version\":2,\"summary\":\"future\"}"}`, "version"},+ {"invalid envelope", `{"role":"user","content":"continue"},{"type":"compaction","encrypted_content":42}`, "invalid compaction item"},+ } {+ t.Run(modelName+"/"+mode.name+"/"+tt.name, func(t *testing.T) {+ local, capture := newCompactionTestServer(t, func(_ int, w http.ResponseWriter, _ *http.Request, _ []byte) {+ w.WriteHeader(http.StatusInternalServerError)+ })+ input := tt.input+ if mode.trigger {+ input += `,{"type":"compaction_trigger"}`+ }+ request := fmt.Sprintf(`{"model":%q,"stream":%t,"input":[%s]}`, modelName, mode.trigger, input)+ status, _, body := postCompactionRequest(t, local, mode.path, request)+ if status != http.StatusBadRequest || !bytes.Contains(body, []byte(tt.error)) {+ t.Fatalf("status=%d body=%s", status, body)+ }+ if paths, _ := capture.snapshot(); len(paths) != 0 {+ t.Fatalf("invalid state reached inference: %v", paths)+ }+ })+ }+ }+ }+}++func TestResponsesForeignCompactionHistory(t *testing.T) {+ for _, tt := range []struct {+ name string+ path string+ stream bool+ compact bool+ }{+ {"json continuation", "/v1/responses", false, false},+ {"streaming continuation", "/v1/responses", true, false},+ {"standalone compaction", "/v1/responses/compact", false, true},+ {"triggered compaction", "/v1/responses", true, true},+ } {+ t.Run(tt.name, func(t *testing.T) {+ const response = `{"id":"resp_next","object":"response","status":"completed","model":"fixture","output":[],"usage":null}`+ streamResponse := "event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":" + response + "}\n\n"+ local, capture := newCompactionTestServer(t, func(_ int, w http.ResponseWriter, _ *http.Request, _ []byte) {+ if tt.stream && !tt.compact {+ w.Header().Set("Content-Type", "text/event-stream")+ _, _ = io.WriteString(w, streamResponse)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ if tt.compact {+ _, _ = w.Write(summaryResponse(t, "Remember kiwi-42.", nil))+ } else {+ _, _ = io.WriteString(w, response)+ }+ })+ input := []any{+ map[string]any{"role": "user", "content": "readable prefix"},+ openai.ResponsesCompactionItem{Type: "compaction", EncryptedContent: "opaque-provider-state"},+ map[string]any{"type": "custom_tool_call", "call_id": "call_1", "name": "read", "input": "notes.txt"},+ map[string]any{"type": "custom_tool_call_output", "call_id": "call_1", "output": "kiwi-42"},+ }+ if tt.compact && tt.stream {+ input = append(input, map[string]any{"type": "compaction_trigger"})+ }+ request, err := json.Marshal(map[string]any{"model": "fixture:cloud", "stream": tt.stream, "input": input})+ if err != nil {+ t.Fatal(err)+ }+ status, headers, body := postCompactionRequest(t, local, tt.path, string(request))+ if status != http.StatusOK {+ t.Fatalf("status=%d body=%s", status, body)+ }+ if tt.stream {+ if !strings.HasPrefix(headers.Get("Content-Type"), "text/event-stream") || strings.Count(string(body), "event: response.completed") != 1 {+ t.Fatalf("unexpected stream: headers=%v body=%s", headers, body)+ }+ if !tt.compact && string(body) != streamResponse {+ t.Fatalf("upstream stream changed: %s", body)+ }+ }+ paths, bodies := capture.snapshot()+ if len(paths) != 1 || paths[0] != "/v1/responses" {+ t.Fatalf("paths=%v", paths)+ }+ forwarded := string(bodies[0])+ if strings.Contains(forwarded, "opaque-provider-state") {+ t.Fatalf("foreign payload reached inference: %s", forwarded)+ }+ for _, text := range []string{"readable prefix", "kiwi-42", "call_1", "notes.txt"} {+ if !strings.Contains(forwarded, text) {+ t.Errorf("history missing %q: %s", text, forwarded)+ }+ }+ })+ }+}