| 1 | package agent |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "sync" |
| 10 | "testing" |
| 11 | |
| 12 | "reasonix/internal/event" |
| 13 | "reasonix/internal/provider" |
| 14 | "reasonix/internal/provider/anthropic" |
| 15 | "reasonix/internal/provider/openai" |
| 16 | "reasonix/internal/provider/responses" |
| 17 | ) |
| 18 | |
| 19 | func TestTruncatedJSONStreamRecoversWithoutExecutingPartialTools(t *testing.T) { |
| 20 | for _, protocol := range []string{"chat", "anthropic"} { |
| 21 | for _, cut := range []bool{true, false} { |
| 22 | name := protocol + "/malformed_line" |
| 23 | if cut { |
| 24 | name = protocol + "/unterminated_fragment" |
| 25 | } |
| 26 | t.Run(name, func(t *testing.T) { |
| 27 | var mu sync.Mutex |
| 28 | var bodies [][]byte |
| 29 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 30 | body, _ := io.ReadAll(r.Body) |
| 31 | mu.Lock() |
| 32 | bodies = append(bodies, body) |
| 33 | n := len(bodies) |
| 34 | mu.Unlock() |
| 35 | w.Header().Set("Content-Type", "text/event-stream") |
| 36 | if n == 1 { |
| 37 | // Complete tool arguments received before EOF still must not execute. |
| 38 | first := `data: {"choices":[{"delta":{"reasoning_content":"partial","tool_calls":[{"index":0,"id":"uncommitted","type":"function","function":{"name":"echo","arguments":"{\"text\":\"unsafe\"}"}}]}}]}` + "\n\n" |
| 39 | if protocol == "anthropic" { |
| 40 | first = `data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"uncommitted","name":"echo","input":{"text":"unsafe"}}}` + "\n\n" |
| 41 | } |
| 42 | _, _ = io.WriteString(w, first+`data: {"delta":nu`) |
| 43 | if !cut { |
| 44 | _, _ = io.WriteString(w, "\n\n") |
| 45 | } |
| 46 | return |
| 47 | } |
| 48 | if n > 2 { |
| 49 | w.WriteHeader(http.StatusUnauthorized) |
| 50 | return |
| 51 | } |
| 52 | reply := `data: {"choices":[{"delta":{"content":"recovered"},"finish_reason":"stop"}],"usage":{"prompt_tokens":12,"completion_tokens":2,"total_tokens":14}}` + "\n\ndata: [DONE]\n\n" |
| 53 | if protocol == "anthropic" { |
| 54 | reply = finalAnswerSSE |
| 55 | } |
| 56 | _, _ = io.WriteString(w, reply) |
| 57 | })) |
| 58 | defer srv.Close() |
| 59 | cfg := provider.Config{Name: "fragment", BaseURL: srv.URL, APIKey: "fixture", Model: "deepseek-v4-flash", Extra: map[string]any{"reasoning_protocol": "deepseek", "thinking": "enabled"}} |
| 60 | var p provider.Provider |
| 61 | var err error |
| 62 | if protocol == "chat" { |
| 63 | p, err = openai.New(cfg) |
| 64 | } else { |
| 65 | p, err = anthropic.New(cfg) |
| 66 | } |
| 67 | if err != nil { |
| 68 | t.Fatal(err) |
| 69 | } |
| 70 | sink := &recordSink{} |
| 71 | a := New(p, echoRegistry(), NewSession(""), Options{MissingReasoningWarnStateDir: t.TempDir()}, sink) |
| 72 | err = a.Run(withNoClosedLoop(context.Background()), "go") |
| 73 | if (err == nil) != cut { |
| 74 | t.Fatalf("cut=%v error=%v", cut, err) |
| 75 | } |
| 76 | if len(sink.kinds(event.ToolResult)) != 0 { |
| 77 | t.Fatal("uncommitted tool executed") |
| 78 | } |
| 79 | mu.Lock() |
| 80 | defer mu.Unlock() |
| 81 | if !cut { |
| 82 | if len(bodies) != 1 { |
| 83 | t.Fatal("malformed complete event retried") |
| 84 | } |
| 85 | return |
| 86 | } |
| 87 | if len(bodies) != 2 || !bytes.Equal(bodies[0], bodies[1]) { |
| 88 | t.Fatal("retry lost frozen request") |
| 89 | } |
| 90 | usages := sink.kinds(event.Usage) |
| 91 | if len(usages) != 1 || usages[0].Usage == nil || !usages[0].Usage.Unknown || usages[0].Usage.RequestCount != 2 { |
| 92 | t.Fatalf("usage=%+v", usages) |
| 93 | } |
| 94 | }) |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | func TestResponsesPassbackRejectionRepairsHistoryWithoutRepeatingTool(t *testing.T) { |
| 100 | var mu sync.Mutex |
| 101 | var bodies [][]byte |
| 102 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 103 | body, _ := io.ReadAll(r.Body) |
| 104 | mu.Lock() |
| 105 | bodies = append(bodies, body) |
| 106 | n := len(bodies) |
| 107 | mu.Unlock() |
| 108 | if n == 2 { |
| 109 | w.WriteHeader(http.StatusBadRequest) |
| 110 | _, _ = io.WriteString(w, "{\"error\":{\"message\":\"The `reasoning_text` in the thinking mode must be passed back to the API.\",\"type\":\"invalid_request_error\"}}") |
| 111 | return |
| 112 | } |
| 113 | if n > 4 { |
| 114 | w.WriteHeader(http.StatusUnauthorized) |
| 115 | return |
| 116 | } |
| 117 | w.Header().Set("Content-Type", "text/event-stream") |
| 118 | if n == 1 { |
| 119 | _, _ = io.WriteString(w, responsesToolWithoutReasoningSSE) |
| 120 | } else { |
| 121 | _, _ = io.WriteString(w, responsesFinalAnswerSSE) |
| 122 | } |
| 123 | })) |
| 124 | defer srv.Close() |
| 125 | p := responses.New(responses.Config{Name: "responses", BaseURL: "https://api.deepseek.com", RequestURL: srv.URL, Model: "deepseek-v4-flash", APIKey: "fixture", Effort: "high", Mode: "stateless"}) |
| 126 | sink := &recordSink{} |
| 127 | a := New(p, echoRegistry(), NewSession(""), Options{MissingReasoningWarnStateDir: t.TempDir()}, sink) |
| 128 | if err := a.Run(withNoClosedLoop(context.Background()), "go"); err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | if err := a.Run(withNoClosedLoop(context.Background()), "A new question: acknowledge the previous result without calling tools."); err != nil { |
| 132 | t.Fatal(err) |
| 133 | } |
| 134 | mu.Lock() |
| 135 | defer mu.Unlock() |
| 136 | if len(bodies) != 4 || len(sink.kinds(event.ToolResult)) != 1 { |
| 137 | t.Fatalf("requests=%d executions=%d", len(bodies), len(sink.kinds(event.ToolResult))) |
| 138 | } |
| 139 | if bytes.Contains(bodies[3], []byte(`"type":"function_call"`)) || !bytes.Contains(bodies[3], []byte("echoed: hi")) { |
| 140 | t.Fatal("later turn restored invalid tool history or lost completed results") |
| 141 | } |
| 142 | if !bytes.Contains(bodies[2], []byte("echoed: hi")) { |
| 143 | t.Fatal("repair dropped the actual completed tool output") |
| 144 | } |
| 145 | if !bytes.Contains(bodies[2], []byte("completed_tools")) || bytes.Contains(bodies[2], []byte(`"type":"function_call"`)) { |
| 146 | t.Fatal("repair lost completed facts or retained invalid call") |
| 147 | } |
| 148 | } |
| 149 |