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.

Sanitise plain-JSON tool-call leaks from weak local models

rcourtmane36945741e1d
diff --git a/internal/ai/chat/agentic_sanitize.go b/internal/ai/chat/agentic_sanitize.go
index a2d7ab57dd..10a98c39fc 100644
--- a/internal/ai/chat/agentic_sanitize.go
+++ b/internal/ai/chat/agentic_sanitize.go
@@ -3,6 +3,8 @@ package chat
import (
"regexp"
"strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
)
// Compiled regexes for structural tool call artifacts from various LLM providers.
@@ -28,6 +30,20 @@ var (
// never falls through to showing raw DSML to the user as the
// assistant's "final response."
dsmlRe = regexp.MustCompile(`</?[\||]+/?DSML[\||]*`)
+
+ // Plain-JSON tool-call leak: weak local models (qwen2.5:11b/14b and
+ // similar small Ollama models) frequently emit Pulse tool invocations
+ // as JSON inside content instead of through the structured tool_calls
+ // channel. The leak shape is a JSON object whose first key is "name"
+ // with a value matching a known Pulse tool, optionally wrapped in a
+ // markdown code fence. Anchored on (?:^|\n) so prose containing JSON
+ // fragments inline (e.g. "the field {"name":"x"} in the schema") is
+ // not stripped. The captured tool name is gated against the canonical
+ // allowlist in tools.IsKnownToolName so arbitrary JSON the user might
+ // legitimately share is left untouched.
+ jsonToolCallRe = regexp.MustCompile(
+ `(?:^|\n)[ \t]*(?:` + "```" + `[ \t]*(?:json|JSON)?[ \t]*\n?[ \t]*)?\{[ \t\n]*"name"[ \t]*:[ \t]*"([a-zA-Z_][a-zA-Z0-9_]*)"`,
+ )
)
// cleanToolCallArtifacts removes LLM-internal tool call format leakage from content.
@@ -86,6 +102,12 @@ func cleanToolCallArtifacts(content string) string {
content = strings.TrimSpace(content[:loc[0]])
}
+ // Plain-JSON tool-call leak from weak local models (qwen2.5 small).
+ // Allowlist-gated to avoid stripping legitimate user JSON.
+ if idx := findJSONToolCallLeak(content); idx >= 0 {
+ content = strings.TrimSpace(content[:idx])
+ }
+
return content
}
@@ -121,6 +143,32 @@ func containsToolCallMarker(content string) bool {
if minimaxMarkerRe.MatchString(content) {
return true
}
+ if findJSONToolCallLeak(content) >= 0 {
+ return true
+ }
return false
}
+
+// findJSONToolCallLeak returns the byte offset to strip from when a plain-JSON
+// tool-call leak is found, or -1 if none. A match must (a) sit at start of
+// content or after a newline, (b) be a JSON object whose first key is "name",
+// and (c) reference a tool in tools.IsKnownToolName's allowlist. Returning
+// the position of the leading newline (or 0) lets the caller preserve any
+// natural-language text before the leak via TrimSpace.
+func findJSONToolCallLeak(content string) int {
+ if content == "" {
+ return -1
+ }
+ matches := jsonToolCallRe.FindAllStringSubmatchIndex(content, -1)
+ for _, m := range matches {
+ if len(m) < 4 || m[2] < 0 || m[3] < 0 {
+ continue
+ }
+ name := content[m[2]:m[3]]
+ if tools.IsKnownToolName(name) {
+ return m[0]
+ }
+ }
+ return -1
+}
diff --git a/internal/ai/chat/agentic_sanitize_test.go b/internal/ai/chat/agentic_sanitize_test.go
index 1e2ac4004c..48538140ac 100644
--- a/internal/ai/chat/agentic_sanitize_test.go
+++ b/internal/ai/chat/agentic_sanitize_test.go
@@ -29,6 +29,59 @@ func TestCleanToolCallArtifacts(t *testing.T) {
{"minimax marker", "Response\nminimax:tool_call {\"name\":\"x\"}", "Response"},
{"only markers no content", "<tool_call>junk</tool_call>", ""},
{"whitespace before marker trimmed", "Hello \n<tool_call>x</tool_call>", "Hello"},
+
+ // Plain-JSON tool-call leak — qwen2.5 small models route the
+ // invocation into content instead of through tool_calls.
+ // Natural-language prose before the leak must be preserved.
+ {
+ "qwen2.5 leak: pulse_query get include",
+ "Para obtener la IP de cada nodo, necesito especificar el ID del recurso. Sin embargo, puedo intentar obtener la información de todos los nodos de una vez.\n\n{\"name\": \"pulse_query\", \"parameters\": {\"action\":\"get\",\"include\":\"ip\"}}",
+ "Para obtener la IP de cada nodo, necesito especificar el ID del recurso. Sin embargo, puedo intentar obtener la información de todos los nodos de una vez.",
+ },
+ {
+ "qwen2.5 leak: pulse_discovery get_node_ips",
+ "Voy a recoger las IPs de los nodos ahora.\n{\"name\": \"pulse_discovery\", \"parameters\": {\"action\":\"get_node_ips\"}}",
+ "Voy a recoger las IPs de los nodos ahora.",
+ },
+ {
+ "qwen2.5 leak: pulse_query resource_id",
+ "Looking up resource 233.\n{\"name\": \"pulse_query\", \"parameters\": {\"action\":\"get\",\"resource_id\":\"233\"}}",
+ "Looking up resource 233.",
+ },
+ {
+ "qwen2.5 leak with code-fence wrapper",
+ "Here's the call I want to make:\n```json\n{\"name\": \"pulse_query\", \"parameters\": {\"action\":\"get\"}}\n```",
+ "Here's the call I want to make:",
+ },
+ {
+ "qwen2.5 leak only no prose",
+ "{\"name\": \"pulse_query\", \"parameters\": {\"action\":\"get\"}}",
+ "",
+ },
+ // Negative: unrelated JSON the user might share — no "name" field
+ // matching an allowlisted tool, so the sanitiser leaves it alone.
+ {
+ "negative: unrelated JSON object",
+ "Here's some data: {\"foo\": \"bar\"}",
+ "Here's some data: {\"foo\": \"bar\"}",
+ },
+ {
+ "negative: JSON with name but not a tool",
+ "Resource: {\"name\": \"my-vm\", \"cpu\": 50}",
+ "Resource: {\"name\": \"my-vm\", \"cpu\": 50}",
+ },
+ {
+ "negative: name field not in allowlist",
+ "Strange output: {\"name\": \"frobnicate\", \"parameters\": {}}",
+ "Strange output: {\"name\": \"frobnicate\", \"parameters\": {}}",
+ },
+ // Edge: tool name appears as substring in prose — no JSON
+ // structure, so the regex does not fire.
+ {
+ "edge: tool name as substring in prose",
+ "You can call the pulse_query tool to look up resources.",
+ "You can call the pulse_query tool to look up resources.",
+ },
}
for _, tt := range tests {
@@ -64,6 +117,14 @@ func TestContainsToolCallMarker(t *testing.T) {
{"minimax marker", "minimax:tool_call {}", true},
{"minimax in middle", "text\nminimax:tool_call x", true},
{"partial minimax no match", "the minimax:tool_callx", false}, // \b prevents this
+
+ // Plain-JSON tool-call leak detection during streaming.
+ {"json leak pulse_query", "{\"name\": \"pulse_query\", \"parameters\": {}}", true},
+ {"json leak pulse_discovery", "prose\n{\"name\": \"pulse_discovery\", \"parameters\": {}}", true},
+ {"json leak with code-fence", "answer\n```json\n{\"name\": \"pulse_query\"}", true},
+ {"json non-tool name", "{\"name\": \"frobnicate\", \"parameters\": {}}", false},
+ {"json unrelated object", "{\"foo\": \"bar\"}", false},
+ {"tool name as prose substring", "the pulse_query tool is useful", false},
}
for _, tt := range tests {
diff --git a/internal/ai/tools/names.go b/internal/ai/tools/names.go
new file mode 100644
index 0000000000..075cf3aaa6
--- /dev/null
+++ b/internal/ai/tools/names.go
@@ -0,0 +1,46 @@
+package tools
+
+import "sync"
+
+// KnownToolNames returns the canonical list of registered Pulse tool names,
+// keyed off the registry built by registerTools(). The list is built lazily
+// on first call via a throwaway executor so adding a new tool to
+// registerTools() automatically extends the allowlist — no separate
+// hand-maintained list to drift out of sync.
+func KnownToolNames() []string {
+ initKnownToolNames()
+ out := make([]string, len(knownToolNamesList))
+ copy(out, knownToolNamesList)
+ return out
+}
+
+// IsKnownToolName reports whether name is one of the canonical Pulse tool
+// names. Used by chat-content sanitisers to gate stripping on a closed
+// allowlist (e.g. JSON tool-call shapes leaked by weak local models that
+// route the call into content instead of through the tool_calls channel).
+func IsKnownToolName(name string) bool {
+ if name == "" {
+ return false
+ }
+ initKnownToolNames()
+ _, ok := knownToolNamesSet[name]
+ return ok
+}
+
+var (
+ knownToolNamesOnce sync.Once
+ knownToolNamesList []string
+ knownToolNamesSet map[string]struct{}
+)
+
+func initKnownToolNames() {
+ knownToolNamesOnce.Do(func() {
+ e := NewPulseToolExecutor(ExecutorConfig{})
+ names := e.registry.allNames()
+ knownToolNamesList = names
+ knownToolNamesSet = make(map[string]struct{}, len(names))
+ for _, n := range names {
+ knownToolNamesSet[n] = struct{}{}
+ }
+ })
+}
diff --git a/internal/ai/tools/names_test.go b/internal/ai/tools/names_test.go
new file mode 100644
index 0000000000..bd21ed231c
--- /dev/null
+++ b/internal/ai/tools/names_test.go
@@ -0,0 +1,47 @@
+package tools
+
+import "testing"
+
+func TestKnownToolNamesIncludesRegisteredTools(t *testing.T) {
+ // Spot-check a representative subset of canonical names that should
+ // always be registered. Drift here means registerTools() lost a tool
+ // or KnownToolNames() stopped reading from the canonical registry.
+ expected := []string{
+ "pulse_query",
+ "pulse_discovery",
+ "pulse_read",
+ "pulse_summarize",
+ "pulse_control",
+ "pulse_metrics",
+ "pulse_storage",
+ "pulse_docker",
+ "pulse_kubernetes",
+ "pulse_alerts",
+ "pulse_file_edit",
+ "pulse_knowledge",
+ "pulse_pmg",
+ "patrol_report_finding",
+ "patrol_resolve_finding",
+ "patrol_get_findings",
+ }
+ for _, name := range expected {
+ if !IsKnownToolName(name) {
+ t.Errorf("IsKnownToolName(%q) = false, want true", name)
+ }
+ }
+}
+
+func TestIsKnownToolNameRejectsUnknown(t *testing.T) {
+ cases := []string{
+ "",
+ "frobnicate",
+ "my-vm",
+ "PULSE_QUERY", // case-sensitive
+ "pulse_unknown_tool",
+ }
+ for _, name := range cases {
+ if IsKnownToolName(name) {
+ t.Errorf("IsKnownToolName(%q) = true, want false", name)
+ }
+ }
+}
diff --git a/internal/ai/tools/registry.go b/internal/ai/tools/registry.go
index 7749dd8608..e33af20bd0 100644
--- a/internal/ai/tools/registry.go
+++ b/internal/ai/tools/registry.go
@@ -138,6 +138,16 @@ func normalizeToolGovernance(tool RegisteredTool) ToolGovernance {
return governance
}
+// allNames returns the canonical list of registered tool names in
+// registration order. Internal helper for KnownToolNames.
+func (r *ToolRegistry) allNames() []string {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ out := make([]string, len(r.order))
+ copy(out, r.order)
+ return out
+}
+
// Execute runs a tool by name
func (r *ToolRegistry) Execute(ctx context.Context, e *PulseToolExecutor, name string, args map[string]interface{}) (CallToolResult, error) {
r.mu.RLock()