Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Support DeepSeek V4 tool turns in Patrol

rcourtman3b077b8ef63d
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 8529407619..96946de0a4 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -1295,6 +1295,15 @@ OpenAI-compatible chat streams. Provider reads that return payload bytes with
process the buffered frame set and route tool-call assembly plus final done
event emission through the same canonical finalizer used for `[DONE]` instead
of dropping the last chunk or leaving tool calls unfinalized on clean close.
+That same provider-transport boundary owns OpenAI-compatible tool protocol
+adaptation. When a direct provider such as DeepSeek accepts tools but rejects
+forced specific or required `tool_choice` values, the shared OpenAI-compatible
+client must degrade offered-tool requests to provider-supported auto tool
+selection instead of surfacing a raw provider protocol error to Assistant or
+Patrol. Reasoning-backed provider turns that return tool calls with
+`reasoning_content` must preserve that reasoning state on the following
+tool-result turn when the provider requires it, so Assistant and Patrol can
+complete multi-turn tool use against live BYOK providers.
That same browser-owned chat read model must keep target normalization helper-
driven. Assistant shells may still derive legacy VM identifiers or display
labels for read-only targeting, but they must do so through shared helpers and
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 664f7a4c65..54863fc0d8 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -496,6 +496,13 @@ contract. Expanded erroring runs should show the backend-provided
provider settings` action near the run narrative, so a provider/model/tool
failure remains actionable even when the operator starts from the Runs tab
rather than the synthetic runtime finding.
+Those run-history failure fields are customer/API-safe classified detail, not
+raw provider payload storage. The backend must normalize both newly written
+and already persisted Patrol run records before browser/API serialization, so
+provider protocol fragments such as `tool_choice`, `reasoning_content`, raw
+endpoint URLs, credential hints, or model-internal error strings do not leak
+through run history while the operator still receives an actionable recovery
+summary.
That same shared finding-presentation helper should also own Patrol finding
subject labels, so Patrol-owned synthetic service findings render as
`Patrol runtime` rather than leaking backend resource internals like
diff --git a/internal/ai/patrol.go b/internal/ai/patrol.go
index 6b4dddfeca..2a017ee5d2 100644
--- a/internal/ai/patrol.go
+++ b/internal/ai/patrol.go
@@ -229,6 +229,10 @@ func canonicalPatrolFindingIDs(ids []string) []string {
func normalizePatrolRunRecord(record PatrolRunRecord) PatrolRunRecord {
record.AlertIdentifier = canonicalPatrolAlertIdentifier(record.AlertIdentifier)
record.FindingIDs = canonicalPatrolFindingIDs(record.FindingIDs)
+ record.ErrorSummary = strings.TrimSpace(redactPatrolRuntimeFailureDetail(record.ErrorSummary))
+ if strings.TrimSpace(record.ErrorDetail) != "" {
+ record.ErrorDetail = truncateString(summarizePatrolRuntimeFailureDetail(record.ErrorDetail), patrolRuntimeFailureDetailLimit)
+ }
return record
}
diff --git a/internal/ai/patrol_history_persistence_test.go b/internal/ai/patrol_history_persistence_test.go
index 76eb6d7c37..fafd6381ae 100644
--- a/internal/ai/patrol_history_persistence_test.go
+++ b/internal/ai/patrol_history_persistence_test.go
@@ -661,8 +661,11 @@ func TestPatrolHistoryPersistenceAdapter_PreservesEmptySnapshotsAndParityFields(
if loaded[0].ErrorSummary != "Selected model does not support Patrol tools" {
t.Fatalf("expected ErrorSummary to survive persistence, got %q", loaded[0].ErrorSummary)
}
- if loaded[0].ErrorDetail != "provider rejected tool_choice" {
- t.Fatalf("expected ErrorDetail to survive persistence, got %q", loaded[0].ErrorDetail)
+ if strings.Contains(loaded[0].ErrorDetail, "tool_choice") {
+ t.Fatalf("expected ErrorDetail to serialize safe classified detail, got %q", loaded[0].ErrorDetail)
+ }
+ if !strings.Contains(loaded[0].ErrorDetail, "Provider rejected Patrol tool calls") {
+ t.Fatalf("expected ErrorDetail to preserve actionable provider classification, got %q", loaded[0].ErrorDetail)
}
}
diff --git a/internal/ai/patrol_runtime_failure.go b/internal/ai/patrol_runtime_failure.go
index 1a271edab1..0fcabe75cc 100644
--- a/internal/ai/patrol_runtime_failure.go
+++ b/internal/ai/patrol_runtime_failure.go
@@ -82,7 +82,7 @@ func patrolRuntimeFailureFromError(err error) patrolRuntimeFailure {
if err != nil {
raw = strings.TrimSpace(err.Error())
}
- detail := truncateString(redactPatrolRuntimeFailureDetail(raw), patrolRuntimeFailureDetailLimit)
+ detail := truncateString(summarizePatrolRuntimeFailureDetail(raw), patrolRuntimeFailureDetailLimit)
lower := strings.ToLower(raw)
failure := patrolRuntimeFailure{
@@ -199,6 +199,8 @@ func summarizePatrolRuntimeFailureDetail(raw string) string {
strings.Contains(lower, "tools are not supported") ||
strings.Contains(lower, "no endpoints found") && strings.Contains(lower, "tool"):
return "Provider rejected Patrol tool calls. Choose a Patrol model and endpoint with tool-call support."
+ case strings.Contains(lower, "reasoning_content"):
+ return "Provider rejected Patrol reasoning state. Retry with a provider route that supports the selected model's reasoning and tool protocol."
case strings.Contains(lower, "insufficient balance") ||
strings.Contains(lower, "402") ||
strings.Contains(lower, "payment required") ||
diff --git a/internal/ai/patrol_runtime_failure_test.go b/internal/ai/patrol_runtime_failure_test.go
index 1244dc109a..9c2dacd5b0 100644
--- a/internal/ai/patrol_runtime_failure_test.go
+++ b/internal/ai/patrol_runtime_failure_test.go
@@ -2,6 +2,7 @@ package ai
import (
"context"
+ "encoding/json"
"errors"
"strings"
"testing"
@@ -29,8 +30,11 @@ func TestPatrolRuntimeFailureFromError_ClassifiesToolCallingUnsupported(t *testi
if !strings.Contains(failure.Recommendation, "supports tool calling") {
t.Fatalf("expected recommendation to mention tool calling, got %q", failure.Recommendation)
}
- if !strings.Contains(failure.Evidence, "tool_choice") {
- t.Fatalf("expected evidence to keep provider detail, got %q", failure.Evidence)
+ if strings.Contains(failure.Evidence, "tool_choice") || strings.Contains(failure.Evidence, "No endpoints found") {
+ t.Fatalf("evidence leaked raw provider detail: %q", failure.Evidence)
+ }
+ if !strings.Contains(failure.Evidence, "Provider rejected Patrol tool calls") {
+ t.Fatalf("expected evidence to keep safe classified detail, got %q", failure.Evidence)
}
}
@@ -83,6 +87,17 @@ func TestPatrolRuntimeFailureFromErrorRedactsSecretLikeDetail(t *testing.T) {
}
}
+func TestPatrolRuntimeFailureFromErrorSummarizesReasoningContentProtocolDetail(t *testing.T) {
+ failure := patrolRuntimeFailureFromError(errors.New("API error (400): The `reasoning_content` in the thinking mode must be passed back to the API."))
+
+ if strings.Contains(failure.Evidence, "reasoning_content") {
+ t.Fatalf("evidence leaked raw provider protocol detail: %q", failure.Evidence)
+ }
+ if !strings.Contains(failure.Evidence, "Provider rejected Patrol reasoning state") {
+ t.Fatalf("expected safe reasoning-state summary, got %q", failure.Evidence)
+ }
+}
+
func TestPatrolRuntimeFailureFromError_DefaultIsActionable(t *testing.T) {
failure := patrolRuntimeFailureFromError(errors.New("upstream returned unexpected eof"))
@@ -149,8 +164,11 @@ func TestRunPatrolRecordsStructuredRuntimeFailure(t *testing.T) {
if runs[0].ErrorSummary != "Selected model does not support Patrol tools" {
t.Fatalf("expected structured run error summary, got %q", runs[0].ErrorSummary)
}
- if !strings.Contains(runs[0].ErrorDetail, "tool_choice") {
- t.Fatalf("expected run error detail to preserve provider message, got %q", runs[0].ErrorDetail)
+ if strings.Contains(runs[0].ErrorDetail, "tool_choice") || strings.Contains(runs[0].ErrorDetail, "No endpoints found") {
+ t.Fatalf("run error detail leaked raw provider message: %q", runs[0].ErrorDetail)
+ }
+ if !strings.Contains(runs[0].ErrorDetail, "Provider rejected Patrol tool calls") {
+ t.Fatalf("expected run error detail to preserve safe classified detail, got %q", runs[0].ErrorDetail)
}
finding := ps.findings.Get(generateFindingID(patrolRuntimeResourceID, "reliability", patrolRuntimeFindingKey))
@@ -165,6 +183,29 @@ func TestRunPatrolRecordsStructuredRuntimeFailure(t *testing.T) {
}
}
+func TestPatrolRunRecordJSONNormalizesRuntimeFailureDetail(t *testing.T) {
+ run := PatrolRunRecord{
+ ID: "run-1",
+ Status: "error",
+ ErrorSummary: "Selected model does not support Patrol tools",
+ ErrorDetail: `agentic patrol failed: provider error: API error (400): deepseek-reasoner does not support this tool_choice at https://openrouter.ai/settings/keys for user_test`,
+ }
+
+ body, err := json.Marshal(run)
+ if err != nil {
+ t.Fatalf("marshal run: %v", err)
+ }
+ text := string(body)
+ for _, raw := range []string{"tool_choice", "openrouter.ai/settings/keys", "user_test", "deepseek-reasoner"} {
+ if strings.Contains(text, raw) {
+ t.Fatalf("marshaled run leaked raw provider detail %q: %s", raw, text)
+ }
+ }
+ if !strings.Contains(text, "Provider rejected Patrol tool calls") {
+ t.Fatalf("expected safe classified detail in marshaled run, got %s", text)
+ }
+}
+
func TestRunScopedPatrolRecordsStructuredRuntimeFailure(t *testing.T) {
svc := NewService(config.NewConfigPersistence(t.TempDir()), nil)
svc.cfg = &config.AIConfig{Enabled: true, PatrolModel: "ollama:qwen3.5:2b"}
diff --git a/internal/ai/providers/openai.go b/internal/ai/providers/openai.go
index 0cdef2642b..2bcc099f0e 100644
--- a/internal/ai/providers/openai.go
+++ b/internal/ai/providers/openai.go
@@ -176,6 +176,21 @@ func (c *OpenAIClient) isDeepSeekReasoner() bool {
return c.isDeepSeek() && strings.Contains(c.model, "reasoner")
}
+func (c *OpenAIClient) shouldSendReasoningContent() bool {
+ return c.isDeepSeek()
+}
+
+func (c *OpenAIClient) supportsForcedToolChoice(model string) bool {
+ return !c.isDeepSeek()
+}
+
+func (c *OpenAIClient) toolChoiceForModel(model string, choice *ToolChoice) interface{} {
+ if !c.supportsForcedToolChoice(model) {
+ return "auto"
+ }
+ return convertToolChoiceToOpenAI(choice)
+}
+
func (c *OpenAIClient) applyProviderHeaders(req *http.Request) {
if !c.isOpenRouter() {
return
@@ -242,8 +257,9 @@ func (c *OpenAIClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse
if m.Content != "" {
msg.Content = m.Content
}
- // For DeepSeek reasoner, include reasoning_content if present
- if c.isDeepSeekReasoner() && m.ReasoningContent != "" {
+ // DeepSeek reasoning-backed models require the reasoning_content
+ // returned with a tool call to be passed back on the next turn.
+ if c.shouldSendReasoningContent() && m.ReasoningContent != "" {
msg.ReasoningContent = m.ReasoningContent
}
for _, tc := range m.ToolCalls {
@@ -268,7 +284,7 @@ func (c *OpenAIClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse
} else {
msg.Content = m.Content
// For assistant messages with reasoning content (DeepSeek)
- if c.isDeepSeekReasoner() && m.ReasoningContent != "" {
+ if c.shouldSendReasoningContent() && m.ReasoningContent != "" {
msg.ReasoningContent = m.ReasoningContent
}
}
@@ -334,11 +350,13 @@ func (c *OpenAIClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse
},
})
}
- if len(openaiReq.Tools) > 0 && !c.isDeepSeekReasoner() {
+ if len(openaiReq.Tools) > 0 {
// Map ToolChoice to OpenAI format
// OpenAI uses "required" instead of Anthropic's "any"
- // DeepSeek Reasoner does not support tool_choice — it decides tool use via reasoning
- openaiReq.ToolChoice = convertToolChoiceToOpenAI(req.ToolChoice)
+ // DeepSeek's direct API accepts tools with auto choice, but rejects
+ // forced specific/required tool_choice values for reasoning-backed
+ // models such as V4 Flash/Pro.
+ openaiReq.ToolChoice = c.toolChoiceForModel(model, req.ToolChoice)
}
}
@@ -528,8 +546,8 @@ func (c *OpenAIClient) modelsEndpoint() string {
// SupportsThinking returns true if the model supports extended thinking
func (c *OpenAIClient) SupportsThinking(model string) bool {
- // DeepSeek reasoner models support extended thinking
- if c.isDeepSeek() && strings.Contains(model, "reasoner") {
+ // DeepSeek reasoning-backed models expose reasoning_content.
+ if c.isDeepSeek() && (strings.Contains(model, "reasoner") || strings.HasPrefix(model, "deepseek-v4-")) {
return true
}
// OpenAI o1/o3/o4 models have reasoning but not in the same streaming format
@@ -657,7 +675,7 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback
if m.Content != "" {
msg.Content = m.Content
}
- if c.isDeepSeekReasoner() && m.ReasoningContent != "" {
+ if c.shouldSendReasoningContent() && m.ReasoningContent != "" {
msg.ReasoningContent = m.ReasoningContent
}
for _, tc := range m.ToolCalls {
@@ -680,7 +698,7 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback
msg.ToolCallID = m.ToolResult.ToolUseID
} else {
msg.Content = m.Content
- if c.isDeepSeekReasoner() && m.ReasoningContent != "" {
+ if c.shouldSendReasoningContent() && m.ReasoningContent != "" {
msg.ReasoningContent = m.ReasoningContent
}
}
@@ -739,10 +757,12 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback
},
})
}
- if len(openaiReq.Tools) > 0 && !c.isDeepSeekReasoner() {
+ if len(openaiReq.Tools) > 0 {
// Map ToolChoice to OpenAI format (same as non-streaming)
- // DeepSeek Reasoner does not support tool_choice — it decides tool use via reasoning
- openaiReq.ToolChoice = convertToolChoiceToOpenAI(req.ToolChoice)
+ // DeepSeek's direct API accepts tools with auto choice, but rejects
+ // forced specific/required tool_choice values for reasoning-backed
+ // models such as V4 Flash/Pro.
+ openaiReq.ToolChoice = c.toolChoiceForModel(model, req.ToolChoice)
}
}
diff --git a/internal/ai/providers/openai_test.go b/internal/ai/providers/openai_test.go
index fbf1d3a159..e6a5ff11c0 100644
--- a/internal/ai/providers/openai_test.go
+++ b/internal/ai/providers/openai_test.go
@@ -400,6 +400,146 @@ func TestOpenAIClient_ChatStream_ToolChoiceNone_DropsTools(t *testing.T) {
assert.True(t, doneCalled)
}
+func TestOpenAIClient_Chat_DeepSeekCoercesForcedToolChoiceToAuto(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var got map[string]interface{}
+ require.NoError(t, json.NewDecoder(r.Body).Decode(&got))
+ assert.Equal(t, "deepseek-v4-flash", got["model"])
+ assert.Equal(t, "auto", got["tool_choice"])
+ require.Len(t, got["tools"], 1)
+
+ _ = json.NewEncoder(w).Encode(openaiResponse{
+ ID: "chatcmpl-deepseek-tools",
+ Model: "deepseek-v4-flash",
+ Choices: []openaiChoice{
+ {
+ Message: openaiRespMsg{Role: "assistant", Content: "ok"},
+ FinishReason: "stop",
+ },
+ },
+ })
+ }))
+ defer server.Close()
+
+ client := NewOpenAIClient("sk-test", "deepseek-v4-flash", server.URL, 0)
+ client.baseURL = strings.TrimSuffix(server.URL, "/") + "/v1/chat/completions#deepseek.com"
+
+ _, err := client.Chat(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "Use the tool"}},
+ Tools: []Tool{
+ {Name: "ping", Description: "Ping", InputSchema: map[string]interface{}{"type": "object"}},
+ },
+ ToolChoice: &ToolChoice{Type: ToolChoiceTool, Name: "ping"},
+ })
+ require.NoError(t, err)
+}
+
+func TestOpenAIClient_ChatStream_DeepSeekCoercesForcedToolChoiceToAuto(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var got map[string]interface{}
+ require.NoError(t, json.NewDecoder(r.Body).Decode(&got))
+ assert.Equal(t, "deepseek-v4-flash", got["model"])
+ assert.Equal(t, "auto", got["tool_choice"])
+ require.Len(t, got["tools"], 1)
+
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprintf(w, "data: %s\n\n", `{"id":"chatcmpl-1","choices":[{"delta":{"content":"ok"}}],"object":"chat.completion.chunk"}`)
+ fmt.Fprintf(w, "data: [DONE]\n\n")
+ w.(http.Flusher).Flush()
+ }))
+ defer server.Close()
+
+ client := NewOpenAIClient("sk-test", "deepseek-v4-flash", server.URL, 0)
+ client.baseURL = strings.TrimSuffix(server.URL, "/") + "/v1/chat/completions#deepseek.com"
+
+ err := client.ChatStream(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "Use the tool"}},
+ Tools: []Tool{
+ {Name: "ping", Description: "Ping", InputSchema: map[string]interface{}{"type": "object"}},
+ },
+ ToolChoice: &ToolChoice{Type: ToolChoiceAny},
+ }, func(event StreamEvent) {})
+ require.NoError(t, err)
+}
+
+func TestOpenAIClient_Chat_DeepSeekPreservesReasoningContentForToolTurns(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var got openaiRequest
+ require.NoError(t, json.NewDecoder(r.Body).Decode(&got))
+ require.Len(t, got.Messages, 3)
+ assert.Equal(t, "assistant", got.Messages[1].Role)
+ assert.Equal(t, "I need current state first.", got.Messages[1].ReasoningContent)
+ require.Len(t, got.Messages[1].ToolCalls, 1)
+
+ _ = json.NewEncoder(w).Encode(openaiResponse{
+ ID: "chatcmpl-deepseek-reasoning",
+ Model: "deepseek-v4-flash",
+ Choices: []openaiChoice{
+ {
+ Message: openaiRespMsg{Role: "assistant", Content: "ok"},
+ FinishReason: "stop",
+ },
+ },
+ })
+ }))
+ defer server.Close()
+
+ client := NewOpenAIClient("sk-test", "deepseek-v4-flash", server.URL, 0)
+ client.baseURL = strings.TrimSuffix(server.URL, "/") + "/v1/chat/completions#deepseek.com"
+
+ _, err := client.Chat(context.Background(), ChatRequest{
+ Messages: []Message{
+ {Role: "user", Content: "Check status"},
+ {
+ Role: "assistant",
+ ReasoningContent: "I need current state first.",
+ ToolCalls: []ToolCall{
+ {ID: "call-1", Name: "pulse_read", Input: map[string]interface{}{"action": "status"}},
+ },
+ },
+ {Role: "tool", ToolResult: &ToolResult{ToolUseID: "call-1", Content: "healthy"}},
+ },
+ })
+ require.NoError(t, err)
+}
+
+func TestOpenAIClient_ChatStream_DeepSeekPreservesReasoningContentForToolTurns(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var got openaiStreamRequest
+ require.NoError(t, json.NewDecoder(r.Body).Decode(&got))
+ require.Len(t, got.Messages, 3)
+ assert.Equal(t, "assistant", got.Messages[1].Role)
+ assert.Equal(t, "I need current state first.", got.Messages[1].ReasoningContent)
+ require.Len(t, got.Messages[1].ToolCalls, 1)
+
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprintf(w, "data: %s\n\n", `{"id":"chatcmpl-1","choices":[{"delta":{"content":"ok"}}],"object":"chat.completion.chunk"}`)
+ fmt.Fprintf(w, "data: [DONE]\n\n")
+ w.(http.Flusher).Flush()
+ }))
+ defer server.Close()
+
+ client := NewOpenAIClient("sk-test", "deepseek-v4-flash", server.URL, 0)
+ client.baseURL = strings.TrimSuffix(server.URL, "/") + "/v1/chat/completions#deepseek.com"
+
+ err := client.ChatStream(context.Background(), ChatRequest{
+ Messages: []Message{
+ {Role: "user", Content: "Check status"},
+ {
+ Role: "assistant",
+ ReasoningContent: "I need current state first.",
+ ToolCalls: []ToolCall{
+ {ID: "call-1", Name: "pulse_read", Input: map[string]interface{}{"action": "status"}},
+ },
+ },
+ {Role: "tool", ToolResult: &ToolResult{ToolUseID: "call-1", Content: "healthy"}},
+ },
+ }, func(event StreamEvent) {})
+ require.NoError(t, err)
+}
+
func TestOpenAIClient_ChatStream_Errors(t *testing.T) {
t.Run("401 Unauthorized", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {