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.

Scope Assistant fast inventory turns

rcourtman17c4c1c17226
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index c5b7e534ff..01d39b8feb 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -147,6 +147,25 @@ runtime cost control, and shared AI transport surfaces.
startup failures may retry once before surfacing failed-turn recovery, but a
stalled route must not leave the user in an opaque first-token wait for the
full provider timeout.
+ Assistant turn tool exposure is backend-owned runtime behavior, not a
+ provider whim or frontend polish concern. Normal diagnostic, log, command,
+ repair, and governed-action prompts keep the full governed tool manifest so
+ the selected model owns investigation and action choice inside Pulse policy.
+ Direct text turns such as exact-reply diagnostics must withhold tools and
+ use a scoped system prompt that does not advertise unavailable tools.
+ Inventory, count, overview, and status prompts that only need canonical
+ Pulse resource state must expose the canonical query/clarification path
+ instead of shell/read/control tools, so prompts like "how many devices in
+ this" route toward Pulse inventory rather than `/dev` inspection. Those
+ count/overview turns may prefetch a bounded canonical inventory summary
+ before the model request and then withhold tools so the first visible answer
+ is fast and cannot drift into shell inspection. If a query-only turn still
+ reaches a model-owned `pulse_query` topology call, omitting `summary_only`
+ must default to summary-only before execution; detailed topology remains
+ available in the full governed path or when the model explicitly asks for
+ detail. The system prompt for a turn must describe only the tools actually
+ offered to the provider for that turn; generic tool-governance prose must not
+ name tools hidden from the current manifest.
Restored Assistant sessions must hydrate saved assistant content and
persisted tool calls into the same transcript event shape used by live
streams so switching sessions does not hide prior tool evidence or collapse
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index f041a8fa42..26adba33dd 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -180,6 +180,25 @@ func toolStartKey(id, name string) string {
return strings.TrimSpace(name)
}
+func normalizeSummaryOnlyPulseQueryInput(prefer bool, name string, input map[string]interface{}) map[string]interface{} {
+ if !prefer || name != "pulse_query" || len(input) == 0 {
+ return input
+ }
+ action, _ := input["action"].(string)
+ if strings.ToLower(strings.TrimSpace(action)) != "topology" {
+ return input
+ }
+ if _, exists := input["summary_only"]; exists {
+ return input
+ }
+ normalized := make(map[string]interface{}, len(input)+1)
+ for key, value := range input {
+ normalized[key] = value
+ }
+ normalized["summary_only"] = true
+ return normalized
+}
+
func emitToolStartEvent(callback StreamCallback, id, name string, input map[string]interface{}) {
if callback == nil {
return
@@ -378,6 +397,10 @@ type AgenticLoop struct {
// emitting a stream error event. The chat service uses this to try another
// configured provider before the browser sees a failed first attempt.
suppressProviderErrorEvents bool
+
+ // Query-only count/overview turns should not let a provider accidentally
+ // expand a topology request into the full infrastructure tree.
+ preferSummaryOnlyQueries bool
}
// NewAgenticLoop creates a new agentic loop
@@ -421,6 +444,12 @@ func (a *AgenticLoop) SetSuppressProviderErrorEvents(suppress bool) {
a.suppressProviderErrorEvents = suppress
}
+func (a *AgenticLoop) SetPreferSummaryOnlyQueries(prefer bool) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.preferSummaryOnlyQueries = prefer
+}
+
// SetOrgID sets the org scope used when validating approval decisions.
func (a *AgenticLoop) SetOrgID(orgID string) {
a.mu.Lock()
@@ -511,6 +540,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
providerName := a.providerName
modelName := a.modelName
requestSanitizer := a.requestSanitizer
+ preferSummaryOnlyQueries := a.preferSummaryOnlyQueries
a.mu.Unlock()
// Record telemetry for loop iteration
@@ -754,6 +784,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
if data.Name == pulseQuestionToolName {
return
}
+ data.Input = normalizeSummaryOnlyPulseQueryInput(preferSummaryOnlyQueries, data.Name, data.Input)
key := toolStartKey(data.ID, data.Name)
if len(data.Input) == 0 {
if key != "" {
@@ -783,6 +814,11 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
if data, ok := event.Data.(providers.DoneEvent); ok {
attemptSawDone = true
toolCalls = data.ToolCalls
+ if preferSummaryOnlyQueries {
+ for i := range toolCalls {
+ toolCalls[i].Input = normalizeSummaryOnlyPulseQueryInput(true, toolCalls[i].Name, toolCalls[i].Input)
+ }
+ }
a.totalInputTokens += data.InputTokens
a.totalOutputTokens += data.OutputTokens
log.Info().
diff --git a/internal/ai/chat/agentic_additional_test.go b/internal/ai/chat/agentic_additional_test.go
index 500436bd7b..102339548e 100644
--- a/internal/ai/chat/agentic_additional_test.go
+++ b/internal/ai/chat/agentic_additional_test.go
@@ -257,6 +257,29 @@ func TestExecuteToolSafely_RecoversPanic(t *testing.T) {
}
}
+func TestNormalizeSummaryOnlyPulseQueryInput_DefaultsTopologyForQueryOnlyTurns(t *testing.T) {
+ input := map[string]interface{}{"action": "topology", "include": "all"}
+
+ got := normalizeSummaryOnlyPulseQueryInput(true, "pulse_query", input)
+
+ if got["summary_only"] != true {
+ t.Fatalf("expected summary_only=true, got %#v", got)
+ }
+ if _, exists := input["summary_only"]; exists {
+ t.Fatalf("normalization must not mutate provider-owned input map: %#v", input)
+ }
+}
+
+func TestNormalizeSummaryOnlyPulseQueryInput_PreservesExplicitTopologyChoice(t *testing.T) {
+ input := map[string]interface{}{"action": "topology", "summary_only": false}
+
+ got := normalizeSummaryOnlyPulseQueryInput(true, "pulse_query", input)
+
+ if got["summary_only"] != false {
+ t.Fatalf("expected summary_only=false to remain explicit, got %#v", got)
+ }
+}
+
func TestAgenticLoop_RetriesProviderStreamBeforeEvents(t *testing.T) {
provider := &stubStreamingProvider{}
executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index f14492b71e..b3c6166361 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -759,9 +759,25 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
}
// Run agentic loop
- filteredTools := s.toolsForExecutionMode(autonomousMode, false)
+ hasModelHandoffContext := handoffContext != "" ||
+ len(handoffResources) > 0 ||
+ len(handoffActions) > 0 ||
+ handoffFindingID != "" ||
+ !handoffMetadataEmpty(handoffMetadata)
+ assistantToolScope := assistantToolScopeForPrompt(req.Prompt, hasModelHandoffContext)
+ if assistantToolScope == assistantTurnToolScopeQueryOnly {
+ if summaryContext := s.prefetchAssistantInventorySummaryContext(ctx, baseExecutor); summaryContext != "" {
+ injectHandoffContextIntoLatestUserMessage(messages, summaryContext)
+ assistantToolScope = assistantTurnToolScopeTextOnly
+ log.Debug().
+ Str("session_id", session.ID).
+ Msg("[ChatService] Prefetched canonical inventory summary for query-only Assistant turn")
+ }
+ }
+ filteredTools := s.toolsForAssistantTurnWithScope(assistantToolScope, autonomousMode, false)
if resourceContextTurnIsContextOnly(req.Prompt, handoffResources, handoffMetadata) {
filteredTools = []providers.Tool{}
+ assistantToolScope = assistantTurnToolScopeTextOnly
log.Debug().
Str("session_id", session.ID).
Msg("[ChatService] Withholding tools for context-only resource handoff turn")
@@ -819,10 +835,11 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
// concurrent sessions and provider fallback attempts. This prevents race
// conditions where ExecuteStream calls overwrite each other's FSM,
// knowledge accumulator, autonomous mode, budget checker, and provider info.
- systemPrompt := s.buildSystemPrompt()
+ systemPrompt := s.buildSystemPromptForOfferedTools(filteredTools)
loop := NewAgenticLoop(attemptProvider, executor, systemPrompt)
loop.SetOrgID(s.orgID)
loop.SetAutonomousMode(autonomousMode)
+ loop.SetPreferSummaryOnlyQueries(assistantToolScope == assistantTurnToolScopeQueryOnly)
loop.SetRequestSanitizer(modelboundary.RequestSanitizerForModel(attempt.Model, unifiedResourceProvider))
loop.SetSuppressProviderErrorEvents(true)
loop.SetSessionFSM(sessionFSM)
@@ -953,6 +970,29 @@ func injectHandoffContextIntoLatestUserMessage(messages []Message, handoffContex
}
}
+func (s *Service) prefetchAssistantInventorySummaryContext(ctx context.Context, executor *tools.PulseToolExecutor) string {
+ if executor == nil {
+ return ""
+ }
+ result, err := executor.ExecuteTool(ctx, "pulse_query", map[string]interface{}{
+ "action": "topology",
+ "summary_only": true,
+ })
+ if err != nil || result.IsError {
+ log.Debug().
+ Err(err).
+ Bool("tool_error", result.IsError).
+ Msg("[ChatService] Unable to prefetch Assistant inventory summary")
+ return ""
+ }
+ resultText := strings.TrimSpace(FormatToolResult(result))
+ if resultText == "" {
+ return ""
+ }
+ return "Pulse inventory summary from current canonical resource state. Use this context to answer the user's count, overview, or status question. Do not claim shell inspection or host command execution.\n" +
+ truncateToolResultForModel(resultText)
+}
+
func sanitizeHandoffContextForResourcePolicy(handoffContext string, handoffResources []HandoffResource, provider tools.UnifiedResourceProvider) string {
return sanitizeTextForHandoffResourcePolicy(handoffContext, handoffResources, provider)
}
@@ -3041,9 +3081,17 @@ func (s *Service) applyChatContextSettings() {
// selection remains model-owned; Pulse enforces safety after a model choice via
// tool policy, approvals, and FSM verification gates.
func (s *Service) buildSystemPrompt() string {
+ return s.buildSystemPromptWithToolGovernance(s.buildToolGovernancePromptSection())
+}
+
+func (s *Service) buildSystemPromptForOfferedTools(offeredTools []providers.Tool) string {
+ return s.buildSystemPromptWithToolGovernance(s.buildToolGovernancePromptSectionForOfferedTools(offeredTools))
+}
+
+func (s *Service) buildSystemPromptWithToolGovernance(toolGovernance string) string {
return `You are Pulse AI, a knowledgeable infrastructure assistant. You pair-program with the user on their homelab and infrastructure tasks.
-` + s.buildToolGovernancePromptSection() + `
+` + toolGovernance + `
## INFRASTRUCTURE TOPOLOGY
- Resources are organized hierarchically: nodes → VMs/containers → Docker containers
@@ -3058,14 +3106,14 @@ func (s *Service) buildSystemPrompt() string {
- Bind mount mappings may be available in Pulse discovery context or tools when needed
## TOOL SELECTION
-- Tool action modes and approval policies are generated from Pulse's tool registry. Treat that manifest as the source of truth for whether a tool is read-only, mixed, or write-capable.
-- pulse_control and pulse_file_edit are WRITE tools — they change infrastructure state.
-- pulse_docker, pulse_kubernetes, pulse_alerts, and pulse_knowledge are MIXED tools — their read subactions are safe, but their write or decision-recording subactions require the governed path described in the manifest.
+- Tool action modes and approval policies are generated from Pulse's tool registry. Treat the available-tool manifest for this turn as the source of truth for which tools exist and whether each tool is read-only, mixed, or write-capable.
+- Use only tools that are explicitly offered in this turn's available-tool manifest.
+- Write tools change infrastructure state. Mixed tools may include read subactions and write or decision-recording subactions; follow the governed path described in the manifest.
- Not every VM or container supports control. Some API-backed platforms are read-only even when the resource type is "vm" or "system-container".
- Write tools are allowed only when the user explicitly asks you to perform an action.
- 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.
+- If a structured clarification tool is offered and you are missing critical information (target, risky choice, preference), use it.
+- If no structured clarification tool is offered, ask for missing information in normal assistant text.
- 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 RESPOND
@@ -3088,6 +3136,42 @@ You are like a colleague doing pair programming on infrastructure tasks. Tool ca
}
func (s *Service) buildToolGovernancePromptSection() string {
+ return s.buildToolGovernancePromptSectionForOfferedToolNames(nil)
+}
+
+func (s *Service) buildToolGovernancePromptSectionForOfferedTools(offeredTools []providers.Tool) string {
+ offeredNames := make(map[string]bool, len(offeredTools))
+ orderedOfferedNames := make([]string, 0, len(offeredTools))
+ for _, tool := range offeredTools {
+ name := strings.TrimSpace(tool.Name)
+ if name == "" || offeredNames[name] {
+ continue
+ }
+ offeredNames[name] = true
+ orderedOfferedNames = append(orderedOfferedNames, name)
+ }
+ return s.buildToolGovernancePromptSectionForOfferedToolNames(orderedOfferedNames)
+}
+
+func (s *Service) buildToolGovernancePromptSectionForOfferedToolNames(orderedOfferedNames []string) string {
+ offeredFilter := map[string]bool(nil)
+ if orderedOfferedNames != nil {
+ offeredFilter = make(map[string]bool, len(orderedOfferedNames))
+ for _, name := range orderedOfferedNames {
+ if trimmed := strings.TrimSpace(name); trimmed != "" {
+ offeredFilter[trimmed] = true
+ }
+ }
+ }
+
+ if offeredFilter != nil && len(offeredFilter) == 0 {
+ return strings.Join([]string{
+ "## AVAILABLE TOOL GOVERNANCE",
+ "No Pulse tools are offered for this turn. Answer directly from the user's message and safe conversation context.",
+ "Do not claim to inspect infrastructure, run commands, or use Pulse data unless that evidence is already present in the conversation.",
+ }, "\n")
+ }
+
manifest := []tools.ToolGovernanceDescriptor(nil)
if s != nil && s.executor != nil {
manifest = s.executor.ListToolGovernance()
@@ -3099,7 +3183,11 @@ func (s *Service) buildToolGovernancePromptSection() string {
var b strings.Builder
b.WriteString("## AVAILABLE TOOL GOVERNANCE\n")
b.WriteString("This manifest is generated from Pulse's governed tool registry. Use only tools that are actually offered by the provider for the current turn.\n")
+ emitted := make(map[string]bool, len(manifest))
for _, tool := range manifest {
+ if offeredFilter != nil && !offeredFilter[tool.Name] {
+ continue
+ }
mode := tool.ActionMode
if mode == "" {
mode = tools.ToolActionRead
@@ -3117,8 +3205,22 @@ func (s *Service) buildToolGovernancePromptSection() string {
} else {
b.WriteString(fmt.Sprintf("- %s: mode=%s; approval=%s\n", tool.Name, mode, policy))
}
+ emitted[tool.Name] = true
+ }
+
+ if offeredFilter == nil || offeredFilter[pulseQuestionToolName] {
+ b.WriteString("- pulse_question: mode=interactive; approval=user answer required; asks the user for missing information using a structured prompt in interactive chat only.\n")
+ emitted[pulseQuestionToolName] = true
+ }
+ if offeredFilter != nil {
+ for _, name := range orderedOfferedNames {
+ if emitted[name] {
+ continue
+ }
+ b.WriteString(fmt.Sprintf("- %s: mode=read; approval=no approval required; Offered by Pulse for this turn.\n", name))
+ emitted[name] = true
+ }
}
- b.WriteString("- pulse_question: mode=interactive; approval=user answer required; asks the user for missing information using a structured prompt in interactive chat only.\n")
return strings.TrimRight(b.String(), "\n")
}
@@ -3360,6 +3462,259 @@ func (s *Service) toolsForExecutionMode(autonomousMode bool, patrolMode bool) []
return filtered
}
+type assistantTurnToolScope string
+
+const (
+ assistantTurnToolScopeFull assistantTurnToolScope = "full"
+ assistantTurnToolScopeQueryOnly assistantTurnToolScope = "query-only"
+ assistantTurnToolScopeTextOnly assistantTurnToolScope = "text-only"
+)
+
+func (s *Service) toolsForAssistantTurn(prompt string, autonomousMode bool, patrolMode bool, hasModelContext bool) []providers.Tool {
+ scope := assistantToolScopeForPrompt(prompt, hasModelContext)
+ return s.toolsForAssistantTurnWithScope(scope, autonomousMode, patrolMode)
+}
+
+func (s *Service) toolsForAssistantTurnWithScope(scope assistantTurnToolScope, autonomousMode bool, patrolMode bool) []providers.Tool {
+ fullTools := s.toolsForExecutionMode(autonomousMode, patrolMode)
+ if patrolMode {
+ return fullTools
+ }
+
+ switch scope {
+ case assistantTurnToolScopeTextOnly:
+ log.Debug().
+ Str("tool_scope", string(scope)).
+ Bool("autonomous", autonomousMode).
+ Msg("[toolsForAssistantTurn] Withholding tools for direct text turn")
+ return []providers.Tool{}
+ case assistantTurnToolScopeQueryOnly:
+ allowed := map[string]bool{"pulse_query": true}
+ if !autonomousMode {
+ allowed[pulseQuestionToolName] = true
+ }
+ filtered := filterProviderToolsByName(fullTools, allowed)
+ log.Debug().
+ Str("tool_scope", string(scope)).
+ Int("tool_manifest_count", len(filtered)).
+ Bool("autonomous", autonomousMode).
+ Msg("[toolsForAssistantTurn] Scoped Assistant turn to canonical query tools")
+ return filtered
+ default:
+ return fullTools
+ }
+}
+
+func filterProviderToolsByName(providerTools []providers.Tool, allowed map[string]bool) []providers.Tool {
+ if len(providerTools) == 0 || len(allowed) == 0 {
+ return []providers.Tool{}
+ }
+ filtered := make([]providers.Tool, 0, len(providerTools))
+ for _, tool := range providerTools {
+ if allowed[tool.Name] {
+ filtered = append(filtered, tool)
+ }
+ }
+ return filtered
+}
+
+func assistantToolScopeForPrompt(prompt string, hasModelContext bool) assistantTurnToolScope {
+ if hasModelContext {
+ return assistantTurnToolScopeFull
+ }
+ normalized := normalizeAssistantToolRoutingPrompt(prompt)
+ if normalized == "" {
+ return assistantTurnToolScopeTextOnly
+ }
+ if assistantPromptRequestsDirectText(normalized) {
+ return assistantTurnToolScopeTextOnly
+ }
+ if assistantPromptNeedsFullToolManifest(normalized) {
+ return assistantTurnToolScopeFull
+ }
+ if assistantPromptIsInventoryQuery(normalized) {
+ return assistantTurnToolScopeQueryOnly
+ }
+ if assistantPromptLooksConversational(normalized) {
+ return assistantTurnToolScopeTextOnly
+ }
+ return assistantTurnToolScopeFull
+}
+
+func normalizeAssistantToolRoutingPrompt(prompt string) string {
+ normalized := strings.ToLower(strings.TrimSpace(prompt))
+ if normalized == "" {
+ return ""
+ }
+ replacer := strings.NewReplacer(
+ "\n", " ",
+ "\r", " ",
+ "\t", " ",
+ ".", " ",
+ ",", " ",
+ ";", " ",
+ ":", " ",
+ "!", " ",
+ "?", " ",
+ "(", " ",
+ ")", " ",
+ "[", " ",
+ "]", " ",
+ "{", " ",
+ "}", " ",
+ "\"", " ",
+ "'", " ",
+ )
+ return " " + strings.Join(strings.Fields(replacer.Replace(normalized)), " ") + " "
+}
+
+func assistantPromptRequestsDirectText(normalized string) bool {
+ return assistantPromptContainsAny(normalized, []string{
+ " reply exactly ",
+ " respond exactly ",
+ " answer exactly ",
+ " say exactly ",
+ " output exactly ",
+ " print exactly ",
+ " echo exactly ",
+ " repeat exactly ",
+ " just say ",
+ " say only ",
+ " reply only ",
+ " respond only ",
+ })
+}
+
+func assistantPromptNeedsFullToolManifest(normalized string) bool {
+ return assistantPromptContainsAny(normalized, []string{
+ " run ",
+ " execute ",
+ " command ",
+ " shell ",
+ " terminal ",
+ " ssh ",
+ " log ",
+ " logs ",
+ " journal ",
+ " tail ",
+ " grep ",
+ " cat ",
+ " file ",
+ " path ",
+ " inspect ",
+ " troubleshoot ",
+ " diagnose ",
+ " investigate ",
+ " fix ",
+ " repair ",
+ " restart ",
+ " start ",
+ " stop ",
+ " shutdown ",
+ " reboot ",
+ " delete ",
+ " remove ",
+ " edit ",
+ " change ",
+ " configure ",
+ " create ",
+ " install ",
+ " update ",
+ " upgrade ",
+ " deploy ",
+ " scale ",
+ " backup ",
+ " restore ",
+ " snapshot ",
+ " approve ",
+ " deny ",
+ " cpu ",
+ " memory ",
+ " disk ",
+ " temperature ",
+ " latency ",
+ " error ",
+ " errors ",
+ })
+}
+
+func assistantPromptIsInventoryQuery(normalized string) bool {
+ hasInventoryNoun := assistantPromptContainsAny(normalized, []string{
+ " device ",
+ " devices ",
+ " resource ",
+ " resources ",
+ " system ",
+ " systems ",
+ " node ",
+ " nodes ",
+ " workload ",
+ " workloads ",
+ " vm ",
+ " vms ",
+ " container ",
+ " containers ",
+ " lxc ",
+ " lxcs ",
+ " host ",
+ " hosts ",
+ " service ",
+ " services ",
+ " cluster ",
+ " clusters ",
+ })
+ if !hasInventoryNoun {
+ return false
+ }
+ return assistantPromptContainsAny(normalized, []string{
+ " how many ",
+ " count ",
+ " counts ",
+ " total ",
+ " totals ",
+ " list ",
+ " show ",
+ " overview ",
+ " status ",
+ " running ",
+ " stopped ",
+ " online ",
+ " offline ",
+ " what is in ",
+ " what s in ",
+ " what are in ",
+ " what do i have ",
+ })
+}
+
+func assistantPromptLooksConversational(normalized string) bool {
+ trimmed := strings.TrimSpace(normalized)
+ if trimmed == "" {
+ return true
+ }
+ if assistantPromptContainsAny(normalized, []string{
+ " hello ",
+ " hi ",
+ " hey ",
+ " thanks ",
+ " thank you ",
+ " who are you ",
+ " what can you do ",
+ }) {
+ return true
+ }
+ return len(strings.Fields(trimmed)) <= 3
+}
+
+func assistantPromptContainsAny(normalized string, needles []string) bool {
+ for _, needle := range needles {
+ if strings.Contains(normalized, needle) {
+ return true
+ }
+ }
+ return false
+}
+
// filterToolsForPatrol applies explicit Patrol subsystem scope settings. It
// must not inspect prompt text or infer which tool the model should use.
func (s *Service) filterToolsForPatrol(providerTools []providers.Tool) []providers.Tool {
diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.go
index 6ce028b20c..146de345a4 100644
--- a/internal/ai/chat/service_execute_additional_test.go
+++ b/internal/ai/chat/service_execute_additional_test.go
@@ -580,7 +580,7 @@ func TestService_ExecuteStream_InteractiveChatLetsModelChooseTools(t *testing.T)
workflowEvents := 0
err = service.ExecuteStream(context.Background(), ExecuteRequest{
SessionID: "interactive-chat-model-choice",
- Prompt: "test",
+ Prompt: "show me the logs for vm 100",
}, func(event StreamEvent) {
switch event.Type {
case "explore_status":
@@ -603,6 +603,60 @@ func TestService_ExecuteStream_InteractiveChatLetsModelChooseTools(t *testing.T)
}
}
+func TestService_ExecuteStream_InventoryCountPrefetchesSummaryWithoutTools(t *testing.T) {
+ tmpDir := t.TempDir()
+ store, err := NewSessionStore(tmpDir)
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ var capturedReq providers.ChatRequest
+ provider := &stubServiceProvider{
+ streamFn: func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ capturedReq = req
+ callback(providers.StreamEvent{
+ Type: "content",
+ Data: providers.ContentEvent{Text: "You have 0 resources."},
+ })
+ callback(providers.StreamEvent{
+ Type: "done",
+ Data: providers.DoneEvent{InputTokens: 1, OutputTokens: 1},
+ })
+ return nil
+ },
+ }
+
+ service := NewService(Config{
+ AIConfig: &config.AIConfig{ControlLevel: config.ControlLevelControlled},
+ StateProvider: &mockStateProvider{},
+ AgentServer: &mockAgentServer{},
+ })
+ service.sessions = store
+ service.provider = provider
+ service.started = true
+
+ err = service.ExecuteStream(context.Background(), ExecuteRequest{
+ SessionID: "inventory-count-fast-path",
+ Prompt: "how many devices in this",
+ }, func(event StreamEvent) {})
+ if err != nil {
+ t.Fatalf("ExecuteStream failed: %v", err)
+ }
+ if len(capturedReq.Tools) != 0 {
+ t.Fatalf("expected prefetched inventory count turn to withhold tools, got %d", len(capturedReq.Tools))
+ }
+ if len(capturedReq.Messages) == 0 {
+ t.Fatal("expected provider request messages")
+ }
+ lastMessage := capturedReq.Messages[len(capturedReq.Messages)-1].Content
+ if !strings.Contains(lastMessage, "Pulse inventory summary from current canonical resource state") {
+ t.Fatalf("expected prefetched inventory summary context, got %q", lastMessage)
+ }
+ if !strings.Contains(lastMessage, "User message: how many devices in this") {
+ t.Fatalf("expected original user message to remain visible to the model, got %q", lastMessage)
+ }
+}
+
func TestResourceContextTurnIsContextOnly(t *testing.T) {
resources := []HandoffResource{{ID: "system-container:ha-node:101", Name: "homeassistant", Type: "system-container"}}
metadata := HandoffMetadata{Kind: "resource_context"}
diff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.go
index 9da6bc17c0..25602568f9 100644
--- a/internal/ai/chat/service_tooling_test.go
+++ b/internal/ai/chat/service_tooling_test.go
@@ -123,6 +123,100 @@ func TestToolsForExecutionMode_InteractiveExposesGovernedTools(t *testing.T) {
}
}
+func TestToolsForAssistantTurn_DirectTextWithholdsTools(t *testing.T) {
+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{
+ StateProvider: fakeStateProvider{},
+ AgentServer: fakeAgentServer{},
+ ReadState: &fakeCanonicalReadState{},
+ ControlLevel: tools.ControlLevelControlled,
+ })
+
+ svc := &Service{executor: exec}
+ toolsList := svc.toolsForAssistantTurn("Reply exactly: PULSE_CHAT_OK", false, false, false)
+
+ if len(toolsList) != 0 {
+ t.Fatalf("expected direct text turn to withhold tools, got %#v", toolNameSet(toolsList))
+ }
+ prompt := svc.buildSystemPromptForOfferedTools(toolsList)
+ if strings.Contains(prompt, "pulse_query") || strings.Contains(prompt, "pulse_read") {
+ t.Fatalf("expected text-only system prompt not to advertise tools, got %q", prompt)
+ }
+ if !strings.Contains(prompt, "No Pulse tools are offered for this turn") {
+ t.Fatalf("expected text-only system prompt to state the tool boundary, got %q", prompt)
+ }
+}
+
+func TestToolsForAssistantTurn_InventoryCountUsesQueryOnly(t *testing.T) {
+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{
+ StateProvider: fakeStateProvider{},
+ AgentServer: fakeAgentServer{},
+ ReadState: &fakeCanonicalReadState{},
+ ControlLevel: tools.ControlLevelControlled,
+ })
+
+ svc := &Service{executor: exec}
+ toolsList := svc.toolsForAssistantTurn("how many devices in this", false, false, false)
+ set := toolNameSet(toolsList)
+
+ if !set["pulse_query"] {
+ t.Fatalf("expected inventory count prompt to expose pulse_query, got %#v", set)
+ }
+ if !set[pulseQuestionToolName] {
+ t.Fatalf("expected interactive inventory prompt to keep clarification available, got %#v", set)
+ }
+ for _, blocked := range []string{"pulse_read", "pulse_control", "pulse_file_edit", "pulse_docker"} {
+ if set[blocked] {
+ t.Fatalf("expected inventory count prompt not to expose %s, got %#v", blocked, set)
+ }
+ }
+
+ prompt := svc.buildSystemPromptForOfferedTools(toolsList)
+ if !strings.Contains(prompt, "pulse_query: mode=read") {
+ t.Fatalf("expected query-only system prompt to advertise pulse_query, got %q", prompt)
+ }
+ if strings.Contains(prompt, "pulse_read") || strings.Contains(prompt, "pulse_control") {
+ t.Fatalf("expected query-only system prompt not to advertise shell/control tools, got %q", prompt)
+ }
+}
+
+func TestToolsForAssistantTurn_ActionAndDiagnosticsKeepFullManifest(t *testing.T) {
+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{
+ StateProvider: fakeStateProvider{},
+ AgentServer: fakeAgentServer{},
+ ReadState: &fakeCanonicalReadState{},
+ ControlLevel: tools.ControlLevelControlled,
+ })
+
+ svc := &Service{executor: exec}
+ for _, prompt := range []string{
+ "show me the logs for vm 100",
+ "restart vm 100",
+ "diagnose high cpu on minipc",
+ } {
+ toolsList := svc.toolsForAssistantTurn(prompt, false, false, false)
+ set := toolNameSet(toolsList)
+ if !set["pulse_read"] || !set["pulse_control"] || !set["pulse_query"] {
+ t.Fatalf("expected full manifest for %q, got %#v", prompt, set)
+ }
+ }
+}
+
+func TestToolsForAssistantTurn_ModelHandoffKeepsFullManifest(t *testing.T) {
+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{
+ StateProvider: fakeStateProvider{},
+ AgentServer: fakeAgentServer{},
+ ReadState: &fakeCanonicalReadState{},
+ ControlLevel: tools.ControlLevelControlled,
+ })
+
+ svc := &Service{executor: exec}
+ toolsList := svc.toolsForAssistantTurn("Reply exactly: PULSE_CHAT_OK", false, false, true)
+ set := toolNameSet(toolsList)
+ if !set["pulse_read"] || !set["pulse_control"] || !set["pulse_query"] {
+ t.Fatalf("expected model handoff turns to keep full manifest, got %#v", set)
+ }
+}
+
func TestToolsForExecutionMode_AutonomousNonPatrolExposesGovernedTools(t *testing.T) {
exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{
StateProvider: fakeStateProvider{},