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.

Answer Assistant inventory counts locally

rcourtman7c583c0547dc
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index cc6587ae9f..49b355c37e 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -6767,11 +6767,11 @@
{
"id": "codex-lane-followup-architecture-post-rc-canonicalization",
"agent_id": "codex",
- "summary": "Suppress compacted Assistant tool prelude leaks",
+ "summary": "Fast-path deterministic Assistant inventory counts",
"target_id": "v6-product-lane-expansion",
"claimed_at": "2026-06-05T21:57:48Z",
- "heartbeat_at": "2026-06-06T00:19:43Z",
- "expires_at": "2026-06-06T02:19:43Z",
+ "heartbeat_at": "2026-06-06T00:22:42Z",
+ "expires_at": "2026-06-06T02:22:42Z",
"work_item": {
"kind": "lane-followup",
"id": "architecture-post-rc-canonicalization"
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index f79b15cfcd..7cb9304f41 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -252,6 +252,17 @@ runtime cost control, and shared AI transport surfaces.
the topology detail is complete or context-truncated, and should pass a
compact user-visible inventory payload rather than raw governed tool JSON so
policy metadata cannot cause providers to hide ordinary topology labels.
+ Deterministic count-only inventory prompts are a stricter case of that same
+ contract: when canonical topology state already carries the complete
+ aggregate counts, `internal/ai/chat` should answer locally by streaming
+ normal typed assistant content and `done` before provider attempt creation.
+ This adapts the referenced OpenCode `message.ts` and `processor.ts` typed
+ part/delta model at commit `fa2b63f850fc0a23bec2bdff9e660450d3fe7913`:
+ locally owned text is still transcript text, but it must not wait on a
+ remote provider or pretend that shell/tool inspection produced the answer.
+ The completion metadata for that path should identify the effective route
+ as `pulse:local-inventory` so the transcript label reflects Pulse-owned
+ local runtime output instead of the operator's selected remote model.
The compact payload must include exact `answer_label` fields for nodes and
workloads; the provider-facing instruction must tell the model to copy those
labels exactly instead of substituting generic labels like `Node 1`, `VM
diff --git a/frontend-modern/src/utils/__tests__/aiProviderPresentation.test.ts b/frontend-modern/src/utils/__tests__/aiProviderPresentation.test.ts
index acf1100b94..db75235af8 100644
--- a/frontend-modern/src/utils/__tests__/aiProviderPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/aiProviderPresentation.test.ts
@@ -51,4 +51,8 @@ describe('aiProviderPresentation', () => {
}),
).toBe('DeepSeek R1 via OpenRouter');
});
+
+ it('labels Pulse-owned local runtime routes without provider wording', () => {
+ expect(formatAIModelRouteLabel('pulse:local-inventory')).toBe('Pulse inventory');
+ });
});
diff --git a/frontend-modern/src/utils/aiProviderPresentation.ts b/frontend-modern/src/utils/aiProviderPresentation.ts
index 07e0586adb..569fc098a0 100644
--- a/frontend-modern/src/utils/aiProviderPresentation.ts
+++ b/frontend-modern/src/utils/aiProviderPresentation.ts
@@ -52,18 +52,25 @@ type AIModelRouteLabelInput =
| (Pick<ModelInfo, 'id'> & Partial<Pick<ModelInfo, 'name' | 'provider'>>);
const GATEWAY_MODEL_PROVIDERS = new Set<string>(['openrouter']);
+const LOCAL_MODEL_ROUTE_LABELS: Record<string, string> = {
+ 'pulse:local-inventory': 'Pulse inventory',
+};
const modelIdForLabel = (model: AIModelRouteLabelInput): string =>
typeof model === 'string' ? model.trim() : model.id.trim();
const baseModelLabel = (model: AIModelRouteLabelInput): string => {
+ const id = modelIdForLabel(model);
+ const localLabel = LOCAL_MODEL_ROUTE_LABELS[id];
+ if (localLabel) {
+ return localLabel;
+ }
if (typeof model !== 'string') {
const name = model.name?.trim();
if (name) {
return name;
}
}
- const id = modelIdForLabel(model);
return id.split(':').pop() || id;
};
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index bb12a8e9c1..883ab3e277 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -651,18 +651,6 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
selectedModel = overrideModel
}
- attempts, initialProviderErr := s.chatProviderAttempts(ctx, cfgSnapshot, selectedModel, configuredModel, configuredProvider)
- if len(attempts) == 0 {
- if initialProviderErr != nil {
- return initialProviderErr
- }
- return fmt.Errorf("provider not initialized")
- }
- initialFallbackModel := ""
- if initialProviderErr != nil {
- initialFallbackModel = attempts[0].Model
- }
-
// Proactively gather context for mentioned resources
s.mu.RLock()
prefetcher := s.contextPrefetcher
@@ -763,6 +751,16 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
assistantToolScope := assistantToolScopeForPrompt(req.Prompt, hasModelHandoffContext)
if assistantToolScope == assistantTurnToolScopeQueryOnly {
emitWorkflowState(streamCallback, "context", "Reading current Pulse inventory with pulse_query.", "", "pulse_query")
+ if assistantPromptRequestsDeterministicInventoryCount(normalizeAssistantToolRoutingPrompt(req.Prompt)) {
+ if answer, ok := s.directAssistantInventoryCountAnswer(ctx, baseExecutor); ok {
+ emitWorkflowState(streamCallback, "context_ready", "Counted current Pulse inventory.", "", "pulse_query")
+ s.streamDirectAssistantAnswer(sessions, session.ID, answer, streamCallback)
+ log.Debug().
+ Str("session_id", session.ID).
+ Msg("[ChatService] Answered deterministic inventory count from canonical state")
+ return nil
+ }
+ }
if summaryContext := s.prefetchAssistantInventoryTopologyContext(ctx, baseExecutor); summaryContext != "" {
modelBoundaryAllowedInventoryContext = summaryContext
injectHandoffContextIntoLatestUserMessage(messages, summaryContext)
@@ -795,6 +793,18 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
}
streamCallback(event)
}
+
+ attempts, initialProviderErr := s.chatProviderAttempts(ctx, cfgSnapshot, selectedModel, configuredModel, configuredProvider)
+ if len(attempts) == 0 {
+ if initialProviderErr != nil {
+ return initialProviderErr
+ }
+ return fmt.Errorf("provider not initialized")
+ }
+ initialFallbackModel := ""
+ if initialProviderErr != nil {
+ initialFallbackModel = attempts[0].Model
+ }
if initialFallbackModel != "" {
emitChatProviderFallback(streamCallback, selectedModel, initialFallbackModel)
}
@@ -1030,112 +1040,272 @@ func (s *Service) prefetchAssistantInventoryTopologyContextFromReadState() strin
return strings.TrimSpace(contextText)
}
-func marshalAssistantInventoryTopologyContextFromReadState(rs unifiedresources.ReadState) (string, error) {
- if rs == nil {
- return "", nil
+func (s *Service) directAssistantInventoryCountAnswer(ctx context.Context, executor *tools.PulseToolExecutor) (string, bool) {
+ context, ok := s.assistantInventoryTopologyContextForDirectAnswer(ctx, executor)
+ if !ok {
+ return "", false
}
+ return formatAssistantInventoryCountAnswer(context)
+}
- context := assistantInventoryTopologyContext{
- Proxmox: assistantInventoryProxmoxTopology{Nodes: []assistantInventoryProxmoxNode{}},
- Docker: assistantInventoryDockerTopology{Hosts: []assistantInventoryDockerHost{}},
- Kubernetes: assistantInventoryKubernetesTopology{Clusters: []assistantInventoryKubernetesCluster{}},
+func (s *Service) assistantInventoryTopologyContextForDirectAnswer(ctx context.Context, executor *tools.PulseToolExecutor) (assistantInventoryTopologyContext, bool) {
+ if contextText := strings.TrimSpace(s.prefetchAssistantInventoryTopologyContextFromReadState()); contextText != "" {
+ return parseAssistantInventoryTopologyContext(contextText)
}
- nodeMap := make(map[string]*assistantInventoryProxmoxNode)
- ensureNode := func(name, status string) *assistantInventoryProxmoxNode {
- name = firstNonEmptyString(name, "unknown")
- key := strings.ToLower(name)
- if existing := nodeMap[key]; existing != nil {
- if existing.Status == "" || existing.Status == "unknown" {
- existing.Status = firstNonEmptyString(status, existing.Status, "unknown")
- }
- return existing
- }
- node := &assistantInventoryProxmoxNode{
- AnswerLabel: assistantInventoryNodeAnswerLabel(name),
- Name: name,
- Status: firstNonEmptyString(status, "unknown"),
- VMs: []assistantInventoryWorkload{},
- Containers: []assistantInventoryWorkload{},
- VMCount: 0,
- ContainerCount: 0,
- }
- nodeMap[key] = node
- return node
+ if executor == nil {
+ return assistantInventoryTopologyContext{}, false
}
+ result, err := executor.ExecuteTool(ctx, "pulse_query", map[string]interface{}{
+ "action": "topology",
+ "summary_only": false,
+ "max_proxmox_nodes": 0,
+ "max_vms_per_node": 0,
+ "max_containers_per_node": 0,
+ "max_docker_hosts": 0,
+ "max_docker_containers_per_host": 0,
+ "max_k8s_clusters": 0,
+ "max_k8s_nodes_per_cluster": 0,
+ "max_k8s_deployments_per_cluster": 0,
+ "max_k8s_pods_per_cluster": 0,
+ })
+ if err != nil || result.IsError {
+ return assistantInventoryTopologyContext{}, false
+ }
+ resultText := strings.TrimSpace(FormatToolResult(result))
+ if resultText == "" {
+ return assistantInventoryTopologyContext{}, false
+ }
+ var topology tools.TopologyResponse
+ if err := json.Unmarshal([]byte(resultText), &topology); err != nil {
+ return assistantInventoryTopologyContext{}, false
+ }
+ contextText, err := marshalAssistantInventoryTopologyContext(topology.NormalizeCollections())
+ if err != nil {
+ return assistantInventoryTopologyContext{}, false
+ }
+ return parseAssistantInventoryTopologyContext(contextText)
+}
- for _, node := range rs.Nodes() {
- if node == nil {
- continue
- }
- context.Summary.TotalNodes++
- ensureNode(firstNonEmptyString(node.NodeName(), node.Name()), string(node.Status()))
+func parseAssistantInventoryTopologyContext(contextText string) (assistantInventoryTopologyContext, bool) {
+ var context assistantInventoryTopologyContext
+ if err := json.Unmarshal([]byte(strings.TrimSpace(contextText)), &context); err != nil {
+ return assistantInventoryTopologyContext{}, false
}
- for _, vm := range rs.VMs() {
- if vm == nil {
- continue
- }
- context.Summary.TotalVMs++
- if statusIsRunningOrOnline(string(vm.Status())) {
- context.Summary.RunningVMs++
- }
- node := ensureNode(vm.Node(), "unknown")
- node.VMCount++
- name := strings.TrimSpace(vm.Name())
- node.VMs = append(node.VMs, assistantInventoryWorkload{
- AnswerLabel: assistantInventoryGuestAnswerLabel("VM", vm.VMID(), name),
- VMID: vm.VMID(),
- Name: name,
- Status: string(vm.Status()),
- CPUPercent: vm.CPUPercent(),
- MemoryPercent: vm.MemoryPercent(),
- })
+ if context.Proxmox.Nodes == nil {
+ context.Proxmox.Nodes = []assistantInventoryProxmoxNode{}
}
- for _, container := range rs.Containers() {
- if container == nil {
- continue
+ if context.Docker.Hosts == nil {
+ context.Docker.Hosts = []assistantInventoryDockerHost{}
+ }
+ if context.Kubernetes.Clusters == nil {
+ context.Kubernetes.Clusters = []assistantInventoryKubernetesCluster{}
+ }
+ return context, assistantInventorySummaryTotal(context.Summary) > 0 || assistantInventoryIncludedContextTotal(context) > 0
+}
+
+func (s *Service) streamDirectAssistantAnswer(sessions *SessionStore, sessionID, answer string, streamCallback StreamCallback) {
+ answer = strings.TrimSpace(answer)
+ if answer == "" {
+ return
+ }
+ if sessions != nil {
+ if err := sessions.AddMessage(sessionID, Message{
+ ID: uuid.New().String(),
+ Role: "assistant",
+ Content: answer,
+ Timestamp: time.Now(),
+ }); err != nil {
+ log.Warn().Err(err).Str("session_id", sessionID).Msg("[ChatService] Failed to save direct Assistant answer")
}
- context.Summary.TotalSystemContainers++
- if statusIsRunningOrOnline(string(container.Status())) {
- context.Summary.RunningContainers++
- }
- node := ensureNode(container.Node(), "unknown")
- node.ContainerCount++
- name := strings.TrimSpace(container.Name())
- node.Containers = append(node.Containers, assistantInventoryWorkload{
- AnswerLabel: assistantInventoryGuestAnswerLabel("CT", container.VMID(), name),
- VMID: container.VMID(),
- Name: name,
- Status: string(container.Status()),
- CPUPercent: container.CPUPercent(),
- MemoryPercent: container.MemoryPercent(),
- })
}
+ contentData, _ := json.Marshal(ContentData{Text: answer})
+ streamCallback(StreamEvent{Type: "content", Data: contentData})
+ doneData, _ := json.Marshal(DoneData{SessionID: sessionID, Model: assistantLocalInventoryModelRoute})
+ streamCallback(StreamEvent{Type: "done", Data: doneData})
+}
- for _, node := range nodeMap {
- context.Proxmox.Nodes = append(context.Proxmox.Nodes, *node)
+func formatAssistantInventoryCountAnswer(context assistantInventoryTopologyContext) (string, bool) {
+ summary := assistantInventoryContextSummary(context)
+ total := assistantInventorySummaryTotal(summary)
+ if total == 0 {
+ return "", false
}
- sort.Slice(context.Proxmox.Nodes, func(i, j int) bool {
- return strings.ToLower(context.Proxmox.Nodes[i].Name) < strings.ToLower(context.Proxmox.Nodes[j].Name)
- })
- for i := range context.Proxmox.Nodes {
- sort.Slice(context.Proxmox.Nodes[i].VMs, func(a, b int) bool {
- return context.Proxmox.Nodes[i].VMs[a].VMID < context.Proxmox.Nodes[i].VMs[b].VMID
- })
- sort.Slice(context.Proxmox.Nodes[i].Containers, func(a, b int) bool {
- return context.Proxmox.Nodes[i].Containers[a].VMID < context.Proxmox.Nodes[i].Containers[b].VMID
- })
+
+ computeTotal := summary.TotalNodes + summary.TotalVMs + summary.TotalSystemContainers
+ dockerTotal := summary.TotalDockerHosts + summary.TotalDockerContainers
+ kubernetesTotal := summary.TotalK8sClusters + summary.TotalK8sNodes + summary.TotalK8sDeployments + summary.TotalK8sPods
+
+ var categories []string
+ if computeTotal > 0 {
+ categories = append(categories, fmt.Sprintf("%s (%s)",
+ assistantInventoryCountPhrase(computeTotal, "compute resource", "compute resources"),
+ assistantInventoryJoinPhrases([]string{
+ assistantInventoryPositiveCountPhrase(summary.TotalNodes, "Proxmox node", "Proxmox nodes"),
+ assistantInventoryPositiveCountPhrase(summary.TotalVMs, "VM", "VMs"),
+ assistantInventoryPositiveCountPhrase(summary.TotalSystemContainers, "system container", "system containers"),
+ }),
+ ))
+ }
+ if dockerTotal > 0 {
+ categories = append(categories, fmt.Sprintf("%s (%s)",
+ assistantInventoryCountPhrase(dockerTotal, "Docker inventory item", "Docker inventory items"),
+ assistantInventoryJoinPhrases([]string{
+ assistantInventoryPositiveCountPhrase(summary.TotalDockerHosts, "Docker host", "Docker hosts"),
+ assistantInventoryPositiveCountPhrase(summary.TotalDockerContainers, "Docker container", "Docker containers"),
+ }),
+ ))
}
+ if kubernetesTotal > 0 {
+ categories = append(categories, fmt.Sprintf("%s (%s)",
+ assistantInventoryCountPhrase(kubernetesTotal, "Kubernetes inventory item", "Kubernetes inventory items"),
+ assistantInventoryJoinPhrases([]string{
+ assistantInventoryPositiveCountPhrase(summary.TotalK8sClusters, "cluster", "clusters"),
+ assistantInventoryPositiveCountPhrase(summary.TotalK8sNodes, "node", "nodes"),
+ assistantInventoryPositiveCountPhrase(summary.TotalK8sDeployments, "deployment", "deployments"),
+ assistantInventoryPositiveCountPhrase(summary.TotalK8sPods, "pod", "pods"),
+ }),
+ ))
+ }
+
+ if len(categories) == 1 {
+ return "Pulse currently sees " + categories[0] + ".", true
+ }
+ return fmt.Sprintf("Pulse currently sees %s: %s.",
+ assistantInventoryCountPhrase(total, "visible inventory item", "visible inventory items"),
+ assistantInventoryJoinPhrases(categories),
+ ), true
+}
+
+func assistantInventoryContextSummary(context assistantInventoryTopologyContext) tools.TopologySummary {
+ summary := context.Summary
+ included := assistantInventoryIncludedContextCounts(context)
+ if summary.TotalNodes == 0 {
+ summary.TotalNodes = included.proxmoxNodes
+ }
+ if summary.TotalVMs == 0 {
+ summary.TotalVMs = included.vms
+ }
+ if summary.TotalSystemContainers == 0 {
+ summary.TotalSystemContainers = included.systemContainers
+ }
+ if summary.TotalDockerHosts == 0 {
+ summary.TotalDockerHosts = included.dockerHosts
+ }
+ if summary.TotalDockerContainers == 0 {
+ summary.TotalDockerContainers = included.dockerContainers
+ }
+ if summary.TotalK8sClusters == 0 {
+ summary.TotalK8sClusters = included.k8sClusters
+ }
+ if summary.TotalK8sNodes == 0 {
+ summary.TotalK8sNodes = included.k8sNodes
+ }
+ if summary.TotalK8sDeployments == 0 {
+ summary.TotalK8sDeployments = included.k8sDeployments
+ }
+ if summary.TotalK8sPods == 0 {
+ summary.TotalK8sPods = included.k8sPods
+ }
+ return summary
+}
- if len(context.Proxmox.Nodes) == 0 &&
- context.Summary.TotalVMs == 0 &&
- context.Summary.TotalSystemContainers == 0 {
+func assistantInventorySummaryTotal(summary tools.TopologySummary) int {
+ return summary.TotalNodes +
+ summary.TotalVMs +
+ summary.TotalSystemContainers +
+ summary.TotalDockerHosts +
+ summary.TotalDockerContainers +
+ summary.TotalK8sClusters +
+ summary.TotalK8sNodes +
+ summary.TotalK8sDeployments +
+ summary.TotalK8sPods
+}
+
+func assistantInventoryIncludedContextTotal(context assistantInventoryTopologyContext) int {
+ counts := assistantInventoryIncludedContextCounts(context)
+ return counts.proxmoxNodes +
+ counts.vms +
+ counts.systemContainers +
+ counts.dockerHosts +
+ counts.dockerContainers +
+ counts.k8sClusters +
+ counts.k8sNodes +
+ counts.k8sDeployments +
+ counts.k8sPods
+}
+
+func assistantInventoryIncludedContextCounts(context assistantInventoryTopologyContext) assistantInventoryTopologyCounts {
+ counts := assistantInventoryTopologyCounts{
+ proxmoxNodes: len(context.Proxmox.Nodes),
+ dockerHosts: len(context.Docker.Hosts),
+ k8sClusters: len(context.Kubernetes.Clusters),
+ }
+ for _, node := range context.Proxmox.Nodes {
+ counts.vms += len(node.VMs)
+ counts.systemContainers += len(node.Containers)
+ }
+ for _, host := range context.Docker.Hosts {
+ counts.dockerContainers += len(host.Containers)
+ }
+ for _, cluster := range context.Kubernetes.Clusters {
+ counts.k8sNodes += len(cluster.Nodes)
+ counts.k8sDeployments += len(cluster.Deployments)
+ counts.k8sPods += len(cluster.Pods)
+ }
+ return counts
+}
+
+func assistantInventoryCountPhrase(count int, singular, plural string) string {
+ if count == 1 {
+ return fmt.Sprintf("1 %s", singular)
+ }
+ return fmt.Sprintf("%d %s", count, plural)
+}
+
+func assistantInventoryPositiveCountPhrase(count int, singular, plural string) string {
+ if count <= 0 {
+ return ""
+ }
+ return assistantInventoryCountPhrase(count, singular, plural)
+}
+
+func assistantInventoryJoinPhrases(phrases []string) string {
+ filtered := make([]string, 0, len(phrases))
+ for _, phrase := range phrases {
+ if trimmed := strings.TrimSpace(phrase); trimmed != "" {
+ filtered = append(filtered, trimmed)
+ }
+ }
+ switch len(filtered) {
+ case 0:
+ return ""
+ case 1:
+ return filtered[0]
+ case 2:
+ return filtered[0] + " and " + filtered[1]
+ default:
+ return strings.Join(filtered[:len(filtered)-1], ", ") + ", and " + filtered[len(filtered)-1]
+ }
+}
+
+func marshalAssistantInventoryTopologyContextFromReadState(rs unifiedresources.ReadState) (string, error) {
+ if rs == nil {
return "", nil
}
- encoded, err := json.Marshal(context)
- if err != nil {
- return "", err
+
+ topology, ok := assistantInventoryTopologyResponseFromReadState(rs)
+ if !ok {
+ return "", nil
}
- return string(encoded), nil
+ return marshalAssistantInventoryTopologyContext(topology)
+}
+
+func assistantInventoryTopologyResponseFromReadState(rs unifiedresources.ReadState) (tools.TopologyResponse, bool) {
+ if rs == nil {
+ return tools.EmptyTopologyResponse(), false
+ }
+ response := tools.BuildTopologyResponseFromReadState(rs, tools.TopologyBuildOptions{Include: "all"})
+ return response, assistantInventorySummaryTotal(response.Summary) > 0
}
func marshalAssistantInventoryTopologyContext(topology tools.TopologyResponse) (string, error) {
@@ -4008,6 +4178,8 @@ const (
assistantTurnToolScopeTextOnly assistantTurnToolScope = "text-only"
)
+const assistantLocalInventoryModelRoute = "pulse:local-inventory"
+
func (s *Service) toolsForAssistantTurn(prompt string, autonomousMode bool, patrolMode bool, hasModelContext bool) []providers.Tool {
scope := assistantToolScopeForPrompt(prompt, hasModelContext)
return s.toolsForAssistantTurnWithScope(scope, autonomousMode, patrolMode)
@@ -4232,6 +4404,33 @@ func assistantPromptIsInventoryQuery(normalized string) bool {
})
}
+func assistantPromptRequestsDeterministicInventoryCount(normalized string) bool {
+ if !assistantPromptIsInventoryQuery(normalized) {
+ return false
+ }
+ if assistantPromptContainsAny(normalized, []string{
+ " list ",
+ " show ",
+ " breakdown ",
+ " detail ",
+ " details ",
+ " detailed ",
+ " overview ",
+ " status ",
+ }) {
+ return false
+ }
+ return assistantPromptContainsAny(normalized, []string{
+ " how many ",
+ " count ",
+ " counts ",
+ " total ",
+ " totals ",
+ " number ",
+ " number of ",
+ })
+}
+
func assistantPromptLooksConversational(normalized string) bool {
trimmed := strings.TrimSpace(normalized)
if trimmed == "" {
diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.go
index 39ecdb2bc5..1d7cae4536 100644
--- a/internal/ai/chat/service_execute_additional_test.go
+++ b/internal/ai/chat/service_execute_additional_test.go
@@ -1026,57 +1026,168 @@ func TestService_ExecuteStream_InteractiveChatLetsModelChooseTools(t *testing.T)
}
}
-func TestService_ExecuteStream_InventoryCountPrefetchesSummaryWithoutTools(t *testing.T) {
+func TestService_ExecuteStream_InventoryCountAnswersFromCanonicalStateWithoutProvider(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
+ var providerCalled atomic.Bool
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},
- })
+ providerCalled.Store(true)
return nil
},
}
+ state := models.StateSnapshot{
+ Nodes: []models.Node{{
+ ID: "node1",
+ Name: "node1",
+ Instance: "pve1",
+ Status: "online",
+ }},
+ VMs: []models.VM{{
+ ID: "qemu/pve1/node1/100",
+ Name: "vm1",
+ VMID: 100,
+ Instance: "pve1",
+ Status: "running",
+ Node: "node1",
+ }},
+ Containers: []models.Container{{
+ ID: "lxc/pve1/node1/201",
+ Name: "ct1",
+ VMID: 201,
+ Instance: "pve1",
+ Status: "running",
+ Node: "node1",
+ }},
+ DockerHosts: []models.DockerHost{{
+ ID: "docker-host-1",
+ Hostname: "docker-host-1",
+ Containers: []models.DockerContainer{{
+ ID: "docker-container-1",
+ Name: "nginx",
+ State: "running",
+ Image: "nginx",
+ Health: "healthy",
+ }},
+ }},
+ KubernetesClusters: []models.KubernetesCluster{{
+ ID: "cluster-1",
+ Name: "prod-cluster",
+ Status: "online",
+ Nodes: []models.KubernetesNode{{
+ Name: "worker-1",
+ UID: "node-1",
+ Ready: true,
+ Roles: []string{"worker"},
+ }},
+ Pods: []models.KubernetesPod{{
+ UID: "pod-1",
+ Name: "api-6f8d5c",
+ Namespace: "default",
+ Phase: "Running",
+ Restarts: 2,
+ OwnerKind: "Deployment",
+ OwnerName: "api",
+ }},
+ Deployments: []models.KubernetesDeployment{{
+ UID: "deploy-1",
+ Name: "api",
+ Namespace: "default",
+ DesiredReplicas: 3,
+ ReadyReplicas: 2,
+ }},
+ }},
+ }
+ registry := unifiedresources.NewRegistry(nil)
+ registry.IngestSnapshot(state)
service := NewService(Config{
AIConfig: &config.AIConfig{ControlLevel: config.ControlLevelControlled},
- StateProvider: &mockStateProvider{},
+ StateProvider: &mockStateProvider{state: state},
+ ReadState: unifiedresources.NewMonitorAdapter(registry),
AgentServer: &mockAgentServer{},
})
service.sessions = store
service.provider = provider
service.started = true
+ var content strings.Builder
+ var doneSeen bool
+ var doneModel string
+ var countedProgressSeen bool
err = service.ExecuteStream(context.Background(), ExecuteRequest{
SessionID: "inventory-count-fast-path",
Prompt: "how many devices in this",
- }, func(event StreamEvent) {})
+ }, func(event StreamEvent) {
+ switch event.Type {
+ case "content":
+ var data ContentData
+ if err := json.Unmarshal(event.Data, &data); err != nil {
+ t.Fatalf("unmarshal content: %v", err)
+ }
+ content.WriteString(data.Text)
+ case "done":
+ doneSeen = true
+ var data DoneData
+ if err := json.Unmarshal(event.Data, &data); err != nil {
+ t.Fatalf("unmarshal done: %v", err)
+ }
+ doneModel = data.Model
+ case "workflow_state":
+ var data WorkflowStateData
+ if err := json.Unmarshal(event.Data, &data); err != nil {
+ t.Fatalf("unmarshal workflow state: %v", err)
+ }
+ if data.Phase == "context_ready" && data.Message == "Counted current Pulse inventory." {
+ countedProgressSeen = true
+ }
+ }
+ })
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 providerCalled.Load() {
+ t.Fatal("expected deterministic inventory count to avoid provider call")
}
- if len(capturedReq.Messages) == 0 {
- t.Fatal("expected provider request messages")
+ if !doneSeen {
+ t.Fatal("done event was not emitted")
}
- 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 doneModel != assistantLocalInventoryModelRoute {
+ t.Fatalf("expected local inventory completion model, got %q", doneModel)
+ }
+ if !countedProgressSeen {
+ t.Fatal("inventory count progress event was not emitted")
+ }
+ answer := content.String()
+ for _, want := range []string{
+ "Pulse currently sees 9 visible inventory items",
+ "3 compute resources",
+ "1 Proxmox node",
+ "1 VM",
+ "1 system container",
+ "2 Docker inventory items",
+ "1 Docker host",
+ "1 Docker container",
+ "4 Kubernetes inventory items",
+ "1 cluster",
+ "1 node",
+ "1 deployment",
+ "1 pod",
+ } {
+ if !strings.Contains(answer, want) {
+ t.Fatalf("expected direct inventory answer to contain %q, got %q", want, answer)
+ }
+ }
+ messages, err := store.GetMessages("inventory-count-fast-path")
+ if err != nil {
+ t.Fatalf("get messages: %v", err)
}
- 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)
+ if len(messages) != 2 || messages[1].Role != "assistant" || messages[1].Content != answer {
+ t.Fatalf("expected direct assistant answer to be persisted, got %#v", messages)
}
}
diff --git a/internal/ai/tools/tools_query.go b/internal/ai/tools/tools_query.go
index 957b8dd4f3..e63c3136e7 100644
--- a/internal/ai/tools/tools_query.go
+++ b/internal/ai/tools/tools_query.go
@@ -4019,93 +4019,41 @@ func (e *PulseToolExecutor) executeListInfrastructure(_ context.Context, args ma
return NewJSONResult(response.NormalizeCollections()), nil
}
-func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[string]interface{}) (CallToolResult, error) {
- include, _ := args["include"].(string)
- if include == "" {
- include = "all"
- }
- include = canonicalQueryTopologyInclude(include)
- switch include {
- case "all", "proxmox", "app-containers", "kubernetes":
- default:
- return NewErrorResult(fmt.Errorf("invalid include: %s. Use all, proxmox, app-containers, or kubernetes", include)), nil
- }
-
- summaryOnly, summaryProvided := args["summary_only"].(bool)
- maxProxmoxNodes := intArg(args, "max_proxmox_nodes", 0)
- maxVMsPerNode := intArg(args, "max_vms_per_node", 0)
- maxContainersPerNode := intArg(args, "max_containers_per_node", 0)
- maxDockerHosts := intArg(args, "max_docker_hosts", 0)
- maxDockerContainersPerHost := intArg(args, "max_docker_containers_per_host", 0)
- maxK8sClusters := intArg(args, "max_k8s_clusters", 0)
- maxK8sNodesPerCluster := intArg(args, "max_k8s_nodes_per_cluster", 0)
- maxK8sDeploymentsPerCluster := intArg(args, "max_k8s_deployments_per_cluster", 0)
- maxK8sPodsPerCluster := intArg(args, "max_k8s_pods_per_cluster", 0)
- _, maxProxmoxNodesProvided := args["max_proxmox_nodes"]
- _, maxVMsProvided := args["max_vms_per_node"]
- _, maxContainersProvided := args["max_containers_per_node"]
- _, maxDockerHostsProvided := args["max_docker_hosts"]
- _, maxDockerContainersProvided := args["max_docker_containers_per_host"]
- _, maxK8sClustersProvided := args["max_k8s_clusters"]
- _, maxK8sNodesProvided := args["max_k8s_nodes_per_cluster"]
- _, maxK8sDeploymentsProvided := args["max_k8s_deployments_per_cluster"]
- _, maxK8sPodsProvided := args["max_k8s_pods_per_cluster"]
-
- if !summaryProvided {
- summaryOnly = false
- }
- if !summaryOnly {
- if !maxProxmoxNodesProvided {
- maxProxmoxNodes = defaultMaxTopologyNodes
- }
- if !maxVMsProvided {
- maxVMsPerNode = defaultMaxTopologyVMsPerNode
- }
- if !maxContainersProvided {
- maxContainersPerNode = defaultMaxTopologyContainersPerNode
- }
- if !maxDockerHostsProvided {
- maxDockerHosts = defaultMaxTopologyDockerHosts
- }
- if !maxDockerContainersProvided {
- maxDockerContainersPerHost = defaultMaxTopologyDockerContainersPerHost
- }
- if !maxK8sClustersProvided {
- maxK8sClusters = defaultMaxTopologyK8sClusters
- }
- if !maxK8sNodesProvided {
- maxK8sNodesPerCluster = defaultMaxTopologyK8sNodesPerCluster
- }
- if !maxK8sDeploymentsProvided {
- maxK8sDeploymentsPerCluster = defaultMaxTopologyK8sDeploymentsPerCluster
- }
- if !maxK8sPodsProvided {
- maxK8sPodsPerCluster = defaultMaxTopologyK8sPodsPerCluster
- }
- }
-
- rs, err := e.readStateForControl()
- if err != nil {
- return NewErrorResult(err), nil
+type TopologyBuildOptions struct {
+ Include string
+ SummaryOnly bool
+ MaxProxmoxNodes int
+ MaxVMsPerNode int
+ MaxContainersPerNode int
+ MaxDockerHosts int
+ MaxDockerContainersPerHost int
+ MaxK8sClusters int
+ MaxK8sNodesPerCluster int
+ MaxK8sDeploymentsPerCluster int
+ MaxK8sPodsPerCluster int
+ ConnectedAgentHostnames map[string]bool
+ ControlEnabled bool
+}
+
+func BuildTopologyResponseFromReadState(rs unifiedresources.ReadState, options TopologyBuildOptions) TopologyResponse {
+ response := EmptyTopologyResponse()
+ if rs == nil {
+ return response
}
- governance := newGovernedQueryMetadataResolver(rs)
- // Build a set of connected agent hostnames for quick lookup
- connectedAgentHostnames := make(map[string]bool)
- if e.agentServer != nil {
- for _, agent := range e.agentServer.GetConnectedAgents() {
- connectedAgentHostnames[agent.Hostname] = true
- }
+ include := canonicalQueryTopologyInclude(options.Include)
+ if include == "" {
+ include = "all"
}
-
- // Check if control is enabled
- controlEnabled := e.controlLevel != ControlLevelReadOnly && e.controlLevel != ""
-
includeProxmox := include == "all" || include == "proxmox"
includeDocker := include == "all" || include == "app-containers"
includeKubernetes := include == "all" || include == "kubernetes"
+ connectedAgentHostnames := options.ConnectedAgentHostnames
+ if connectedAgentHostnames == nil {
+ connectedAgentHostnames = map[string]bool{}
+ }
+ governance := newGovernedQueryMetadataResolver(rs)
- // Summary counters
summary := TopologySummary{
TotalNodes: len(rs.Nodes()),
TotalVMs: len(rs.VMs()),
@@ -4119,6 +4067,9 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
}
for _, node := range rs.Nodes() {
+ if node == nil {
+ continue
+ }
if connectedAgentHostnames[node.Name()] {
summary.NodesWithAgents++
}
@@ -4142,11 +4093,13 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
}
}
- // Build node topology - group VMs and containers by hypervisor node
nodeMap := make(map[string]*ProxmoxNodeTopology)
- if includeProxmox && !summaryOnly {
+ if includeProxmox && !options.SummaryOnly {
for _, node := range rs.Nodes() {
- if maxProxmoxNodes > 0 && len(nodeMap) >= maxProxmoxNodes {
+ if node == nil {
+ continue
+ }
+ if options.MaxProxmoxNodes > 0 && len(nodeMap) >= options.MaxProxmoxNodes {
break
}
name := node.Name()
@@ -4156,7 +4109,7 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
Name: name,
Status: string(node.Status()),
AgentConnected: hasAgent,
- CanExecute: hasAgent && controlEnabled,
+ CanExecute: hasAgent && options.ControlEnabled,
VMs: []TopologyVM{},
Containers: []TopologyContainer{},
}
@@ -4164,13 +4117,13 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
}
ensureNode := func(name, status string) *ProxmoxNodeTopology {
- if !includeProxmox || summaryOnly {
+ if !includeProxmox || options.SummaryOnly {
return nil
}
if node, exists := nodeMap[name]; exists {
return node
}
- if maxProxmoxNodes > 0 && len(nodeMap) >= maxProxmoxNodes {
+ if options.MaxProxmoxNodes > 0 && len(nodeMap) >= options.MaxProxmoxNodes {
return nil
}
hasAgent := connectedAgentHostnames[name]
@@ -4179,27 +4132,27 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
Name: name,
Status: status,
AgentConnected: hasAgent,
- CanExecute: hasAgent && controlEnabled,
+ CanExecute: hasAgent && options.ControlEnabled,
VMs: []TopologyVM{},
Containers: []TopologyContainer{},
}
return nodeMap[name]
}
- // Add VMs to their nodes
for _, vm := range rs.VMs() {
+ if vm == nil {
+ continue
+ }
status := string(vm.Status())
if status == "running" || status == string(unifiedresources.StatusOnline) {
summary.RunningVMs++
}
-
nodeTopology := ensureNode(vm.Node(), "unknown")
if nodeTopology == nil {
continue
}
-
nodeTopology.VMCount++
- if maxVMsPerNode <= 0 || len(nodeTopology.VMs) < maxVMsPerNode {
+ if options.MaxVMsPerNode <= 0 || len(nodeTopology.VMs) < options.MaxVMsPerNode {
nodeTopology.VMs = append(nodeTopology.VMs, TopologyVM{
GovernedResourceMetadata: governance.Resolve(vm.Name(), vm.ID(), fmt.Sprintf("%d", vm.VMID())),
VMID: vm.VMID(),
@@ -4212,20 +4165,20 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
}
}
- // Add containers to their nodes
for _, ct := range rs.Containers() {
+ if ct == nil {
+ continue
+ }
status := string(ct.Status())
if status == "running" || status == string(unifiedresources.StatusOnline) {
summary.RunningContainers++
}
-
nodeTopology := ensureNode(ct.Node(), "unknown")
if nodeTopology == nil {
continue
}
-
nodeTopology.ContainerCount++
- if maxContainersPerNode <= 0 || len(nodeTopology.Containers) < maxContainersPerNode {
+ if options.MaxContainersPerNode <= 0 || len(nodeTopology.Containers) < options.MaxContainersPerNode {
nodeTopology.Containers = append(nodeTopology.Containers, TopologyContainer{
GovernedResourceMetadata: governance.Resolve(ct.Name(), ct.ID(), fmt.Sprintf("%d", ct.VMID())),
VMID: ct.VMID(),
@@ -4238,9 +4191,8 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
}
}
- // Convert node map to slice
proxmoxNodes := []ProxmoxNodeTopology{}
- if includeProxmox && !summaryOnly {
+ if includeProxmox && !options.SummaryOnly {
for _, node := range nodeMap {
proxmoxNodes = append(proxmoxNodes, *node)
}
@@ -4257,7 +4209,6 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
}
}
- // Build Docker topology
containersByHost := make(map[string][]*unifiedresources.DockerContainerView)
for _, container := range rs.DockerContainers() {
if container == nil {
@@ -4294,8 +4245,8 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
runningCount++
}
- if includeDocker && !summaryOnly {
- if maxDockerContainersPerHost <= 0 || len(containers) < maxDockerContainersPerHost {
+ if includeDocker && !options.SummaryOnly {
+ if options.MaxDockerContainersPerHost <= 0 || len(containers) < options.MaxDockerContainersPerHost {
containers = append(containers, DockerContainerSummary{
GovernedResourceMetadata: governance.Resolve(container.Name(), container.ID(), container.ContainerID()),
ID: container.ID(),
@@ -4308,8 +4259,8 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
}
}
- if includeDocker && !summaryOnly {
- if maxDockerHosts > 0 && len(dockerHosts) >= maxDockerHosts {
+ if includeDocker && !options.SummaryOnly {
+ if options.MaxDockerHosts > 0 && len(dockerHosts) >= options.MaxDockerHosts {
continue
}
@@ -4321,7 +4272,7 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
Hostname: hostname,
DisplayName: displayName,
AgentConnected: hasAgent,
- CanExecute: hasAgent && controlEnabled,
+ CanExecute: hasAgent && options.ControlEnabled,
Containers: containers,
ContainerCount: len(hostContainers),
RunningCount: runningCount,
@@ -4332,14 +4283,12 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
return strings.ToLower(dockerHosts[i].Hostname) < strings.ToLower(dockerHosts[j].Hostname)
})
- // Build Kubernetes topology
k8sClusters := []KubernetesClusterTopology{}
clusterMap := make(map[string]*KubernetesClusterTopology)
clusterKeyByID := make(map[string]string)
clusterKeyByName := make(map[string]string)
-
ensureCluster := func(name, id, status string) *KubernetesClusterTopology {
- if !includeKubernetes || summaryOnly {
+ if !includeKubernetes || options.SummaryOnly {
return nil
}
name = strings.TrimSpace(name)
@@ -4348,7 +4297,6 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
if status == "" {
status = "unknown"
}
-
key := strings.ToLower(id)
if key == "" {
key = strings.ToLower(name)
@@ -4369,7 +4317,7 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
}
return existing
}
- if maxK8sClusters > 0 && len(clusterMap) >= maxK8sClusters {
+ if options.MaxK8sClusters > 0 && len(clusterMap) >= options.MaxK8sClusters {
return nil
}
@@ -4391,7 +4339,6 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
}
return cluster
}
-
resolveCluster := func(parentID, clusterName string) *KubernetesClusterTopology {
parentID = strings.TrimSpace(parentID)
clusterName = strings.TrimSpace(clusterName)
@@ -4408,7 +4355,7 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
return ensureCluster(clusterName, parentID, "unknown")
}
- if includeKubernetes && !summaryOnly {
+ if includeKubernetes && !options.SummaryOnly {
for _, cluster := range rs.K8sClusters() {
if cluster == nil {
continue
@@ -4426,7 +4373,7 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
continue
}
cluster.NodeCount++
- if includeKubernetes && !summaryOnly && (maxK8sNodesPerCluster <= 0 || len(cluster.Nodes) < maxK8sNodesPerCluster) {
+ if includeKubernetes && !options.SummaryOnly && (options.MaxK8sNodesPerCluster <= 0 || len(cluster.Nodes) < options.MaxK8sNodesPerCluster) {
cluster.Nodes = append(cluster.Nodes, KubernetesNodeTopology{
GovernedResourceMetadata: governance.Resolve(node.Name()),
Name: node.Name(),
@@ -4448,7 +4395,7 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
continue
}
cluster.DeploymentCount++
- if includeKubernetes && !summaryOnly && (maxK8sDeploymentsPerCluster <= 0 || len(cluster.Deployments) < maxK8sDeploymentsPerCluster) {
+ if includeKubernetes && !options.SummaryOnly && (options.MaxK8sDeploymentsPerCluster <= 0 || len(cluster.Deployments) < options.MaxK8sDeploymentsPerCluster) {
cluster.Deployments = append(cluster.Deployments, KubernetesDeploymentDetail{
GovernedResourceMetadata: governance.Resolve(deployment.Name()),
Name: deployment.Name(),
@@ -4469,7 +4416,7 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
continue
}
cluster.PodCount++
- if includeKubernetes && !summaryOnly && (maxK8sPodsPerCluster <= 0 || len(cluster.Pods) < maxK8sPodsPerCluster) {
+ if includeKubernetes && !options.SummaryOnly && (options.MaxK8sPodsPerCluster <= 0 || len(cluster.Pods) < options.MaxK8sPodsPerCluster) {
cluster.Pods = append(cluster.Pods, KubernetesPodDetail{
GovernedResourceMetadata: governance.Resolve(pod.Name()),
Name: pod.Name(),
@@ -4482,7 +4429,7 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
}
}
- if includeKubernetes && !summaryOnly {
+ if includeKubernetes && !options.SummaryOnly {
for _, cluster := range clusterMap {
k8sClusters = append(k8sClusters, *cluster)
}
@@ -4502,13 +4449,111 @@ func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[strin
}
}
- response := EmptyTopologyResponse()
response.Proxmox.Nodes = proxmoxNodes
response.Docker.Hosts = dockerHosts
response.Kubernetes.Clusters = k8sClusters
response.Summary = summary
+ return response.NormalizeCollections()
+}
- return NewJSONResult(response.NormalizeCollections()), nil
+func (e *PulseToolExecutor) executeGetTopology(_ context.Context, args map[string]interface{}) (CallToolResult, error) {
+ include, _ := args["include"].(string)
+ if include == "" {
+ include = "all"
+ }
+ include = canonicalQueryTopologyInclude(include)
+ switch include {
+ case "all", "proxmox", "app-containers", "kubernetes":
+ default:
+ return NewErrorResult(fmt.Errorf("invalid include: %s. Use all, proxmox, app-containers, or kubernetes", include)), nil
+ }
+
+ summaryOnly, summaryProvided := args["summary_only"].(bool)
+ maxProxmoxNodes := intArg(args, "max_proxmox_nodes", 0)
+ maxVMsPerNode := intArg(args, "max_vms_per_node", 0)
+ maxContainersPerNode := intArg(args, "max_containers_per_node", 0)
+ maxDockerHosts := intArg(args, "max_docker_hosts", 0)
+ maxDockerContainersPerHost := intArg(args, "max_docker_containers_per_host", 0)
+ maxK8sClusters := intArg(args, "max_k8s_clusters", 0)
+ maxK8sNodesPerCluster := intArg(args, "max_k8s_nodes_per_cluster", 0)
+ maxK8sDeploymentsPerCluster := intArg(args, "max_k8s_deployments_per_cluster", 0)
+ maxK8sPodsPerCluster := intArg(args, "max_k8s_pods_per_cluster", 0)
+ _, maxProxmoxNodesProvided := args["max_proxmox_nodes"]
+ _, maxVMsProvided := args["max_vms_per_node"]
+ _, maxContainersProvided := args["max_containers_per_node"]
+ _, maxDockerHostsProvided := args["max_docker_hosts"]
+ _, maxDockerContainersProvided := args["max_docker_containers_per_host"]
+ _, maxK8sClustersProvided := args["max_k8s_clusters"]
+ _, maxK8sNodesProvided := args["max_k8s_nodes_per_cluster"]
+ _, maxK8sDeploymentsProvided := args["max_k8s_deployments_per_cluster"]
+ _, maxK8sPodsProvided := args["max_k8s_pods_per_cluster"]
+
+ if !summaryProvided {
+ summaryOnly = false
+ }
+ if !summaryOnly {
+ if !maxProxmoxNodesProvided {
+ maxProxmoxNodes = defaultMaxTopologyNodes
+ }
+ if !maxVMsProvided {
+ maxVMsPerNode = defaultMaxTopologyVMsPerNode
+ }
+ if !maxContainersProvided {
+ maxContainersPerNode = defaultMaxTopologyContainersPerNode
+ }
+ if !maxDockerHostsProvided {
+ maxDockerHosts = defaultMaxTopologyDockerHosts
+ }
+ if !maxDockerContainersProvided {
+ maxDockerContainersPerHost = defaultMaxTopologyDockerContainersPerHost
+ }
+ if !maxK8sClustersProvided {
+ maxK8sClusters = defaultMaxTopologyK8sClusters
+ }
+ if !maxK8sNodesProvided {
+ maxK8sNodesPerCluster = defaultMaxTopologyK8sNodesPerCluster
+ }
+ if !maxK8sDeploymentsProvided {
+ maxK8sDeploymentsPerCluster = defaultMaxTopologyK8sDeploymentsPerCluster
+ }
+ if !maxK8sPodsProvided {
+ maxK8sPodsPerCluster = defaultMaxTopologyK8sPodsPerCluster
+ }
+ }
+
+ rs, err := e.readStateForControl()
+ if err != nil {
+ return NewErrorResult(err), nil
+ }
+
+ // Build a set of connected agent hostnames for quick lookup
+ connectedAgentHostnames := make(map[string]bool)
+ if e.agentServer != nil {
+ for _, agent := range e.agentServer.GetConnectedAgents() {
+ connectedAgentHostnames[agent.Hostname] = true
+ }
+ }
+
+ // Check if control is enabled
+ controlEnabled := e.controlLevel != ControlLevelReadOnly && e.controlLevel != ""
+
+ response := BuildTopologyResponseFromReadState(rs, TopologyBuildOptions{
+ Include: include,
+ SummaryOnly: summaryOnly,
+ MaxProxmoxNodes: maxProxmoxNodes,
+ MaxVMsPerNode: maxVMsPerNode,
+ MaxContainersPerNode: maxContainersPerNode,
+ MaxDockerHosts: maxDockerHosts,
+ MaxDockerContainersPerHost: maxDockerContainersPerHost,
+ MaxK8sClusters: maxK8sClusters,
+ MaxK8sNodesPerCluster: maxK8sNodesPerCluster,
+ MaxK8sDeploymentsPerCluster: maxK8sDeploymentsPerCluster,
+ MaxK8sPodsPerCluster: maxK8sPodsPerCluster,
+ ConnectedAgentHostnames: connectedAgentHostnames,
+ ControlEnabled: controlEnabled,
+ })
+
+ return NewJSONResult(response), nil
}
func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[string]interface{}) (CallToolResult, error) {