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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Fix Assistant current-resource tool routing
rcourtman774d49e2a4ed
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.goindex 0ddee93dc2..efebf10951 100644--- a/internal/ai/chat/agentic.go+++ b/internal/ai/chat/agentic.go@@ -94,6 +94,122 @@ func fallbackProviderStreamErrorMessage(err error) string {return sanitizeProviderStreamErrorForUser(err.Error())}+func currentResourceUnavailableToolResult(err error) string {+ reason := "current_resource is unavailable because no single attached Pulse resource is selected in this chat turn"+ if err != nil && strings.TrimSpace(err.Error()) != "" {+ reason = strings.TrimSpace(err.Error())+ }+ return fmt.Sprintf(+ "CURRENT_RESOURCE_UNAVAILABLE: %s. Ask which host, VM, container, app, or storage resource the user means before calling resource-targeted tools. Do not retry this tool with current_resource until the user provides or opens a specific resource context.",+ reason,+ )+}++func toolInputContainsCurrentResourceReference(value interface{}) bool {+ switch v := value.(type) {+ case nil:+ return false+ case string:+ return tools.IsCurrentResourceReference(v)+ case map[string]interface{}:+ for _, child := range v {+ if toolInputContainsCurrentResourceReference(child) {+ return true+ }+ }+ case []interface{}:+ for _, child := range v {+ if toolInputContainsCurrentResourceReference(child) {+ return true+ }+ }+ case []string:+ for _, child := range v {+ if tools.IsCurrentResourceReference(child) {+ return true+ }+ }+ }+ return false+}++func (a *AgenticLoop) currentResourcePlaceholderBlock(tc providers.ToolCall) (string, bool) {+ if !toolInputContainsCurrentResourceReference(tc.Input) {+ return "", false+ }+ if a == nil || a.executor == nil {+ return currentResourceUnavailableToolResult(nil), true+ }+ if err := a.executor.ValidateCurrentResourceAvailable(); err != nil {+ return currentResourceUnavailableToolResult(err), true+ }+ return "", false+}++func removeToolCallFromResultMessages(messages []Message, toolUseID string) []Message {+ toolUseID = strings.TrimSpace(toolUseID)+ if toolUseID == "" {+ return messages+ }+ for idx := len(messages) - 1; idx >= 0; idx-- {+ if len(messages[idx].ToolCalls) == 0 {+ continue+ }+ filtered := messages[idx].ToolCalls[:0]+ for _, tc := range messages[idx].ToolCalls {+ if strings.TrimSpace(tc.ID) != toolUseID {+ filtered = append(filtered, tc)+ }+ }+ if len(filtered) == len(messages[idx].ToolCalls) {+ continue+ }+ messages[idx].ToolCalls = filtered+ if len(messages[idx].ToolCalls) == 0 && strings.TrimSpace(messages[idx].Content) == "" && messages[idx].ToolResult == nil {+ return append(messages[:idx], messages[idx+1:]...)+ }+ return messages+ }+ return messages+}++func toolStartKey(id, name string) string {+ if key := strings.TrimSpace(id); key != "" {+ return key+ }+ return strings.TrimSpace(name)+}++func emitToolStartEvent(callback StreamCallback, id, name string, input map[string]interface{}) {+ if callback == nil {+ return+ }+ inputStr, rawInput := formatToolInputForFrontend(name, input, false)+ jsonData, _ := json.Marshal(ToolStartData{+ ID: id,+ Name: name,+ Input: inputStr,+ RawInput: rawInput,+ })+ callback(StreamEvent{Type: "tool_start", Data: jsonData})+}++func emitToolEndEvent(callback StreamCallback, id, name string, input map[string]interface{}, output string, success bool) {+ if callback == nil {+ return+ }+ inputStr, rawInput := formatToolInputForFrontend(name, input, true)+ jsonData, _ := json.Marshal(ToolEndData{+ ID: id,+ Name: name,+ Input: inputStr,+ RawInput: rawInput,+ Output: output,+ Success: success,+ })+ callback(StreamEvent{Type: "tool_end", Data: jsonData})+}+// sanitizeProviderStreamErrorForUser turns a raw provider/transport error into a// clean, human message safe to render in the chat. Upstream errors (especially// from OpenAI-compatible gateways like OpenRouter) embed raw JSON bodies and@@ -542,6 +658,41 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, mevar toolCalls []providers.ToolCallvar suppressLeakedToolContent boolvar pendingVisibleContent string+ visibleToolStarts := make(map[string]bool)+ deferredToolStarts := make(map[string]providers.ToolStartEvent)+ suppressedToolStarts := make(map[string]bool)+ emitDeferredToolStart := func(tc providers.ToolCall) {+ key := toolStartKey(tc.ID, tc.Name)+ if key == "" || visibleToolStarts[key] || suppressedToolStarts[key] {+ return+ }+ if _, ok := deferredToolStarts[key]; !ok {+ return+ }+ emitToolStartEvent(callback, tc.ID, tc.Name, tc.Input)+ visibleToolStarts[key] = true+ }+ emitCurrentResourceBlock := func(tc providers.ToolCall, blockMsg string) {+ key := toolStartKey(tc.ID, tc.Name)+ if key != "" && visibleToolStarts[key] {+ emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, blockMsg, false)+ resultMessages = append(resultMessages, Message{+ ID: uuid.New().String(),+ Role: "user",+ Timestamp: time.Now(),+ ToolResult: &ToolResult{+ ToolUseID: tc.ID,+ Content: blockMsg,+ IsError: true,+ },+ })+ return+ }+ if key != "" {+ suppressedToolStarts[key] = true+ }+ resultMessages = removeToolCallFromResultMessages(resultMessages, tc.ID)+ }log.Debug().Str("session_id", sessionID).@@ -587,21 +738,33 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, mecase "tool_start":if data, ok := event.Data.(providers.ToolStartEvent); ok {- attemptEmittedVisibleEvents = true// pulse_question is rendered as a dedicated "question" card; suppress tool UI events.if data.Name == pulseQuestionToolName {return}- // Format input for frontend display- // For control tools, show a human-readable summary instead of raw JSON to avoid "hallucination" look- inputStr, rawInput := formatToolInputForFrontend(data.Name, data.Input, false)- jsonData, _ := json.Marshal(ToolStartData{- ID: data.ID,- Name: data.Name,- Input: inputStr,- RawInput: rawInput,- })- callback(StreamEvent{Type: "tool_start", Data: jsonData})+ key := toolStartKey(data.ID, data.Name)+ if len(data.Input) == 0 {+ if key != "" {+ deferredToolStarts[key] = data+ }+ return+ }+ if blockMsg, blocked := a.currentResourcePlaceholderBlock(providers.ToolCall{ID: data.ID, Name: data.Name, Input: data.Input}); blocked {+ log.Warn().+ Str("tool", data.Name).+ Str("id", data.ID).+ Str("reason", blockMsg).+ Msg("[AgenticLoop] Suppressed invalid current_resource tool_start before user-visible execution")+ if key != "" {+ suppressedToolStarts[key] = true+ }+ return+ }+ attemptEmittedVisibleEvents = true+ if key != "" {+ visibleToolStarts[key] = true+ }+ emitToolStartEvent(callback, data.ID, data.Name, data.Input)}case "done":@@ -882,6 +1045,25 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, metoolKind := ClassifyToolCall(tc.Name, tc.Input)+ if blockMsg, blocked := a.currentResourcePlaceholderBlock(tc); blocked {+ log.Warn().+ Str("tool", tc.Name).+ Str("id", tc.ID).+ Str("reason", blockMsg).+ Msg("[AgenticLoop] Blocked invalid current_resource tool call before interactive-set execution")++ emitCurrentResourceBlock(tc, blockMsg)+ providerMessages = append(providerMessages, providers.Message{+ Role: "user",+ ToolResult: &providers.ToolResult{+ ToolUseID: tc.ID,+ Content: truncateToolResultForModel(blockMsg),+ IsError: true,+ },+ })+ continue+ }+// FSM enforcement still applies (even if we're skipping execution).if fsm != nil {if fsmErr := fsm.CanExecuteTool(toolKind, tc.Name); fsmErr != nil {@@ -900,16 +1082,8 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me}}- inputStr, rawInput := formatToolInputForFrontend(tc.Name, tc.Input, true)- jsonData, _ := json.Marshal(ToolEndData{- ID: tc.ID,- Name: tc.Name,- Input: inputStr,- RawInput: rawInput,- Output: fsmErr.Error(),- Success: false,- })- callback(StreamEvent{Type: "tool_end", Data: jsonData})+ emitDeferredToolStart(tc)+ emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, fsmErr.Error(), false)toolResultMsg := Message{ID: uuid.New().String(),@@ -940,16 +1114,8 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meif recentCallCounts[callKey] > maxIdenticalCalls {loopMsg := fmt.Sprintf("LOOP_DETECTED: You have called %s with the same arguments %d times. This call is blocked. Try a different tool or approach.", tc.Name, recentCallCounts[callKey])- inputStr, rawInput := formatToolInputForFrontend(tc.Name, tc.Input, true)- jsonData, _ := json.Marshal(ToolEndData{- ID: tc.ID,- Name: tc.Name,- Input: inputStr,- RawInput: rawInput,- Output: loopMsg,- Success: false,- })- callback(StreamEvent{Type: "tool_end", Data: jsonData})+ emitDeferredToolStart(tc)+ emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, loopMsg, false)toolResultMsg := Message{ID: uuid.New().String(),@@ -977,16 +1143,8 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meif tc.Name != pulseQuestionToolName {skipMsg := fmt.Sprintf("SKIPPED: %s was requested this turn. Wait for the user's answer, then re-issue this tool call with the clarified inputs.", pulseQuestionToolName)- inputStr, rawInput := formatToolInputForFrontend(tc.Name, tc.Input, true)- jsonData, _ := json.Marshal(ToolEndData{- ID: tc.ID,- Name: tc.Name,- Input: inputStr,- RawInput: rawInput,- Output: skipMsg,- Success: false,- })- callback(StreamEvent{Type: "tool_end", Data: jsonData})+ emitDeferredToolStart(tc)+ emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, skipMsg, false)toolResultMsg := Message{ID: uuid.New().String(),@@ -1067,6 +1225,26 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me// === FSM ENFORCEMENT GATE 1: Check if tool is allowed in current state ===toolKind := ClassifyToolCall(tc.Name, tc.Input)++ if blockMsg, blocked := a.currentResourcePlaceholderBlock(tc); blocked {+ log.Warn().+ Str("tool", tc.Name).+ Str("id", tc.ID).+ Str("reason", blockMsg).+ Msg("[AgenticLoop] Blocked invalid current_resource tool call before execution")++ emitCurrentResourceBlock(tc, blockMsg)+ providerMessages = append(providerMessages, providers.Message{+ Role: "user",+ ToolResult: &providers.ToolResult{+ ToolUseID: tc.ID,+ Content: truncateToolResultForModel(blockMsg),+ IsError: true,+ },+ })+ continue+ }+if fsm != nil {if fsmErr := fsm.CanExecuteTool(toolKind, tc.Name); fsmErr != nil {log.Warn().@@ -1093,14 +1271,8 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me}// Send tool_end event with error- jsonData, _ := json.Marshal(ToolEndData{- ID: tc.ID,- Name: tc.Name,- Input: "",- Output: fsmErr.Error(),- Success: false,- })- callback(StreamEvent{Type: "tool_end", Data: jsonData})+ emitDeferredToolStart(tc)+ emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, fsmErr.Error(), false)// Create tool result message with the errortoolResultMsg := Message{@@ -1142,14 +1314,8 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meloopMsg := fmt.Sprintf("LOOP_DETECTED: You have called %s with the same arguments %d times. This call is blocked. Try a different tool or approach.", tc.Name, recentCallCounts[callKey])- jsonData, _ := json.Marshal(ToolEndData{- ID: tc.ID,- Name: tc.Name,- Input: "",- Output: loopMsg,- Success: false,- })- callback(StreamEvent{Type: "tool_end", Data: jsonData})+ emitDeferredToolStart(tc)+ emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, loopMsg, false)toolResultMsg := Message{ID: uuid.New().String(),@@ -1183,6 +1349,9 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me// Cap concurrency at 4 to avoid overwhelming infrastructure.execResults := make([]parallelToolResult, len(pendingExec))if len(pendingExec) > 0 {+ for _, pe := range pendingExec {+ emitDeferredToolStart(pe.tc)+ }executeMessage := "Running infrastructure checks."workflowTool := pendingExec[0].tc.Namefor _, pe := range pendingExec {diff --git a/internal/ai/chat/agentic_additional_test.go b/internal/ai/chat/agentic_additional_test.goindex 0f4ab2bdad..500436bd7b 100644--- a/internal/ai/chat/agentic_additional_test.go+++ b/internal/ai/chat/agentic_additional_test.go@@ -531,3 +531,89 @@ func TestAgenticLoop_DoesNotAutoRecoverStructuredToolCall(t *testing.T) {t.Fatalf("unexpected final response: %+v", results[2])}}++func TestAgenticLoop_HidesUnavailableCurrentResourceToolCall(t *testing.T) {+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})+ provider := &stubStreamingProvider{}+ loop := NewAgenticLoop(provider, executor, "prompt")++ var events []StreamEvent+ callCount := 0+ provider.chatStream = func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {+ callCount+++ switch callCount {+ case 1:+ callback(providers.StreamEvent{+ Type: "tool_start",+ Data: providers.ToolStartEvent{+ ID: "call-read-dev",+ Name: "pulse_read",+ },+ })+ callback(providers.StreamEvent{+ Type: "done",+ Data: providers.DoneEvent{+ ToolCalls: []providers.ToolCall{{+ ID: "call-read-dev",+ Name: "pulse_read",+ Input: map[string]interface{}{+ "action": "exec",+ "target_host": "current_resource",+ "command": "ls /dev | wc -l",+ },+ }},+ },+ })+ case 2:+ if len(req.Messages) != 3 {+ t.Fatalf("expected user, assistant tool call, and hidden tool result, got %d messages", len(req.Messages))+ }+ toolResult := req.Messages[2].ToolResult+ if toolResult == nil || !toolResult.IsError {+ t.Fatalf("expected hidden current_resource tool result error, got %+v", toolResult)+ }+ if !strings.Contains(toolResult.Content, "CURRENT_RESOURCE_UNAVAILABLE") {+ t.Fatalf("expected current resource block marker, got %q", toolResult.Content)+ }+ if !strings.Contains(toolResult.Content, "Ask which host, VM, container, app, or storage resource") {+ t.Fatalf("expected model-facing recovery instruction, got %q", toolResult.Content)+ }+ callback(providers.StreamEvent{+ Type: "content",+ Data: providers.ContentEvent{Text: "Which host, VM, container, app, or storage resource should I check?"},+ })+ callback(providers.StreamEvent{+ Type: "done",+ Data: providers.DoneEvent{},+ })+ default:+ t.Fatalf("unexpected provider call %d", callCount)+ }+ return nil+ }++ results, err := loop.Execute(context.Background(), "current-resource-hidden-block", []Message{{Role: "user", Content: "how many devices in this"}}, func(event StreamEvent) {+ events = append(events, event)+ })+ if err != nil {+ t.Fatalf("expected hidden current_resource recovery turn, got %v", err)+ }+ if callCount != 2 {+ t.Fatalf("expected recovery turn after hidden current_resource block, got %d provider calls", callCount)+ }+ for _, event := range events {+ switch event.Type {+ case "tool_start", "tool_end":+ t.Fatalf("current_resource placeholder block should not emit visible tool event: %+v", event)+ }+ }+ if len(results) != 1 {+ t.Fatalf("expected only final assistant message to be session-visible, got %d: %+v", len(results), results)+ }+ if len(results[0].ToolCalls) != 0 || results[0].ToolResult != nil {+ t.Fatalf("expected hidden placeholder call to be absent from session-visible messages, got %+v", results[0])+ }+ if !strings.Contains(results[0].Content, "Which host") {+ t.Fatalf("expected assistant to ask for target, got %q", results[0].Content)+ }+}diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 16b9782418..88e374fd7b 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -2861,6 +2861,7 @@ func (s *Service) buildSystemPrompt() string {- target_host specifies where commands run (host name, container name, or VM name)- Commands execute inside the target: target_host="homepage-docker" runs inside that container- For Docker containers inside system containers: target the container, then use docker commands+- The placeholder current_resource is valid only when this turn includes a Pulse resource-context handoff that explicitly says an attached resource is selected. If no attached resource context is present, do not use target_host="current_resource" or resource_id="current_resource"; ask which host, VM, container, app, or storage resource the user means, or use read-only query/search tools to identify an explicit target first.## DOCKER BIND MOUNTS- Container files are often mapped to host paths via bind mounts@@ -2876,6 +2877,7 @@ func (s *Service) buildSystemPrompt() string {- Status checks and monitoring are read-oriented; do not change state unless the user asked for a state change.- If you are missing critical information (target, risky choice, preference), pulse_question is available for structured clarification.- pulse_question is not available in autonomous mode; proceed with safe defaults and clearly state assumptions instead.+- Missing target information is not a safe default. In autonomous mode, ask for the missing target in normal assistant text instead of attempting a tool call with current_resource or another placeholder.## HOW TO RESPONDYou are like a colleague doing pair programming on infrastructure tasks. Tool calls are your internal investigation — the user sees your final synthesized response.diff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.goindex 72ba83e7b6..9da6bc17c0 100644--- a/internal/ai/chat/service_tooling_test.go+++ b/internal/ai/chat/service_tooling_test.go@@ -166,6 +166,23 @@ func TestBuildSystemPrompt_DoesNotClaimGenericVMControl(t *testing.T) {}}+func TestBuildSystemPrompt_CurrentResourceRequiresResourceHandoff(t *testing.T) {+ svc := &Service{}++ prompt := svc.buildSystemPrompt()++ for _, expected := range []string{+ "The placeholder current_resource is valid only when this turn includes a Pulse resource-context handoff",+ "If no attached resource context is present, do not use target_host=\"current_resource\" or resource_id=\"current_resource\"",+ "Missing target information is not a safe default.",+ "In autonomous mode, ask for the missing target in normal assistant text instead of attempting a tool call with current_resource",+ } {+ if !strings.Contains(prompt, expected) {+ t.Fatalf("expected current_resource boundary %q in system prompt, got %q", expected, prompt)+ }+ }+}+func TestBuildToolGovernancePromptSection_FallbackDiscoveryMatchesRunContract(t *testing.T) {svc := &Service{}diff --git a/internal/ai/tools/current_resource.go b/internal/ai/tools/current_resource.goindex 8945fab7c0..194499516c 100644--- a/internal/ai/tools/current_resource.go+++ b/internal/ai/tools/current_resource.go@@ -23,9 +23,23 @@ func isCurrentResourceReference(value string) bool {}}+// IsCurrentResourceReference reports whether a tool argument is one of the+// session-scoped placeholders that must resolve through attached resource+// context before execution.+func IsCurrentResourceReference(value string) bool {+ return isCurrentResourceReference(value)+}++// ValidateCurrentResourceAvailable checks whether the session currently has a+// single attached resource that can satisfy current_resource placeholders.+func (e *PulseToolExecutor) ValidateCurrentResourceAvailable() error {+ _, err := e.resolveCurrentResource()+ return err+}+func (e *PulseToolExecutor) resolveCurrentResource() (ResolvedResourceInfo, error) {if e == nil || e.resolvedContext == nil {- return nil, fmt.Errorf("%s is unavailable because no resource context is attached", currentResourceHandle)+ return nil, fmt.Errorf("%s is unavailable because no Pulse resource context is attached to this chat turn", currentResourceHandle)}recentIDs := e.resolvedContext.GetRecentlyAccessedResources(currentResourceSelectionWindow)@@ -50,11 +64,11 @@ func (e *PulseToolExecutor) resolveCurrentResource() (ResolvedResourceInfo, erroswitch len(resolved) {case 0:- return nil, fmt.Errorf("%s is unavailable because no single attached resource is selected", currentResourceHandle)+ return nil, fmt.Errorf("%s is unavailable because no single attached resource is selected in this chat turn", currentResourceHandle)case 1:return resolved[0], nildefault:- return nil, fmt.Errorf("%s is ambiguous because multiple resources were recently selected; use pulse_query get for the intended resource first", currentResourceHandle)+ return nil, fmt.Errorf("%s is ambiguous because multiple resources were recently selected; ask which host, VM, container, app, or storage resource the user means", currentResourceHandle)}}@@ -116,7 +130,7 @@ func resolvedResourceKindMatchesLocation(resource ResolvedResourceInfo, locTypefunc (e *PulseToolExecutor) commandTargetForResolvedResource(resource ResolvedResourceInfo) (string, error) {if resource == nil {- return "", fmt.Errorf("%s is unavailable because no resource context is attached", currentResourceHandle)+ return "", fmt.Errorf("%s is unavailable because no Pulse resource context is attached to this chat turn", currentResourceHandle)}candidates := append([]string(nil), resource.GetAliases()...)