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: add mutex to prevent concurrent map writes in Docker agent CPU tracking
rcourtman035436ad6e0c
diff --git a/analyze_coverage.py b/analyze_coverage.pynew file mode 100644index 0000000000..070f967a61--- /dev/null+++ b/analyze_coverage.py@@ -0,0 +1,56 @@++import sys+import os++def parse_coverage(filename):+ if not os.path.exists(filename):+ print(f"File {filename} not found")+ return++ package_stmts = {}+ package_covered = {}++ with open(filename, 'r') as f:+ lines = f.readlines()++ current_mode = ""+ for line in lines:+ if line.startswith("mode:"):+ current_mode = line.split()[1]+ continue++ parts = line.strip().split(':')+ if len(parts) != 2:+ continue++ file_path = parts[0]+ # Package is directory of file_path+ package_name = os.path.dirname(file_path)++ metrics = parts[1].split()+ if len(metrics) != 3:+ continue++ # start_end = metrics[0]+ num_stmts = int(metrics[1])+ count = int(metrics[2])++ package_stmts[package_name] = package_stmts.get(package_name, 0) + num_stmts+ if count > 0:+ package_covered[package_name] = package_covered.get(package_name, 0) + num_stmts++ results = []+ for pkg, total in package_stmts.items():+ covered = package_covered.get(pkg, 0)+ percent = (covered / total) * 100 if total > 0 else 0+ results.append((pkg, percent, covered, total))++ # Sort by percentage (ascending)+ results.sort(key=lambda x: x[1])++ print("Package Coverage Report (Bottom 20):")+ for pkg, pct, cov, tot in results[:20]:+ print(f"{pct:6.2f}% ({cov}/{tot}) {pkg}")++if __name__ == "__main__":+ parse_coverage("coverage.out")diff --git a/cmd/pulse-agent/main.go b/cmd/pulse-agent/main.goindex 9e076cc852..f41770faf5 100644--- a/cmd/pulse-agent/main.go+++ b/cmd/pulse-agent/main.go@@ -110,6 +110,10 @@ func run(ctx context.Context, args []string, getenv func(string) string) error {logger := zerolog.New(os.Stdout).Level(cfg.LogLevel).With().Timestamp().Logger()cfg.Logger = &logger+ if cfg.InsecureSkipVerify {+ logger.Warn().Msg("TLS verification disabled for agent connections (self-signed cert mode)")+ }+// 2a. Handle Self-Testif cfg.SelfTest {logger.Info().Msg("Self-test passed: config loaded and logger initialized")diff --git a/docs/API.md b/docs/API.mdindex 5d1e3ed3f3..55aff71c26 100644--- a/docs/API.md+++ b/docs/API.md@@ -32,6 +32,7 @@ Some endpoints require admin privileges and/or scopes. Common scopes include:- `monitoring:read`- `settings:read`- `settings:write`+- `host-agent:config:read`Endpoints that require admin access are noted below.@@ -531,7 +532,7 @@ Removes a host agent from state.### Agent Remote Config`GET /api/agents/host/{agent_id}/config`-Returns the server-side config payload for an agent (used by remote config and debugging). Requires `host-agent:report`.+Returns the server-side config payload for an agent (used by remote config and debugging). Requires `host-agent:config:read`.`PATCH /api/agents/host/{agent_id}/config` (admin, `host-agent:manage`)Updates server-side config for an agent (e.g., `commandsEnabled`).diff --git a/docs/CENTRALIZED_MANAGEMENT.md b/docs/CENTRALIZED_MANAGEMENT.mdindex 92ec51ca0a..7da6c29531 100644--- a/docs/CENTRALIZED_MANAGEMENT.md+++ b/docs/CENTRALIZED_MANAGEMENT.md@@ -94,6 +94,8 @@ GET /api/agents/host/{agent_id}/configAuthorization: Bearer <agent-or-admin-token>```+Requires `host-agent:config:read` (or admin tokens with management scopes).+## Agent Behavior1. On startup, the agent computes its Agent ID.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 0ec4a163d1..ec95687f79 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -161,6 +161,9 @@ Environment variables take precedence over `system.json`.|----------|-------------|---------|| `PULSE_PUBLIC_URL` | URL for UI links, notifications, and OIDC. For reverse proxies, keep this as the public URL and use `PULSE_AGENT_CONNECT_URL` for agent installs if you need a direct/internal address. | Auto-detected || `PULSE_AGENT_CONNECT_URL` | Dedicated direct URL for agents (overrides `PULSE_PUBLIC_URL` for agent install commands). Alias: `PULSE_AGENT_URL`. | *(unset)* |+| `PULSE_AGENT_CONFIG_SIGNING_KEY` | Base64 Ed25519 private key used to sign remote agent config payloads. | *(unset)* |+| `PULSE_AGENT_CONFIG_PUBLIC_KEYS` | Comma-separated base64 Ed25519 public keys (raw 32-byte or PKIX-encoded) trusted by agents. | *(unset)* |+| `PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED` | Require signed remote config payloads (set on Pulse and agents). | `false` || `ALLOWED_ORIGINS` | CORS allowed origin (`*` or a single origin). Empty = same-origin only. | *(unset)* || `DISCOVERY_ENABLED` | Auto-discover nodes | `false` || `DISCOVERY_SUBNET` | CIDR or `auto` | `auto` |diff --git a/docs/UNIFIED_AGENT.md b/docs/UNIFIED_AGENT.mdindex 45fd6c3b62..e4e4720b37 100644--- a/docs/UNIFIED_AGENT.md+++ b/docs/UNIFIED_AGENT.md@@ -207,6 +207,9 @@ Behavior:- Profile settings override local flags/env for supported keys.- Profile changes take effect on the next agent restart.- Command execution (`commandsEnabled`) is controlled per agent in **Settings → Agents → Unified Agents** and can change live.+- Remote config responses can be signed with `PULSE_AGENT_CONFIG_SIGNING_KEY` (base64 Ed25519 private key).+- To require signed payloads, set `PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED=true` on Pulse and agents.+- If you use a custom signing key, set `PULSE_AGENT_CONFIG_PUBLIC_KEYS` on agents to trust the matching public key.See [Centralized Agent Management](CENTRALIZED_MANAGEMENT.md) for supported keys and profile setup.diff --git a/frontend-modern/src/api/agentProfiles.ts b/frontend-modern/src/api/agentProfiles.tsindex 6a54738c95..cc666c6d1a 100644--- a/frontend-modern/src/api/agentProfiles.ts+++ b/frontend-modern/src/api/agentProfiles.ts@@ -39,6 +39,52 @@ export interface ProfileSuggestion {rationale: string[];}+export interface ConfigKeyDefinition {+ key: string;+ type: string;+ description: string;+ defaultValue?: unknown;+ required: boolean;+ min?: number;+ max?: number;+ pattern?: string;+ enum?: string[];+}++export interface ConfigValidationError {+ key: string;+ message: string;+}++export interface ConfigValidationResult {+ valid: boolean;+ errors: ConfigValidationError[];+ warnings: ConfigValidationError[];+}++type ConfigKeyDefinitionResponse = {+ Key: string;+ Type: string;+ Description: string;+ Default: unknown;+ Required: boolean;+ Min?: number;+ Max?: number;+ Pattern?: string;+ Enum?: string[];+};++type ConfigValidationErrorResponse = {+ Key: string;+ Message: string;+};++type ConfigValidationResultResponse = {+ Valid: boolean;+ Errors?: ConfigValidationErrorResponse[];+ Warnings?: ConfigValidationErrorResponse[];+};+/*** API client for agent profiles (Pro feature).* Endpoints are gated behind license - returns 402 if not licensed.@@ -192,4 +238,44 @@ export class AgentProfilesAPI {return response.json();}++ /**+ * Fetch config schema definitions for agent profiles.+ */+ static async getConfigSchema(): Promise<ConfigKeyDefinition[]> {+ const response = await apiFetchJSON<ConfigKeyDefinitionResponse[]>(`${this.baseUrl}/schema`);+ const defs = response || [];+ return defs.map(def => ({+ key: def.Key,+ type: def.Type,+ description: def.Description,+ defaultValue: def.Default,+ required: def.Required,+ min: def.Min,+ max: def.Max,+ pattern: def.Pattern,+ enum: def.Enum,+ }));+ }++ /**+ * Validate a config without saving.+ */+ static async validateConfig(config: Record<string, unknown>): Promise<ConfigValidationResult> {+ const response = await apiFetchJSON<ConfigValidationResultResponse>(`${this.baseUrl}/validate`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(config),+ });++ if (!response) {+ return { valid: true, errors: [], warnings: [] };+ }++ return {+ valid: response.Valid,+ errors: (response.Errors || []).map(err => ({ key: err.Key, message: err.Message })),+ warnings: (response.Warnings || []).map(err => ({ key: err.Key, message: err.Message })),+ };+ }}diff --git a/frontend-modern/src/api/opencode.ts b/frontend-modern/src/api/opencode.tsindex 6fdd7cb3e0..f1ba012860 100644--- a/frontend-modern/src/api/opencode.ts+++ b/frontend-modern/src/api/opencode.ts@@ -28,7 +28,7 @@ export interface ToolCall {}export interface StreamEvent {- type: 'content' | 'thinking' | 'tool_start' | 'tool_end' | 'tool' | 'done' | 'error';+ type: 'content' | 'thinking' | 'tool_start' | 'tool_end' | 'tool' | 'approval_needed' | 'question' | 'done' | 'error';data?: any;}@@ -76,6 +76,29 @@ export class OpenCodeAPI {});}+ // Approve a pending command+ static async approveCommand(approvalId: string): Promise<{ approved: boolean; message: string }> {+ return apiFetchJSON(`${this.baseUrl}/approvals/${approvalId}/approve`, {+ method: 'POST',+ }) as Promise<{ approved: boolean; message: string }>;+ }++ // Deny a pending command+ static async denyCommand(approvalId: string, reason?: string): Promise<{ denied: boolean; message: string }> {+ return apiFetchJSON(`${this.baseUrl}/approvals/${approvalId}/deny`, {+ method: 'POST',+ body: JSON.stringify({ reason: reason || 'User skipped' }),+ }) as Promise<{ denied: boolean; message: string }>;+ }++ // Answer a pending question from OpenCode+ static async answerQuestion(questionId: string, answers: Array<{ id: string; value: string }>): Promise<void> {+ await apiFetch(`${this.baseUrl}/question/${questionId}/answer`, {+ method: 'POST',+ body: JSON.stringify({ answers }),+ });+ }+// Stream chat - the main chat interfacestatic async chat(prompt: string,diff --git a/frontend-modern/src/components/AI/Chat/ChatMessages.tsx b/frontend-modern/src/components/AI/Chat/ChatMessages.tsxindex a78468d3c0..5139b7d7cc 100644--- a/frontend-modern/src/components/AI/Chat/ChatMessages.tsx+++ b/frontend-modern/src/components/AI/Chat/ChatMessages.tsx@@ -1,11 +1,13 @@import { Component, Show, For, createEffect } from 'solid-js';import { MessageItem } from './MessageItem';-import type { ChatMessage, PendingApproval } from './types';+import type { ChatMessage, PendingApproval, PendingQuestion } from './types';interface ChatMessagesProps {messages: ChatMessage[];onApprove: (messageId: string, approval: PendingApproval) => void;onSkip: (messageId: string, toolId: string) => void;+ onAnswerQuestion: (messageId: string, question: PendingQuestion, answers: Array<{ id: string; value: string }>) => void;+ onSkipQuestion: (messageId: string, questionId: string) => void;emptyState?: {title: string;subtitle: string;@@ -98,6 +100,8 @@ export const ChatMessages: Component<ChatMessagesProps> = (props) => {message={message}onApprove={(approval) => props.onApprove(message.id, approval)}onSkip={(toolId) => props.onSkip(message.id, toolId)}+ onAnswerQuestion={(question, answers) => props.onAnswerQuestion(message.id, question, answers)}+ onSkipQuestion={(questionId) => props.onSkipQuestion(message.id, questionId)}/>)}</For>diff --git a/frontend-modern/src/components/AI/Chat/MessageItem.tsx b/frontend-modern/src/components/AI/Chat/MessageItem.tsxindex 19c7c38998..010f02573a 100644--- a/frontend-modern/src/components/AI/Chat/MessageItem.tsx+++ b/frontend-modern/src/components/AI/Chat/MessageItem.tsx@@ -3,12 +3,15 @@ import { renderMarkdown } from '../aiChatUtils';import { ThinkingBlock } from './ThinkingBlock';import { ToolExecutionBlock, PendingToolBlock } from './ToolExecutionBlock';import { ApprovalCard } from './ApprovalCard';-import type { ChatMessage, PendingApproval, StreamDisplayEvent } from './types';+import { QuestionCard } from './QuestionCard';+import type { ChatMessage, PendingApproval, PendingQuestion, StreamDisplayEvent } from './types';interface MessageItemProps {message: ChatMessage;onApprove: (approval: PendingApproval) => void;onSkip: (toolId: string) => void;+ onAnswerQuestion: (question: PendingQuestion, answers: Array<{ id: string; value: string }>) => void;+ onSkipQuestion: (questionId: string) => void;}/**@@ -24,7 +27,7 @@ export const MessageItem: Component<MessageItemProps> = (props) => {props.message.streamEvents && props.message.streamEvents.length > 0;// Group stream events for cleaner rendering- // Combine consecutive content events, separate thinking and tools+ // Combine consecutive content events, separate thinking, tools, and approvalsconst groupedEvents = createMemo(() => {const events = props.message.streamEvents || [];const grouped: StreamDisplayEvent[] = [];@@ -42,6 +45,24 @@ export const MessageItem: Component<MessageItemProps> = (props) => {continue;}+ // Pending tool events are kept separate+ if (evt.type === 'pending_tool') {+ grouped.push(evt);+ continue;+ }++ // Approval events are kept separate+ if (evt.type === 'approval') {+ grouped.push(evt);+ continue;+ }++ // Question events are kept separate+ if (evt.type === 'question') {+ grouped.push(evt);+ continue;+ }+// Content events can be merged with previous contentif (evt.type === 'content' && evt.content) {const lastIdx = grouped.length - 1;@@ -119,12 +140,12 @@ export const MessageItem: Component<MessageItemProps> = (props) => {{/* Content/text block */}<Match when={evt.type === 'content' && evt.content}><div- class="text-sm prose prose-slate prose-sm dark:prose-invert max-w-none+ class="text-sm prose prose-slate prose-sm dark:prose-invert max-w-noneprose-p:leading-relaxed prose-p:my-2prose-pre:bg-slate-900 prose-pre:text-slate-100 prose-pre:rounded-lg prose-pre:text-xs- prose-code:text-purple-600 dark:prose-code:text-purple-400- prose-code:bg-purple-50 dark:prose-code:bg-purple-900/30- prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded+ prose-code:text-purple-600 dark:prose-code:text-purple-400+ prose-code:bg-purple-50 dark:prose-code:bg-purple-900/30+ prose-code:px-1.5 prose-code:py-0.5 prose-code:roundedprose-code:before:content-none prose-code:after:content-noneprose-headings:text-slate-900 dark:prose-headings:text-slate-100prose-strong:text-slate-900 dark:prose-strong:text-slate-100@@ -132,6 +153,28 @@ export const MessageItem: Component<MessageItemProps> = (props) => {innerHTML={renderMarkdown(evt.content!)}/></Match>++ {/* Approval card - inline in stream */}+ <Match when={evt.type === 'approval' && evt.approval}>+ <div class="my-3">+ <ApprovalCard+ approval={evt.approval!}+ onApprove={() => props.onApprove(evt.approval!)}+ onSkip={() => props.onSkip(evt.approval!.toolId)}+ />+ </div>+ </Match>++ {/* Question card - inline in stream */}+ <Match when={evt.type === 'question' && evt.question}>+ <div class="my-3">+ <QuestionCard+ question={evt.question!}+ onAnswer={(answers) => props.onAnswerQuestion(evt.question!, answers)}+ onSkip={() => props.onSkipQuestion(evt.question!.questionId)}+ />+ </div>+ </Match></Switch>)}</For>@@ -154,21 +197,6 @@ export const MessageItem: Component<MessageItemProps> = (props) => {/></Show>- {/* Pending approvals */}- <Show when={props.message.pendingApprovals && props.message.pendingApprovals.length > 0}>- <div class="mt-3 space-y-2">- <For each={props.message.pendingApprovals}>- {(approval) => (- <ApprovalCard- approval={approval}- onApprove={() => props.onApprove(approval)}- onSkip={() => props.onSkip(approval.toolId)}- />- )}- </For>- </div>- </Show>-{/* Streaming text indicator */}<Show when={isStreamingText()}><span class="inline-block w-2 h-4 ml-0.5 bg-purple-500 dark:bg-purple-400 animate-pulse rounded-sm" />diff --git a/frontend-modern/src/components/AI/Chat/ToolExecutionBlock.tsx b/frontend-modern/src/components/AI/Chat/ToolExecutionBlock.tsxindex 2418a9924e..8c9d5365cf 100644--- a/frontend-modern/src/components/AI/Chat/ToolExecutionBlock.tsx+++ b/frontend-modern/src/components/AI/Chat/ToolExecutionBlock.tsx@@ -9,7 +9,7 @@ interface ToolExecutionBlockProps {* ToolExecutionBlock - Displays completed tool executions in a compact terminal-like style.*/export const ToolExecutionBlock: Component<ToolExecutionBlockProps> = (props) => {- const [showOutput, setShowOutput] = createSignal(false);+ const [showOutput, setShowOutput] = createSignal(true);// Get display name for toolconst toolLabel = createMemo(() => {diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.tsindex b8de41558e..4f15fa01fb 100644--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts@@ -6,6 +6,7 @@ import type {ChatMessage,ToolExecution,StreamDisplayEvent,+ PendingQuestion,} from '../types';const generateId = () => Math.random().toString(36).substring(2, 9);@@ -173,6 +174,63 @@ export function useChat(options: UseChatOptions = {}) {};}+ case 'approval_needed': {+ const data = event.data as {+ command: string;+ tool_id: string;+ tool_name: string;+ run_on_host: boolean;+ target_host?: string;+ approval_id?: string;+ };++ const approval = {+ command: data.command,+ toolId: data.tool_id,+ toolName: data.tool_name,+ runOnHost: data.run_on_host,+ targetHost: data.target_host,+ isExecuting: false,+ approvalId: data.approval_id,+ };++ // Add to streamEvents for chronological display+ const updated = addStreamEvent(msg, { type: 'approval', approval });++ return {+ ...updated,+ pendingApprovals: [...(msg.pendingApprovals || []), approval],+ };+ }++ case 'question': {+ const data = event.data as {+ question_id: string;+ session_id: string;+ questions: Array<{+ id: string;+ type: 'text' | 'select';+ question: string;+ options?: Array<{ label: string; value: string }>;+ }>;+ };++ const pendingQuestion: PendingQuestion = {+ questionId: data.question_id,+ sessionId: data.session_id,+ questions: data.questions,+ isAnswering: false,+ };++ // Add to streamEvents for chronological display+ const updated = addStreamEvent(msg, { type: 'question', question: pendingQuestion });++ return {+ ...updated,+ pendingQuestions: [...(msg.pendingQuestions || []), pendingQuestion],+ };+ }+case 'done': {return { ...msg, isStreaming: false, pendingTools: [] };}@@ -198,6 +256,22 @@ export function useChat(options: UseChatOptions = {}) {const sendMessage = async (prompt: string) => {if (!prompt.trim() || isLoading()) return;+ // Ensure we have a session for conversation continuity+ // Without this, every message creates a new session and loses context+ let currentSessionId = sessionId();+ if (!currentSessionId) {+ try {+ const session = await OpenCodeAPI.createSession();+ currentSessionId = session.id;+ setSessionId(currentSessionId);+ logger.debug('[useChat] Created new session', { sessionId: currentSessionId });+ } catch (error) {+ logger.error('[useChat] Failed to create session:', error);+ notificationStore.error('Failed to create chat session');+ return;+ }+ }+// Add user messageconst userMessage: ChatMessage = {id: generateId(),@@ -227,7 +301,7 @@ export function useChat(options: UseChatOptions = {}) {try {await OpenCodeAPI.chat(prompt,- sessionId() || undefined,+ currentSessionId,model() || undefined,(event: StreamEvent) => {processEvent(assistantId, event);@@ -256,9 +330,10 @@ export function useChat(options: UseChatOptions = {}) {}};- // Clear messages+ // Clear messages and reset session (for starting fresh)const clearMessages = () => {setMessages([]);+ setSessionId(''); // Clear session so next message creates a new one};// Load session messages@@ -293,6 +368,84 @@ export function useChat(options: UseChatOptions = {}) {}};+ // Update pending approval state (e.g., to mark as executing or remove)+ const updateApproval = (messageId: string, toolId: string, update: Partial<{ isExecuting: boolean; removed: boolean }>) => {+ setMessages((prev) =>+ prev.map((msg) => {+ if (msg.id !== messageId) return msg;+ if (update.removed) {+ // Remove from pendingApprovals+ return {+ ...msg,+ pendingApprovals: (msg.pendingApprovals || []).filter((a) => a.toolId !== toolId),+ };+ }+ // Update the approval in place+ return {+ ...msg,+ pendingApprovals: (msg.pendingApprovals || []).map((a) =>+ a.toolId === toolId ? { ...a, ...update } : a+ ),+ };+ })+ );+ };++ // Add a tool call result to a message (after approval execution)+ const addToolResult = (messageId: string, toolCall: { name: string; input: string; output: string; success: boolean }) => {+ setMessages((prev) =>+ prev.map((msg) => {+ if (msg.id !== messageId) return msg;+ return {+ ...msg,+ toolCalls: [...(msg.toolCalls || []), toolCall],+ streamEvents: [+ ...(msg.streamEvents || []),+ { type: 'tool' as const, tool: toolCall },+ ],+ };+ })+ );+ };++ // Update pending question state (e.g., to mark as answering or remove)+ const updateQuestion = (messageId: string, questionId: string, update: Partial<{ isAnswering: boolean; removed: boolean }>) => {+ setMessages((prev) =>+ prev.map((msg) => {+ if (msg.id !== messageId) return msg;+ if (update.removed) {+ // Remove from pendingQuestions+ return {+ ...msg,+ pendingQuestions: (msg.pendingQuestions || []).filter((q) => q.questionId !== questionId),+ };+ }+ // Update the question in place+ return {+ ...msg,+ pendingQuestions: (msg.pendingQuestions || []).map((q) =>+ q.questionId === questionId ? { ...q, ...update } : q+ ),+ };+ })+ );+ };++ // Answer a pending question+ const answerQuestion = async (messageId: string, questionId: string, answers: Array<{ id: string; value: string }>) => {+ updateQuestion(messageId, questionId, { isAnswering: true });++ try {+ await OpenCodeAPI.answerQuestion(questionId, answers);+ // Remove the question after successful answer+ updateQuestion(messageId, questionId, { removed: true });+ } catch (error) {+ logger.error('[useChat] Failed to answer question:', error);+ notificationStore.error('Failed to answer question');+ updateQuestion(messageId, questionId, { isAnswering: false });+ }+ };+return {messages,isLoading,@@ -304,5 +457,9 @@ export function useChat(options: UseChatOptions = {}) {clearMessages,loadSession,newSession,+ updateApproval,+ addToolResult,+ updateQuestion,+ answerQuestion,};}diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsxindex a4adbcd3ed..b39d6113da 100644--- a/frontend-modern/src/components/AI/Chat/index.tsx+++ b/frontend-modern/src/components/AI/Chat/index.tsx@@ -1,10 +1,16 @@-import { Component, Show, createSignal, onMount, For, createMemo } from 'solid-js';+import { Component, Show, createSignal, onMount, For, createMemo, createEffect } from 'solid-js';+import { AIAPI } from '@/api/ai';import { OpenCodeAPI, type ChatSession } from '@/api/opencode';import { notificationStore } from '@/stores/notifications';import { logger } from '@/utils/logger';import { useChat } from './hooks/useChat';import { ChatMessages } from './ChatMessages';-import type { PendingApproval } from './types';+import { PROVIDER_DISPLAY_NAMES, getProviderFromModelId, groupModelsByProvider } from '../aiChatUtils';+import type { PendingApproval, ModelInfo } from './types';++const MODEL_LEGACY_STORAGE_KEY = 'pulse:ai_chat_model';+const MODEL_SESSION_STORAGE_KEY = 'pulse:ai_chat_models_by_session';+const DEFAULT_SESSION_KEY = '__default__';interface AIChatProps {onClose: () => void;@@ -22,9 +28,176 @@ export const AIChat: Component<AIChatProps> = (props) => {const [input, setInput] = createSignal('');const [sessions, setSessions] = createSignal<ChatSession[]>([]);const [showSessions, setShowSessions] = createSignal(false);+ const [showModelSelector, setShowModelSelector] = createSignal(false);+ const [models, setModels] = createSignal<ModelInfo[]>([]);+ const [modelsLoading, setModelsLoading] = createSignal(false);+ const [modelsError, setModelsError] = createSignal('');+ const [modelQuery, setModelQuery] = createSignal('');+ const [defaultModel, setDefaultModel] = createSignal('');+ const [chatOverrideModel, setChatOverrideModel] = createSignal('');++ const loadModelSelections = (): Record<string, string> => {+ try {+ const raw = localStorage.getItem(MODEL_SESSION_STORAGE_KEY);+ const parsed = raw ? JSON.parse(raw) : {};+ const selections = typeof parsed === 'object' && parsed ? parsed as Record<string, string> : {};+ const legacy = localStorage.getItem(MODEL_LEGACY_STORAGE_KEY);+ if (legacy && !selections[DEFAULT_SESSION_KEY]) {+ selections[DEFAULT_SESSION_KEY] = legacy;+ }+ if (legacy) {+ localStorage.removeItem(MODEL_LEGACY_STORAGE_KEY);+ }+ return selections;+ } catch (error) {+ logger.warn('[AIChat] Failed to read stored models:', error);+ return {};+ }+ };++ const persistModelSelections = (selections: Record<string, string>) => {+ try {+ localStorage.setItem(MODEL_SESSION_STORAGE_KEY, JSON.stringify(selections));+ } catch (error) {+ logger.warn('[AIChat] Failed to persist model selections:', error);+ }+ };++ const initialModelSelections = loadModelSelections();+ const [modelSelections, setModelSelections] = createSignal<Record<string, string>>(initialModelSelections);++ const getStoredModel = (sessionId: string) => {+ const key = sessionId || DEFAULT_SESSION_KEY;+ return modelSelections()[key] || '';+ };++ const updateStoredModel = (sessionId: string, modelId: string) => {+ const key = sessionId || DEFAULT_SESSION_KEY;+ setModelSelections((prev) => {+ const next = { ...prev };+ if (modelId) {+ next[key] = modelId;+ } else {+ delete next[key];+ }+ persistModelSelections(next);+ return next;+ });+ };// Chat hook- const chat = useChat();+ const chat = useChat({ model: initialModelSelections[DEFAULT_SESSION_KEY] || '' });++ const defaultModelLabel = createMemo(() => {+ const fallback = defaultModel().trim();+ if (!fallback) return '';+ const match = models().find((model) => model.id === fallback);+ return match ? (match.name || match.id.split(':').pop() || match.id) : fallback;+ });++ const chatOverrideLabel = createMemo(() => {+ const override = chatOverrideModel().trim();+ if (!override) return '';+ const match = models().find((model) => model.id === override);+ return match ? (match.name || match.id.split(':').pop() || match.id) : override;+ });++ const selectedModelLabel = createMemo(() => {+ const selected = chat.model().trim();+ if (!selected) {+ const fallback = defaultModelLabel();+ return fallback ? `Default (${fallback})` : 'Default';+ }+ const match = models().find((model) => model.id === selected);+ if (match) return match.name || match.id.split(':').pop() || match.id;+ return selected;+ });++ const filteredModels = createMemo(() => {+ const query = modelQuery().trim().toLowerCase();+ if (!query) return models();+ return models().filter((model) => {+ const provider = getProviderFromModelId(model.id);+ const providerName = PROVIDER_DISPLAY_NAMES[provider] || provider;+ const modelName = model.name || '';+ return (+ model.id.toLowerCase().includes(query) ||+ modelName.toLowerCase().includes(query) ||+ (model.description || '').toLowerCase().includes(query) ||+ provider.toLowerCase().includes(query) ||+ providerName.toLowerCase().includes(query)+ );+ });+ });++ const customModelCandidate = createMemo(() => modelQuery().trim());+ const showCustomModelOption = createMemo(() => {+ const candidate = customModelCandidate();+ if (!candidate) return false;+ return !models().some((model) => model.id === candidate);+ });++ const loadModels = async (notify = false) => {+ if (notify) {+ notificationStore.info('Refreshing models...', 2000);+ }+ setModelsLoading(true);+ setModelsError('');+ try {+ const result = await AIAPI.getModels();+ const nextModels = result.models || [];+ setModels(nextModels);+ if (result.error) {+ setModelsError(result.error);+ if (notify) {+ notificationStore.warning(result.error, 6000);+ }+ } else if (notify) {+ notificationStore.success(`Models refreshed (${nextModels.length})`, 2000);+ }+ } catch (error) {+ logger.error('[AIChat] Failed to load models:', error);+ setModels([]);+ const message = error instanceof Error ? error.message : 'Failed to load models.';+ setModelsError(message);+ notificationStore.error(message);+ } finally {+ setModelsLoading(false);+ }+ };++ const loadSettings = async () => {+ try {+ const settings = await AIAPI.getSettings();+ const chatOverride = (settings.chat_model || '').trim();+ const fallback = chatOverride || (settings.model || '').trim();+ setDefaultModel(fallback);+ setChatOverrideModel(chatOverride);+ } catch (error) {+ logger.error('[AIChat] Failed to load AI settings:', error);+ }+ };++ const selectModel = (modelId: string) => {+ chat.setModel(modelId);+ updateStoredModel(chat.sessionId(), modelId);+ setShowModelSelector(false);+ setModelQuery('');+ };++ createEffect(() => {+ const sessionId = chat.sessionId();+ const storedModel = getStoredModel(sessionId);+ if (storedModel) {+ if (chat.model() !== storedModel) {+ chat.setModel(storedModel);+ }+ return;+ }+ if (chat.model()) {+ chat.setModel('');+ }+ });// Compute current status for displayconst currentStatus = createMemo(() => {@@ -60,6 +233,8 @@ export const AIChat: Component<AIChatProps> = (props) => {}const sessionList = await OpenCodeAPI.listSessions();setSessions(sessionList);+ await loadSettings();+ await loadModels();} catch (error) {logger.error('[AIChat] Failed to initialize:', error);}@@ -100,6 +275,7 @@ export const AIChat: Component<AIChatProps> = (props) => {try {await OpenCodeAPI.deleteSession(sessionId);setSessions(prev => prev.filter(s => s.id !== sessionId));+ updateStoredModel(sessionId, '');if (chat.sessionId() === sessionId) {chat.clearMessages();}@@ -108,9 +284,84 @@ export const AIChat: Component<AIChatProps> = (props) => {}};- // Empty state for approval (not used with OpenCode but keeping interface)- const handleApprove = (_messageId: string, _approval: PendingApproval) => { };- const handleSkip = (_messageId: string, _toolId: string) => { };+ // Approval handlers+ const handleApprove = async (messageId: string, approval: PendingApproval) => {+ if (!approval.approvalId) {+ notificationStore.error('No approval ID available');+ return;+ }++ // Mark as executing+ chat.updateApproval(messageId, approval.toolId, { isExecuting: true });++ try {+ const result = await OpenCodeAPI.approveCommand(approval.approvalId);++ // Remove from pending approvals+ chat.updateApproval(messageId, approval.toolId, { removed: true });++ // Add tool result if command was executed+ if (result.approved) {+ const execResult = (result as { result?: { stdout?: string; stderr?: string; exit_code?: number } }).result;+ const output = execResult+ ? `Exit code: ${execResult.exit_code}\n${execResult.stdout || ''}${execResult.stderr ? '\nStderr: ' + execResult.stderr : ''}`+ : 'Command approved but no execution result available.';++ chat.addToolResult(messageId, {+ name: approval.toolName,+ input: approval.command,+ output: output.trim(),+ success: execResult ? execResult.exit_code === 0 : false,+ });+ }+ } catch (error) {+ logger.error('[AIChat] Approval failed:', error);+ notificationStore.error('Failed to approve command');+ chat.updateApproval(messageId, approval.toolId, { isExecuting: false });+ }+ };++ const handleSkip = async (messageId: string, toolId: string) => {+ // Find the approval to get the approvalId+ const msg = chat.messages().find((m) => m.id === messageId);+ const approval = msg?.pendingApprovals?.find((a) => a.toolId === toolId);++ if (!approval?.approvalId) {+ // Just remove from UI if no approval ID+ chat.updateApproval(messageId, toolId, { removed: true });+ return;+ }++ try {+ await OpenCodeAPI.denyCommand(approval.approvalId, 'User skipped');+ chat.updateApproval(messageId, toolId, { removed: true });+ } catch (error) {+ logger.error('[AIChat] Skip/deny failed:', error);+ // Still remove from UI even if API fails+ chat.updateApproval(messageId, toolId, { removed: true });+ }+ };++ const toggleModelSelector = () => {+ const next = !showModelSelector();+ setShowModelSelector(next);+ if (next) {+ setShowSessions(false);+ setModelQuery('');+ if (models().length === 0 && !modelsLoading()) {+ loadModels();+ }+ }+ };++ const handleModelInputKeyDown = (e: KeyboardEvent) => {+ if (e.key !== 'Enter') return;+ e.preventDefault();+ const candidate = customModelCandidate();+ if (candidate) {+ selectModel(candidate);+ }+ };return (<div@@ -135,10 +386,142 @@ export const AIChat: Component<AIChatProps> = (props) => {</div><div class="flex items-center gap-1.5">+ {/* Model selector */}+ <div class="relative">+ <button+ onClick={toggleModelSelector}+ class="flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] text-slate-600 dark:text-slate-300 hover:text-slate-800 dark:hover:text-slate-100 rounded-lg border border-slate-200 dark:border-slate-700 hover:border-slate-300 dark:hover:border-slate-600 bg-white dark:bg-slate-800 transition-colors"+ title="Select model for this chat"+ >+ <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />+ </svg>+ <span class="max-w-[120px] truncate font-medium">{selectedModelLabel()}</span>+ <Show when={modelsLoading()}>+ <svg class="w-3 h-3 text-slate-400 animate-spin" fill="none" viewBox="0 0 24 24">+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="3" />+ <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />+ </svg>+ </Show>+ <svg class="w-3 h-3 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />+ </svg>+ </button>++ <Show when={showModelSelector()}>+ <div class="absolute right-0 top-full mt-1 w-80 max-h-96 overflow-hidden bg-white dark:bg-slate-800 rounded-xl shadow-xl border border-slate-200 dark:border-slate-700 z-50">+ <div class="flex items-center gap-2 px-3 py-2 border-b border-slate-200 dark:border-slate-700">+ <input+ type="text"+ value={modelQuery()}+ onInput={(e) => setModelQuery(e.currentTarget.value)}+ onKeyDown={handleModelInputKeyDown}+ placeholder="Search or enter model ID"+ class="flex-1 text-xs px-2 py-1.5 rounded-md border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 text-slate-700 dark:text-slate-200 focus:outline-none focus:ring-2 focus:ring-purple-400/50"+ />+ <button+ type="button"+ onClick={() => loadModels(true)}+ disabled={modelsLoading()}+ class="p-1.5 rounded-md text-slate-500 hover:text-slate-700 dark:hover:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-700 disabled:opacity-50"+ title="Refresh models"+ >+ <svg class={`w-3.5 h-3.5 ${modelsLoading() ? 'animate-spin' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v6h6M20 20v-6h-6M5.32 9A7.5 7.5 0 0119 12.5M18.68 15A7.5 7.5 0 015 11.5" />+ </svg>+ </button>+ </div>++ <Show when={modelsError()}>+ <div class="px-3 py-2 text-[11px] text-red-500 border-b border-slate-200 dark:border-slate-700">+ {modelsError()}+ </div>+ </Show>++ <div class="max-h-72 overflow-y-auto py-1">+ <button+ onClick={() => selectModel('')}+ class={`w-full px-3 py-2 text-left text-sm hover:bg-slate-50 dark:hover:bg-slate-700 ${!chat.model() ? 'bg-purple-50 dark:bg-purple-900/30' : ''}`}+ >+ <div class="font-medium text-slate-900 dark:text-slate-100">Default</div>+ <div class="text-[11px] text-slate-500 dark:text-slate-400">+ {defaultModelLabel() ? `Use configured default model (${defaultModelLabel()})` : 'Use configured default model'}+ </div>+ </button>++ <Show when={chatOverrideModel()}>+ <button+ onClick={() => selectModel(chatOverrideModel())}+ class={`w-full px-3 py-2 text-left text-sm hover:bg-slate-50 dark:hover:bg-slate-700 ${chat.model() === chatOverrideModel() ? 'bg-purple-50 dark:bg-purple-900/30' : ''}`}+ >+ <div class="font-medium text-slate-900 dark:text-slate-100">Chat override</div>+ <div class="text-[11px] text-slate-500 dark:text-slate-400">+ {chatOverrideLabel() || chatOverrideModel()}+ </div>+ </button>+ </Show>++ <Show when={showCustomModelOption()}>+ <button+ onClick={() => selectModel(customModelCandidate())}+ class="w-full px-3 py-2 text-left text-sm hover:bg-slate-50 dark:hover:bg-slate-700"+ >+ <div class="font-medium text-slate-900 dark:text-slate-100">+ Use "{customModelCandidate()}"+ </div>+ <div class="text-[11px] text-slate-500 dark:text-slate-400">Custom model ID</div>+ </button>+ </Show>++ <Show when={!modelsLoading() && filteredModels().length === 0}>+ <div class="px-3 py-4 text-center text-[11px] text-slate-500 dark:text-slate-400">+ No matching models.+ </div>+ </Show>++ <For each={Array.from(groupModelsByProvider(filteredModels()).entries())}>+ {([provider, providerModels]) => (+ <>+ <div class="px-3 py-1.5 text-[11px] font-semibold text-slate-500 dark:text-slate-400 bg-slate-50 dark:bg-slate-700/50 sticky top-0">+ {PROVIDER_DISPLAY_NAMES[provider] || provider}+ </div>+ <For each={providerModels}>+ {(model) => (+ <button+ onClick={() => selectModel(model.id)}+ class={`w-full px-3 py-2 text-left text-sm hover:bg-slate-50 dark:hover:bg-slate-700 ${chat.model() === model.id ? 'bg-purple-50 dark:bg-purple-900/30' : ''}`}+ >+ <div class="font-medium text-slate-900 dark:text-slate-100">+ {model.name || model.id.split(':').pop() || model.id}+ </div>+ <Show when={model.description}>+ <div class="text-[11px] text-slate-500 dark:text-slate-400 line-clamp-2">+ {model.description}+ </div>+ </Show>+ <Show when={model.name && model.name !== model.id}>+ <div class="text-[10px] text-slate-400 dark:text-slate-500">+ {model.id}+ </div>+ </Show>+ </button>+ )}+ </For>+ </>+ )}+ </For>+ </div>+ </div>+ </Show>+ </div>+{/* Session picker */}<div class="relative"><button- onClick={() => setShowSessions(!showSessions())}+ onClick={() => {+ setShowModelSelector(false);+ setShowSessions(!showSessions());+ }}class="p-2 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors"title="Chat sessions">diff --git a/frontend-modern/src/components/AI/Chat/types.ts b/frontend-modern/src/components/AI/Chat/types.tsindex b69584a6dd..190b11d547 100644--- a/frontend-modern/src/components/AI/Chat/types.ts+++ b/frontend-modern/src/components/AI/Chat/types.ts@@ -19,10 +19,31 @@ export interface PendingApproval {runOnHost: boolean;targetHost?: string;isExecuting?: boolean;+ approvalId?: string; // ID of the approval record for API calls+}++// Question from OpenCode+export interface QuestionOption {+ label: string;+ value: string;+}++export interface Question {+ id: string;+ type: 'text' | 'select';+ question: string;+ options?: QuestionOption[];+}++export interface PendingQuestion {+ questionId: string;+ sessionId: string;+ questions: Question[];+ isAnswering?: boolean;}// Unified event for chronological display-export type StreamEventType = 'thinking' | 'tool' | 'content' | 'pending_tool';+export type StreamEventType = 'thinking' | 'tool' | 'content' | 'pending_tool' | 'approval' | 'question';export interface StreamDisplayEvent {type: StreamEventType;@@ -31,6 +52,8 @@ export interface StreamDisplayEvent {pendingTool?: PendingTool;content?: string;toolId?: string; // Used to match pending_tool with completed tool+ approval?: PendingApproval; // For approval_needed events+ question?: PendingQuestion; // For question events}export interface ChatMessage {@@ -47,6 +70,7 @@ export interface ChatMessage {isStreaming?: boolean;pendingTools?: PendingTool[];pendingApprovals?: PendingApproval[];+ pendingQuestions?: PendingQuestion[];}export interface ModelInfo {@@ -71,11 +95,23 @@ export type StreamEventKind =| 'tool_start'| 'tool_end'| 'approval_needed'+ | 'question'| 'processing'| 'complete'| 'done'| 'error';+export interface StreamQuestionData {+ question_id: string;+ session_id: string;+ questions: Array<{+ id: string;+ type: 'text' | 'select';+ question: string;+ options?: Array<{ label: string; value: string }>;+ }>;+}+export interface StreamToolStartData {name: string;input: string;@@ -94,6 +130,7 @@ export interface StreamApprovalNeededData {tool_name: string;run_on_host: boolean;target_host?: string;+ approval_id?: string;}export interface StreamCompleteData {diff --git a/frontend-modern/src/components/Settings/AgentProfilesPanel.tsx b/frontend-modern/src/components/Settings/AgentProfilesPanel.tsxindex 980b1da1b2..9d3384dc13 100644--- a/frontend-modern/src/components/Settings/AgentProfilesPanel.tsx+++ b/frontend-modern/src/components/Settings/AgentProfilesPanel.tsx@@ -7,6 +7,7 @@ import { notificationStore } from '@/stores/notifications';import { logger } from '@/utils/logger';import { formatRelativeTime } from '@/utils/format';import { SuggestProfileModal } from './SuggestProfileModal';+import { KNOWN_SETTINGS, type SelectSetting, type StringSetting } from './agentProfileSettings';import Plus from 'lucide-solid/icons/plus';import Pencil from 'lucide-solid/icons/pencil';import Trash2 from 'lucide-solid/icons/trash-2';@@ -15,60 +16,6 @@ import Users from 'lucide-solid/icons/users';import Settings from 'lucide-solid/icons/settings';import Sparkles from 'lucide-solid/icons/sparkles';-// Known agent settings with their types and descriptions-interface BooleanSetting {- key: string;- type: 'boolean';- label: string;- description: string;-}--interface SelectSetting {- key: string;- type: 'select';- label: string;- description: string;- options: string[];-}--interface DurationSetting {- key: string;- type: 'duration';- label: string;- description: string;-}--interface StringSetting {- key: string;- type: 'string';- label: string;- description: string;- placeholder?: string;-}--type KnownSetting = BooleanSetting | SelectSetting | DurationSetting | StringSetting;--// Settings that the agent actually supports (from applyRemoteSettings in cmd/pulse-agent/main.go)-const KNOWN_SETTINGS: KnownSetting[] = [- // Core monitoring- { key: 'enable_host', type: 'boolean', label: 'Enable Host Monitoring', description: 'Collect host metrics and allow command execution' },- { key: 'enable_docker', type: 'boolean', label: 'Enable Docker Monitoring', description: 'Monitor Docker or Podman containers on this agent' },- { key: 'docker_runtime', type: 'select', label: 'Docker Runtime', description: 'Force a specific container runtime', options: ['auto', 'docker', 'podman'] },- { key: 'enable_kubernetes', type: 'boolean', label: 'Enable Kubernetes Monitoring', description: 'Monitor Kubernetes workloads' },- { key: 'kube_include_all_pods', type: 'boolean', label: 'Include All Pods', description: 'Include all non-succeeded pods in reports' },- { key: 'kube_include_all_deployments', type: 'boolean', label: 'Include All Deployments', description: 'Include all deployments, not just problem ones' },- { key: 'enable_proxmox', type: 'boolean', label: 'Enable Proxmox Mode', description: 'Auto-detect and configure Proxmox API access' },- { key: 'proxmox_type', type: 'select', label: 'Proxmox Type', description: 'Force PVE or PBS mode', options: ['auto', 'pve', 'pbs'] },- { key: 'disable_ceph', type: 'boolean', label: 'Disable Ceph Monitoring', description: 'Skip local Ceph status polling' },- // Timing- { key: 'interval', type: 'duration', label: 'Reporting Interval', description: 'How often the agent reports metrics (e.g., 30s, 1m)' },- // Network- { key: 'report_ip', type: 'string', label: 'Report IP Override', description: 'Override the reported IP address', placeholder: '' },- // Operations- { key: 'disable_auto_update', type: 'boolean', label: 'Disable Auto Updates', description: 'Stop the unified agent from auto-updating' },- { key: 'disable_docker_update_checks', type: 'boolean', label: 'Disable Docker Update Checks', description: 'Skip Docker image update detection (avoid registry rate limits)' },- { key: 'log_level', type: 'select', label: 'Log Level', description: 'Agent logging verbosity', options: ['debug', 'info', 'warn', 'error'] },-];export const AgentProfilesPanel: Component = () => {const { state } = useWebSocket();diff --git a/frontend-modern/src/components/Settings/SuggestProfileModal.tsx b/frontend-modern/src/components/Settings/SuggestProfileModal.tsxindex c7b930489a..4b96762230 100644--- a/frontend-modern/src/components/Settings/SuggestProfileModal.tsx+++ b/frontend-modern/src/components/Settings/SuggestProfileModal.tsx@@ -1,7 +1,9 @@-import { Component, createSignal, Show, For } from 'solid-js';-import { AgentProfilesAPI, type ProfileSuggestion } from '@/api/agentProfiles';+import { Component, createSignal, Show, For, createMemo, createEffect, on, onMount } from 'solid-js';+import { AgentProfilesAPI, type ProfileSuggestion, type ConfigKeyDefinition, type ConfigValidationResult } from '@/api/agentProfiles';import { notificationStore } from '@/stores/notifications';import { logger } from '@/utils/logger';+import { formatRelativeTime } from '@/utils/format';+import { KNOWN_SETTINGS_BY_KEY } from './agentProfileSettings';import Sparkles from 'lucide-solid/icons/sparkles';import AlertCircle from 'lucide-solid/icons/alert-circle';import Check from 'lucide-solid/icons/check';@@ -12,11 +14,63 @@ interface SuggestProfileModalProps {onSuggestionAccepted: (suggestion: ProfileSuggestion) => void;}+interface SuggestionHistoryItem {+ id: string;+ prompt: string;+ suggestion: ProfileSuggestion;+ createdAt: number;+}++interface SettingPreviewItem {+ key: string;+ label: string;+ description: string;+ value: unknown;+ defaultValue?: unknown;+ type?: string;+ known: boolean;+}++const createHistoryId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;++const toTitleCase = (value: string) =>+ value+ .split('_')+ .filter(Boolean)+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))+ .join(' ');++const formatDisplayValue = (value: unknown) => {+ if (value === null || value === undefined) return 'unset';+ if (typeof value === 'boolean') return value ? 'Enabled' : 'Disabled';+ if (typeof value === 'string') return value === '' ? '(empty)' : value;+ if (typeof value === 'number') return String(value);+ return JSON.stringify(value);+};++const formatValueBadgeClass = (value: unknown) => {+ if (typeof value === 'boolean') {+ return value+ ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300'+ : 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300';+ }+ return 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300';+};++const hasValue = (value: unknown) => value !== null && value !== undefined;+export const SuggestProfileModal: Component<SuggestProfileModalProps> = (props) => {const [prompt, setPrompt] = createSignal('');const [loading, setLoading] = createSignal(false);const [error, setError] = createSignal<string | null>(null);const [suggestion, setSuggestion] = createSignal<ProfileSuggestion | null>(null);+ const [schema, setSchema] = createSignal<ConfigKeyDefinition[]>([]);+ const [schemaError, setSchemaError] = createSignal<string | null>(null);+ const [validation, setValidation] = createSignal<ConfigValidationResult | null>(null);+ const [validationError, setValidationError] = createSignal<string | null>(null);+ const [history, setHistory] = createSignal<SuggestionHistoryItem[]>([]);+ const [activeHistoryId, setActiveHistoryId] = createSignal<string | null>(null);+ const [showDefaults, setShowDefaults] = createSignal(false);// Example prompts for inspirationconst examplePrompts = [@@ -26,6 +80,109 @@ export const SuggestProfileModal: Component<SuggestProfileModalProps> = (props)'Development environment profile with debug logging',];+ const schemaByKey = createMemo(() => new Map(schema().map(def => [def.key, def])));++ const activeHistoryItem = createMemo(() => {+ const currentId = activeHistoryId();+ if (!currentId) return null;+ return history().find(item => item.id === currentId) || null;+ });++ const settingsPreview = createMemo<SettingPreviewItem[]>(() => {+ const current = suggestion();+ if (!current) return [];++ const config = current.config || {};+ const items = Object.entries(config).map(([key, value]) => {+ const known = KNOWN_SETTINGS_BY_KEY.get(key);+ const definition = schemaByKey().get(key);+ return {+ key,+ label: known?.label ?? toTitleCase(key),+ description: known?.description ?? definition?.description ?? 'No description available.',+ value,+ defaultValue: definition?.defaultValue,+ type: definition?.type,+ known: Boolean(known || definition),+ };+ });++ return items.sort((a, b) => {+ if (a.known !== b.known) return a.known ? -1 : 1;+ return a.key.localeCompare(b.key);+ });+ });++ const omittedDefaults = createMemo<ConfigKeyDefinition[]>(() => {+ const current = suggestion();+ if (!current || schema().length === 0) return [];+ const presentKeys = new Set(Object.keys(current.config || {}));+ return schema().filter(def => !presentKeys.has(def.key) && hasValue(def.defaultValue));+ });++ const riskHints = createMemo(() => {+ const current = suggestion();+ if (!current) return [];+ const config = current.config || {};+ const hints: string[] = [];++ if (config.disable_auto_update === true) {+ hints.push('Auto updates are disabled. Plan manual patching for agents.');+ }+ if (config.disable_docker_update_checks === true) {+ hints.push('Docker update checks are disabled. Update visibility will be limited.');+ }+ if (config.enable_host === false) {+ hints.push('Host monitoring is disabled. Host metrics and command execution will stop.');+ }+ if (config.enable_docker === false) {+ hints.push('Docker monitoring is disabled. Container metrics and update tracking will stop.');+ }+ if (config.disable_ceph === true) {+ hints.push('Ceph monitoring is disabled. Cluster health checks will be skipped.');+ }++ return hints;+ });++ onMount(async () => {+ try {+ const defs = await AgentProfilesAPI.getConfigSchema();+ setSchema(defs);+ setSchemaError(null);+ } catch (err) {+ logger.error('Failed to load agent profile schema', err);+ setSchema([]);+ setSchemaError('Defaults and validation details are unavailable right now.');+ }+ });++ let validationRequestId = 0;+ createEffect(on(suggestion, (current) => {+ validationRequestId += 1;+ const requestId = validationRequestId;++ if (!current) {+ setValidation(null);+ setValidationError(null);+ return;+ }++ setValidationError(null);+ (async () => {+ try {+ const result = await AgentProfilesAPI.validateConfig(current.config || {});+ if (requestId !== validationRequestId) return;+ setValidation(result);+ } catch (err) {+ if (requestId !== validationRequestId) return;+ logger.error('Failed to validate profile suggestion', err);+ setValidationError('Validation unavailable right now. You can still review the draft.');+ setValidation(null);+ }+ })();+ }));+const handleSubmit = async () => {const userPrompt = prompt().trim();if (!userPrompt) {@@ -35,13 +192,21 @@ export const SuggestProfileModal: Component<SuggestProfileModalProps> = (props)setLoading(true);setError(null);- setSuggestion(null);try {const result = await AgentProfilesAPI.suggestProfile({prompt: userPrompt,});+ const historyEntry: SuggestionHistoryItem = {+ id: createHistoryId(),+ prompt: userPrompt,+ suggestion: result,+ createdAt: Date.now(),+ };+ setHistory(prev => [historyEntry, ...prev].slice(0, 5));+ setActiveHistoryId(historyEntry.id);setSuggestion(result);+ setShowDefaults(false);} catch (err) {logger.error('Failed to get profile suggestion', err);const message = err instanceof Error ? err.message : 'Failed to get suggestion';@@ -63,6 +228,14 @@ export const SuggestProfileModal: Component<SuggestProfileModalProps> = (props)setPrompt(example);};+ const handleSelectHistory = (item: SuggestionHistoryItem) => {+ setSuggestion(item.suggestion);+ setPrompt(item.prompt);+ setActiveHistoryId(item.id);+ setError(null);+ setShowDefaults(false);+ };+return (<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm"><div class="w-full max-w-2xl bg-white dark:bg-gray-900 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-700 mx-4 max-h-[90vh] overflow-hidden flex flex-col">@@ -107,6 +280,11 @@ export const SuggestProfileModal: Component<SuggestProfileModalProps> = (props)class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 shadow-sm focus:border-purple-500 focus:outline-none focus:ring-2 focus:ring-purple-200 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:focus:border-purple-400 dark:focus:ring-purple-800/60 resize-none"disabled={loading()}/>+ <Show when={suggestion()}>+ <p class="text-xs text-gray-500 dark:text-gray-400">+ Tip: edit the prompt and click Regenerate to refine the draft.+ </p>+ </Show></div>{/* Example Prompts */}@@ -140,9 +318,9 @@ export const SuggestProfileModal: Component<SuggestProfileModalProps> = (props){/* Loading State */}<Show when={loading()}>- <div class="flex items-center justify-center py-8">- <Loader2 class="w-6 h-6 text-purple-600 dark:text-purple-400 animate-spin" />- <span class="ml-3 text-gray-600 dark:text-gray-400">Generating suggestion...</span>+ <div class="flex items-center justify-center py-4">+ <Loader2 class="w-5 h-5 text-purple-600 dark:text-purple-400 animate-spin" />+ <span class="ml-3 text-sm text-gray-600 dark:text-gray-400">Generating suggestion...</span></div></Show>@@ -154,25 +332,193 @@ export const SuggestProfileModal: Component<SuggestProfileModalProps> = (props)<div class="flex items-start gap-2 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800"><AlertCircle class="w-4 h-4 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" /><p class="text-sm text-amber-700 dark:text-amber-300">- This is a draft suggestion. Review the settings before creating the profile.+ Draft suggestion — review settings before creating the profile.</p></div>+ <Show when={validationError()}>+ <div class="flex items-start gap-2 p-3 rounded-lg bg-gray-50 dark:bg-gray-800/60 border border-gray-200 dark:border-gray-700">+ <AlertCircle class="w-4 h-4 text-gray-500 dark:text-gray-400 mt-0.5 shrink-0" />+ <p class="text-xs text-gray-600 dark:text-gray-300">{validationError()}</p>+ </div>+ </Show>++ <Show when={schemaError()}>+ <div class="flex items-start gap-2 p-3 rounded-lg bg-gray-50 dark:bg-gray-800/60 border border-gray-200 dark:border-gray-700">+ <AlertCircle class="w-4 h-4 text-gray-500 dark:text-gray-400 mt-0.5 shrink-0" />+ <p class="text-xs text-gray-600 dark:text-gray-300">{schemaError()}</p>+ </div>+ </Show>++ <Show when={validation()?.errors?.length}>+ <div class="flex items-start gap-2 p-3 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800">+ <AlertCircle class="w-4 h-4 text-red-600 dark:text-red-400 mt-0.5 shrink-0" />+ <div class="space-y-1">+ <p class="text-sm font-medium text-red-700 dark:text-red-300">+ Fix these before saving.+ </p>+ <ul class="text-xs text-red-700 dark:text-red-300 space-y-1">+ <For each={validation()?.errors || []}>+ {(issue) => (+ <li class="flex items-start gap-2">+ <span class="font-mono text-red-700 dark:text-red-200">{issue.key}</span>+ <span>{issue.message}</span>+ </li>+ )}+ </For>+ </ul>+ </div>+ </div>+ </Show>++ <Show when={validation()?.warnings?.length}>+ <div class="flex items-start gap-2 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800">+ <AlertCircle class="w-4 h-4 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" />+ <div class="space-y-1">+ <p class="text-sm font-medium text-amber-700 dark:text-amber-300">+ Review before saving (some may be ignored).+ </p>+ <ul class="text-xs text-amber-700 dark:text-amber-300 space-y-1">+ <For each={validation()?.warnings || []}>+ {(issue) => (+ <li class="flex items-start gap-2">+ <span class="font-mono text-amber-700 dark:text-amber-200">{issue.key}</span>+ <span>{issue.message}</span>+ </li>+ )}+ </For>+ </ul>+ </div>+ </div>+ </Show>++ <Show when={riskHints().length > 0}>+ <div class="flex items-start gap-2 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800">+ <AlertCircle class="w-4 h-4 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" />+ <div class="space-y-1">+ <p class="text-sm font-medium text-amber-700 dark:text-amber-300">+ Review checklist+ </p>+ <ul class="text-xs text-amber-700 dark:text-amber-300 space-y-1">+ <For each={riskHints()}>+ {(hint) => <li>{hint}</li>}+ </For>+ </ul>+ </div>+ </div>+ </Show>+{/* Profile Preview */}<div class="rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">{/* Name & Description */}- <div class="p-4 bg-gray-50 dark:bg-gray-800/50 border-b border-gray-200 dark:border-gray-700">- <h4 class="font-medium text-gray-900 dark:text-gray-100">{sugg().name}</h4>- <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">{sugg().description}</p>+ <div class="p-4 bg-gray-50 dark:bg-gray-800/50 border-b border-gray-200 dark:border-gray-700 space-y-2">+ <div>+ <h4 class="font-medium text-gray-900 dark:text-gray-100">{sugg().name}</h4>+ <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">{sugg().description}</p>+ </div>+ <Show when={activeHistoryItem()}>+ <div class="text-xs text-gray-500 dark:text-gray-400 break-words">+ <span class="font-medium text-gray-600 dark:text-gray-300">Prompt:</span>{' '}+ {activeHistoryItem()?.prompt}+ </div>+ </Show></div>- {/* Config */}- <div class="p-4 space-y-3">- <h5 class="text-sm font-medium text-gray-700 dark:text-gray-300">Settings</h5>- <div class="bg-gray-900 dark:bg-gray-950 rounded-md p-3 overflow-x-auto">- <pre class="text-xs text-gray-300 font-mono">- {JSON.stringify(sugg().config, null, 2)}- </pre>+ {/* Settings Preview + JSON */}+ <div class="p-4 space-y-4">+ <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <div class="space-y-3">+ <h5 class="text-sm font-medium text-gray-700 dark:text-gray-300">Settings Preview</h5>+ <Show when={settingsPreview().length > 0} fallback={+ <p class="text-xs text-gray-500 dark:text-gray-400">No settings were suggested.</p>+ }>+ <div class="space-y-2">+ <For each={settingsPreview()}>+ {(setting) => (+ <div class="rounded-lg border border-gray-200 dark:border-gray-700 p-3">+ <div class="flex items-start justify-between gap-3">+ <div class="space-y-1">+ <div class="flex items-center gap-2 flex-wrap">+ <span class="text-sm font-medium text-gray-900 dark:text-gray-100">+ {setting.label}+ </span>+ <span class="text-[10px] font-mono text-gray-400 dark:text-gray-500">+ {setting.key}+ </span>+ <Show when={!setting.known}>+ <span class="text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300">+ Unknown (ignored)+ </span>+ </Show>+ </div>+ <p class="text-xs text-gray-500 dark:text-gray-400">{setting.description}</p>+ </div>+ <div class="text-right shrink-0">+ <span class={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${formatValueBadgeClass(setting.value)}`}>+ {formatDisplayValue(setting.value)}+ </span>+ <Show when={schema().length > 0}>+ <div class="text-[11px] text-gray-400 dark:text-gray-500 mt-1">+ Default{' '}+ {hasValue(setting.defaultValue)+ ? formatDisplayValue(setting.defaultValue)+ : 'n/a'}+ </div>+ </Show>+ </div>+ </div>+ </div>+ )}+ </For>+ </div>+ </Show>++ <Show when={schema().length > 0}>+ <div class="rounded-lg border border-gray-200 dark:border-gray-700 p-3">+ <div class="flex items-start justify-between gap-3">+ <div>+ <h6 class="text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wide">+ Defaults unchanged+ </h6>+ <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">+ Only overrides are shown. {omittedDefaults().length} settings stay at defaults.+ </p>+ </div>+ <button+ type="button"+ onClick={() => setShowDefaults(!showDefaults())}+ class="text-xs font-medium text-purple-600 hover:text-purple-700 dark:text-purple-400 dark:hover:text-purple-300"+ >+ {showDefaults() ? 'Hide defaults' : 'Show defaults'}+ </button>+ </div>+ <Show when={showDefaults()}>+ <div class="mt-3 space-y-2">+ <Show when={omittedDefaults().length > 0} fallback={+ <p class="text-xs text-gray-500 dark:text-gray-400">No defaults to show.</p>+ }>+ <For each={omittedDefaults()}>+ {(def) => (+ <div class="flex items-center justify-between text-xs text-gray-600 dark:text-gray-400">+ <span class="font-mono">{def.key}</span>+ <span>{formatDisplayValue(def.defaultValue)}</span>+ </div>+ )}+ </For>+ </Show>+ </div>+ </Show>+ </div>+ </Show>+ </div>+ <div class="space-y-3">+ <h5 class="text-sm font-medium text-gray-700 dark:text-gray-300">Raw JSON</h5>+ <div class="bg-gray-900 dark:bg-gray-950 rounded-md p-3 overflow-x-auto">+ <pre class="text-xs text-gray-300 font-mono">+ {JSON.stringify(sugg().config, null, 2)}+ </pre>+ </div>+ </div></div></div>@@ -193,6 +539,41 @@ export const SuggestProfileModal: Component<SuggestProfileModalProps> = (props)</div></Show></div>++ <Show when={history().length > 1}>+ <div class="rounded-lg border border-gray-200 dark:border-gray-700 p-4 space-y-2">+ <div class="flex items-center justify-between">+ <h5 class="text-sm font-medium text-gray-700 dark:text-gray-300">Recent drafts</h5>+ <span class="text-xs text-gray-500 dark:text-gray-400">+ {history().length - 1} older+ </span>+ </div>+ <p class="text-xs text-gray-500 dark:text-gray-400">+ Switch to a previous suggestion.+ </p>+ <div class="space-y-2">+ <For each={history().filter(item => item.id !== activeHistoryId())}>+ {(item) => (+ <button+ type="button"+ onClick={() => handleSelectHistory(item)}+ class="w-full text-left rounded-md border border-gray-200 dark:border-gray-700 p-3 hover:border-purple-300 hover:bg-purple-50 dark:hover:border-purple-700/60 dark:hover:bg-purple-900/20 transition-colors"+ >+ <div class="flex items-center justify-between gap-3">+ <span class="text-sm font-medium text-gray-900 dark:text-gray-100">+ {item.suggestion.name}+ </span>+ <span class="text-xs text-gray-400 dark:text-gray-500">+ {formatRelativeTime(item.createdAt)}+ </span>+ </div>+ <p class="text-xs text-gray-500 dark:text-gray-400 mt-1 truncate">{item.prompt}</p>+ </button>+ )}+ </For>+ </div>+ </div>+ </Show></div>)}</Show>@@ -223,18 +604,19 @@ export const SuggestProfileModal: Component<SuggestProfileModalProps> = (props)><buttontype="button"- onClick={() => {- setSuggestion(null);- setError(null);- }}- class="rounded-lg px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"+ onClick={handleSubmit}+ disabled={loading() || !prompt().trim()}+ class="inline-flex items-center gap-2 rounded-lg bg-purple-100 px-4 py-2 text-sm font-medium text-purple-700 transition-colors hover:bg-purple-200 dark:bg-purple-900/40 dark:text-purple-200 dark:hover:bg-purple-900/60 disabled:cursor-not-allowed disabled:opacity-60"+ title="Regenerate using the current prompt">- Try Again+ <Sparkles class="w-4 h-4" />+ {loading() ? 'Generating...' : 'Regenerate draft'}</button><buttontype="button"onClick={handleAccept}- class="inline-flex items-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-green-700"+ disabled={loading()}+ class="inline-flex items-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-green-700 disabled:cursor-not-allowed disabled:opacity-60"><Check class="w-4 h-4" />Use This Profilediff --git a/frontend-modern/src/components/Settings/UnifiedAgents.tsx b/frontend-modern/src/components/Settings/UnifiedAgents.tsxindex 1b1f53f280..ad3aa36e94 100644--- a/frontend-modern/src/components/Settings/UnifiedAgents.tsx+++ b/frontend-modern/src/components/Settings/UnifiedAgents.tsx@@ -9,7 +9,7 @@ import { notificationStore } from '@/stores/notifications';import type { SecurityStatus } from '@/types/config';import type { HostLookupResponse } from '@/types/api';import type { APITokenRecord } from '@/api/security';-import { HOST_AGENT_SCOPE, DOCKER_REPORT_SCOPE, KUBERNETES_REPORT_SCOPE } from '@/constants/apiScopes';+import { HOST_AGENT_SCOPE, HOST_AGENT_CONFIG_READ_SCOPE, DOCKER_REPORT_SCOPE, KUBERNETES_REPORT_SCOPE } from '@/constants/apiScopes';import { copyToClipboard } from '@/utils/clipboard';import { getPulseBaseUrl } from '@/utils/url';import { logger } from '@/utils/logger';@@ -262,14 +262,14 @@ export const UnifiedAgents: Component = () => {try {const desiredName = tokenName().trim() || buildDefaultTokenName();// Generate token with unified agent reporting scopes- const scopes = [HOST_AGENT_SCOPE, DOCKER_REPORT_SCOPE, KUBERNETES_REPORT_SCOPE];+ const scopes = [HOST_AGENT_SCOPE, HOST_AGENT_CONFIG_READ_SCOPE, DOCKER_REPORT_SCOPE, KUBERNETES_REPORT_SCOPE];const { token, record } = await SecurityAPI.createToken(desiredName, scopes);setCurrentToken(token);setLatestRecord(record);setTokenName('');setConfirmedNoToken(false);- notificationStore.success('Token generated with Host, Docker, and Kubernetes permissions.', 4000);+ notificationStore.success('Token generated with Host config + reporting, Docker, and Kubernetes permissions.', 4000);} catch (err) {logger.error('Failed to generate agent token', err);notificationStore.error('Failed to generate agent token. Confirm you are signed in as an administrator.', 6000);@@ -938,7 +938,7 @@ export const UnifiedAgents: Component = () => {</div><Show when={insecureMode()}><div class="rounded-lg border border-amber-200 bg-amber-50 px-4 py-2 text-sm text-amber-800 dark:border-amber-700 dark:bg-amber-900/20 dark:text-amber-200">- <span class="font-medium">TLS verification disabled</span> — commands will skip certificate checks (for self-signed certs).+ <span class="font-medium">TLS verification disabled</span> — skip cert checks for self-signed setups. Not recommended for production.</div></Show><label class="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer" title="Skip TLS certificate verification (for self-signed certificates)">@@ -948,7 +948,7 @@ export const UnifiedAgents: Component = () => {onChange={(e) => setInsecureMode(e.currentTarget.checked)}class="rounded border-gray-300 text-blue-600 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700"/>- Skip TLS certificate verification (self-signed certs)+ Skip TLS certificate verification (self-signed certs; not recommended)</label><label class="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer" title="Allow AI Patrol to execute diagnostic and fix commands on this agent (requires Pulse Pro)"><input@@ -964,6 +964,9 @@ export const UnifiedAgents: Component = () => {<span class="font-medium">AI commands enabled</span> — The agent will accept diagnostic and fix commands from Pulse AI features.</div></Show>+ <div class="rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-2 text-sm text-emerald-900 dark:border-emerald-700 dark:bg-emerald-900/20 dark:text-emerald-100">+ <span class="font-medium">Config signing (optional)</span> — Require signed remote config payloads with <code>PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED=true</code>. Provide keys via <code>PULSE_AGENT_CONFIG_SIGNING_KEY</code> (Pulse) and <code>PULSE_AGENT_CONFIG_PUBLIC_KEYS</code> (agents).+ </div></div><div class="space-y-4">diff --git a/frontend-modern/src/components/Settings/__tests__/SuggestProfileModal.test.tsx b/frontend-modern/src/components/Settings/__tests__/SuggestProfileModal.test.tsxnew file mode 100644index 0000000000..01959854ec--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/SuggestProfileModal.test.tsx@@ -0,0 +1,167 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';+import { SuggestProfileModal } from '../SuggestProfileModal';++const suggestProfileMock = vi.fn();+const getConfigSchemaMock = vi.fn();+const validateConfigMock = vi.fn();+const notificationSuccessMock = vi.fn();+const notificationErrorMock = vi.fn();+const loggerErrorMock = vi.fn();++vi.mock('@/api/agentProfiles', () => ({+ AgentProfilesAPI: {+ suggestProfile: (...args: unknown[]) => suggestProfileMock(...args),+ getConfigSchema: (...args: unknown[]) => getConfigSchemaMock(...args),+ validateConfig: (...args: unknown[]) => validateConfigMock(...args),+ },+}));++vi.mock('@/stores/notifications', () => ({+ notificationStore: {+ success: (...args: unknown[]) => notificationSuccessMock(...args),+ error: (...args: unknown[]) => notificationErrorMock(...args),+ },+}));++vi.mock('@/utils/logger', () => ({+ logger: {+ error: (...args: unknown[]) => loggerErrorMock(...args),+ },+}));++const renderModal = (props?: Partial<Parameters<typeof SuggestProfileModal>[0]>) => {+ const onClose = vi.fn();+ const onSuggestionAccepted = vi.fn();+ render(() => (+ <SuggestProfileModal+ onClose={props?.onClose ?? onClose}+ onSuggestionAccepted={props?.onSuggestionAccepted ?? onSuggestionAccepted}+ />+ ));+ return { onClose, onSuggestionAccepted };+};++beforeEach(() => {+ suggestProfileMock.mockReset();+ getConfigSchemaMock.mockReset();+ validateConfigMock.mockReset();+ notificationSuccessMock.mockReset();+ notificationErrorMock.mockReset();+ loggerErrorMock.mockReset();++ getConfigSchemaMock.mockResolvedValue([+ {+ key: 'enable_docker',+ type: 'bool',+ description: 'Enable Docker container monitoring',+ defaultValue: true,+ required: false,+ },+ {+ key: 'interval',+ type: 'duration',+ description: 'Polling interval for metrics collection',+ defaultValue: '30s',+ required: false,+ },+ {+ key: 'log_level',+ type: 'enum',+ description: 'Agent log verbosity level',+ defaultValue: 'info',+ required: false,+ },+ ]);+});++afterEach(() => {+ cleanup();+});++describe('SuggestProfileModal', () => {+ it('renders preview details, defaults, and validation hints', async () => {+ suggestProfileMock.mockResolvedValue({+ name: 'Production Servers',+ description: 'Tighter logging for prod hosts',+ config: {+ enable_docker: false,+ interval: '1m',+ mystery_key: 'value',+ },+ rationale: ['Reduce noise', 'Keep Docker off'],+ });++ validateConfigMock.mockResolvedValue({+ valid: false,+ errors: [{ key: 'interval', message: 'Expected duration string' }],+ warnings: [{ key: 'mystery_key', message: 'Unknown configuration key' }],+ });++ renderModal();++ fireEvent.input(+ screen.getByPlaceholderText('Describe the agents and use case for this profile...'),+ {+ target: { value: 'Production profile with minimal logging' },+ },+ );+ fireEvent.click(screen.getByRole('button', { name: /suggest profile/i }));++ expect(await screen.findByText('Production Servers')).toBeInTheDocument();+ expect(screen.getByText('Settings Preview')).toBeInTheDocument();+ expect(screen.getByText('Enable Docker Monitoring')).toBeInTheDocument();+ expect(screen.getByText('Reporting Interval')).toBeInTheDocument();+ expect(screen.getByText('Unknown (ignored)')).toBeInTheDocument();++ expect(screen.getByText(/Fix these before saving/i)).toBeInTheDocument();+ expect(screen.getByText(/Review before saving/i)).toBeInTheDocument();+ expect(screen.getByText(/Review checklist/i)).toBeInTheDocument();+ expect(screen.getByText(/Docker monitoring is disabled/i)).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: /show defaults/i }));+ expect(await screen.findByText('log_level')).toBeInTheDocument();+ });++ it('supports regenerating and accepting a later draft', async () => {+ const firstSuggestion = {+ name: 'Production Profile',+ description: 'For prod workloads',+ config: { enable_docker: true },+ rationale: [],+ };+ const secondSuggestion = {+ name: 'Development Profile',+ description: 'For dev workloads',+ config: { log_level: 'debug' },+ rationale: [],+ };++ suggestProfileMock+ .mockResolvedValueOnce(firstSuggestion)+ .mockResolvedValueOnce(secondSuggestion);+ validateConfigMock.mockResolvedValue({ valid: true, errors: [], warnings: [] });++ const { onSuggestionAccepted } = renderModal();++ const promptInput = screen.getByPlaceholderText('Describe the agents and use case for this profile...');+ fireEvent.input(promptInput, { target: { value: 'Production profile' } });+ fireEvent.click(screen.getByRole('button', { name: /suggest profile/i }));++ expect(await screen.findByText('Production Profile')).toBeInTheDocument();++ fireEvent.input(promptInput, { target: { value: 'Development profile' } });+ fireEvent.click(screen.getByRole('button', { name: /regenerate/i }));++ expect(await screen.findByText('Development Profile')).toBeInTheDocument();+ expect(screen.getByText('Recent drafts')).toBeInTheDocument();++ expect(screen.getByText('Production Profile')).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: /use this profile/i }));++ await waitFor(() => {+ expect(onSuggestionAccepted).toHaveBeenCalledWith(secondSuggestion);+ });+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/UnifiedAgents.test.tsx b/frontend-modern/src/components/Settings/__tests__/UnifiedAgents.test.tsxindex 74fc3a72cd..ccb1b27855 100644--- a/frontend-modern/src/components/Settings/__tests__/UnifiedAgents.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/UnifiedAgents.test.tsx@@ -225,7 +225,7 @@ describe('UnifiedAgents token generation', () => {{ interval: 0 },);expect(notificationSuccessMock).toHaveBeenCalledWith(- 'Token generated with Host, Docker, and Kubernetes permissions.',+ 'Token generated with Host config + reporting, Docker, and Kubernetes permissions.',4000,);});diff --git a/frontend-modern/src/components/Settings/agentProfileSettings.ts b/frontend-modern/src/components/Settings/agentProfileSettings.tsnew file mode 100644index 0000000000..0f0fd825e0--- /dev/null+++ b/frontend-modern/src/components/Settings/agentProfileSettings.ts@@ -0,0 +1,55 @@+export interface BooleanSetting {+ key: string;+ type: 'boolean';+ label: string;+ description: string;+}++export interface SelectSetting {+ key: string;+ type: 'select';+ label: string;+ description: string;+ options: string[];+}++export interface DurationSetting {+ key: string;+ type: 'duration';+ label: string;+ description: string;+}++export interface StringSetting {+ key: string;+ type: 'string';+ label: string;+ description: string;+ placeholder?: string;+}++export type KnownSetting = BooleanSetting | SelectSetting | DurationSetting | StringSetting;++// Settings that the agent actually supports (from applyRemoteSettings in cmd/pulse-agent/main.go)+export const KNOWN_SETTINGS: KnownSetting[] = [+ // Core monitoring+ { key: 'enable_host', type: 'boolean', label: 'Enable Host Monitoring', description: 'Collect host metrics and allow command execution' },+ { key: 'enable_docker', type: 'boolean', label: 'Enable Docker Monitoring', description: 'Monitor Docker or Podman containers on this agent' },+ { key: 'docker_runtime', type: 'select', label: 'Docker Runtime', description: 'Force a specific container runtime', options: ['auto', 'docker', 'podman'] },+ { key: 'enable_kubernetes', type: 'boolean', label: 'Enable Kubernetes Monitoring', description: 'Monitor Kubernetes workloads' },+ { key: 'kube_include_all_pods', type: 'boolean', label: 'Include All Pods', description: 'Include all non-succeeded pods in reports' },+ { key: 'kube_include_all_deployments', type: 'boolean', label: 'Include All Deployments', description: 'Include all deployments, not just problem ones' },+ { key: 'enable_proxmox', type: 'boolean', label: 'Enable Proxmox Mode', description: 'Auto-detect and configure Proxmox API access' },+ { key: 'proxmox_type', type: 'select', label: 'Proxmox Type', description: 'Force PVE or PBS mode', options: ['auto', 'pve', 'pbs'] },+ { key: 'disable_ceph', type: 'boolean', label: 'Disable Ceph Monitoring', description: 'Skip local Ceph status polling' },+ // Timing+ { key: 'interval', type: 'duration', label: 'Reporting Interval', description: 'How often the agent reports metrics (e.g., 30s, 1m)' },+ // Network+ { key: 'report_ip', type: 'string', label: 'Report IP Override', description: 'Override the reported IP address', placeholder: '' },+ // Operations+ { key: 'disable_auto_update', type: 'boolean', label: 'Disable Auto Updates', description: 'Stop the unified agent from auto-updating' },+ { key: 'disable_docker_update_checks', type: 'boolean', label: 'Disable Docker Update Checks', description: 'Skip Docker image update detection (avoid registry rate limits)' },+ { key: 'log_level', type: 'select', label: 'Log Level', description: 'Agent logging verbosity', options: ['debug', 'info', 'warn', 'error'] },+];++export const KNOWN_SETTINGS_BY_KEY = new Map(KNOWN_SETTINGS.map(setting => [setting.key, setting]));diff --git a/frontend-modern/src/constants/apiScopes.ts b/frontend-modern/src/constants/apiScopes.tsindex f2e5daa64d..906c08fe21 100644--- a/frontend-modern/src/constants/apiScopes.ts+++ b/frontend-modern/src/constants/apiScopes.ts@@ -6,6 +6,7 @@ export interface APIScopeOption {}export const HOST_AGENT_SCOPE = 'host-agent:report';+export const HOST_AGENT_CONFIG_READ_SCOPE = 'host-agent:config:read';export const DOCKER_REPORT_SCOPE = 'docker:report';export const DOCKER_MANAGE_SCOPE = 'docker:manage';export const KUBERNETES_REPORT_SCOPE = 'kubernetes:report';@@ -58,6 +59,12 @@ export const API_SCOPE_OPTIONS: APIScopeOption[] = [description: 'Allow the host agent to send OS, CPU, and disk metrics.',group: 'Agents',},+ {+ value: HOST_AGENT_CONFIG_READ_SCOPE,+ label: 'Host agent config fetch',+ description: 'Allow the host agent to retrieve its assigned configuration profile.',+ group: 'Agents',+ },{value: SETTINGS_READ_SCOPE,label: 'Settings (read)',diff --git a/internal/ai/mcp/data_types.go b/internal/ai/mcp/data_types.gonew file mode 100644index 0000000000..d637a5ebca--- /dev/null+++ b/internal/ai/mcp/data_types.go@@ -0,0 +1,476 @@+package mcp++import "time"++// MetricPoint represents a single metric data point+type MetricPoint struct {+ Timestamp time.Time `json:"timestamp"`+ CPU float64 `json:"cpu"`+ Memory float64 `json:"memory"`+ Disk float64 `json:"disk,omitempty"`+}++// ResourceMetricsSummary summarizes metrics for a resource over a period+type ResourceMetricsSummary struct {+ ResourceID string `json:"resource_id"`+ ResourceName string `json:"resource_name"`+ ResourceType string `json:"resource_type"`+ AvgCPU float64 `json:"avg_cpu"`+ MaxCPU float64 `json:"max_cpu"`+ AvgMemory float64 `json:"avg_memory"`+ MaxMemory float64 `json:"max_memory"`+ AvgDisk float64 `json:"avg_disk,omitempty"`+ MaxDisk float64 `json:"max_disk,omitempty"`+ Trend string `json:"trend"` // "stable", "growing", "declining"+}++// MetricBaseline represents learned normal behavior for a metric+type MetricBaseline struct {+ Mean float64 `json:"mean"`+ StdDev float64 `json:"std_dev"`+ Min float64 `json:"min"`+ Max float64 `json:"max"`+}++// Pattern represents a detected operational pattern+type Pattern struct {+ ResourceID string `json:"resource_id"`+ ResourceName string `json:"resource_name"`+ PatternType string `json:"pattern_type"` // "recurring_spike", "gradual_growth", "weekly_cycle"+ Description string `json:"description"`+ Confidence float64 `json:"confidence"`+ LastSeen time.Time `json:"last_seen"`+}++// Prediction represents a predicted future issue+type Prediction struct {+ ResourceID string `json:"resource_id"`+ ResourceName string `json:"resource_name"`+ IssueType string `json:"issue_type"` // "disk_full", "memory_exhaustion", etc.+ PredictedTime time.Time `json:"predicted_time"`+ Confidence float64 `json:"confidence"`+ Recommendation string `json:"recommendation"`+}++// ActiveAlert represents an active alert+type ActiveAlert struct {+ ID string `json:"id"`+ ResourceID string `json:"resource_id"`+ ResourceName string `json:"resource_name"`+ Type string `json:"type"` // "cpu", "memory", "disk", "offline"+ Severity string `json:"severity"`+ Value float64 `json:"value"`+ Threshold float64 `json:"threshold"`+ StartTime time.Time `json:"start_time"`+ Message string `json:"message"`+}++// Finding represents a patrol finding+type Finding struct {+ ID string `json:"id"`+ Key string `json:"key"`+ Severity string `json:"severity"`+ Category string `json:"category"`+ ResourceID string `json:"resource_id"`+ ResourceName string `json:"resource_name"`+ ResourceType string `json:"resource_type"`+ Title string `json:"title"`+ Description string `json:"description"`+ Recommendation string `json:"recommendation"`+ Evidence string `json:"evidence"`+ DetectedAt time.Time `json:"detected_at"`+ LastSeenAt time.Time `json:"last_seen_at"`+ TimesRaised int `json:"times_raised"`+}++// GuestInfo represents resolved guest information+type GuestInfo struct {+ VMID int+ Name string+ Node string+ Type string // "vm" or "lxc"+ Status string+ Instance string+}++// ========== JSON Response Types ==========++// CapabilitiesResponse is returned by pulse_get_capabilities+type CapabilitiesResponse struct {+ ControlLevel string `json:"control_level"`+ Features FeatureFlags `json:"features"`+ ProtectedGuests []string `json:"protected_guests,omitempty"`+ ConnectedAgents int `json:"connected_agents"`+ Version string `json:"version"`+}++// FeatureFlags indicates which features are available+type FeatureFlags struct {+ MetricsHistory bool `json:"metrics_history"`+ Baselines bool `json:"baselines"`+ Patterns bool `json:"patterns"`+ Alerts bool `json:"alerts"`+ Findings bool `json:"findings"`+ Backups bool `json:"backups"`+ Storage bool `json:"storage"`+ DiskHealth bool `json:"disk_health"`+ AgentProfiles bool `json:"agent_profiles"`+ Control bool `json:"control"`+}++// InfrastructureResponse is returned by pulse_list_infrastructure+type InfrastructureResponse struct {+ Nodes []NodeSummary `json:"nodes,omitempty"`+ VMs []VMSummary `json:"vms,omitempty"`+ Containers []ContainerSummary `json:"containers,omitempty"`+ DockerHosts []DockerHostSummary `json:"docker_hosts,omitempty"`+ Total TotalCounts `json:"total"`+ Pagination *PaginationInfo `json:"pagination,omitempty"`+}++// NodeSummary is a summarized node for list responses+type NodeSummary struct {+ Name string `json:"name"`+ Status string `json:"status"`+ ID string `json:"id,omitempty"`+}++// VMSummary is a summarized VM for list responses+type VMSummary struct {+ VMID int `json:"vmid"`+ Name string `json:"name"`+ Status string `json:"status"`+ Node string `json:"node"`+ CPU float64 `json:"cpu_percent,omitempty"`+ Memory float64 `json:"memory_percent,omitempty"`+}++// ContainerSummary is a summarized LXC container for list responses+type ContainerSummary struct {+ VMID int `json:"vmid"`+ Name string `json:"name"`+ Status string `json:"status"`+ Node string `json:"node"`+ CPU float64 `json:"cpu_percent,omitempty"`+ Memory float64 `json:"memory_percent,omitempty"`+}++// DockerHostSummary is a summarized Docker host for list responses+type DockerHostSummary struct {+ ID string `json:"id"`+ Hostname string `json:"hostname"`+ DisplayName string `json:"display_name,omitempty"`+ ContainerCount int `json:"container_count"`+ Containers []DockerContainerSummary `json:"containers,omitempty"`+}++// DockerContainerSummary is a summarized Docker container+type DockerContainerSummary struct {+ ID string `json:"id"`+ Name string `json:"name"`+ State string `json:"state"`+ Image string `json:"image"`+ Health string `json:"health,omitempty"`+}++// TotalCounts for infrastructure response+type TotalCounts struct {+ Nodes int `json:"nodes"`+ VMs int `json:"vms"`+ Containers int `json:"containers"`+ DockerHosts int `json:"docker_hosts"`+}++// PaginationInfo describes pagination state+type PaginationInfo struct {+ Total int `json:"total"`+ Limit int `json:"limit"`+ Offset int `json:"offset"`+}++// ResourceResponse is returned by pulse_get_resource+type ResourceResponse struct {+ Type string `json:"type"` // "vm", "container", "docker"+ ID string `json:"id"`+ Name string `json:"name"`+ Status string `json:"status"`+ Node string `json:"node,omitempty"`+ Host string `json:"host,omitempty"`+ CPU ResourceCPU `json:"cpu"`+ Memory ResourceMemory `json:"memory"`+ Disk *ResourceDisk `json:"disk,omitempty"`+ OS string `json:"os,omitempty"`+ Tags []string `json:"tags,omitempty"`+ Networks []NetworkInfo `json:"networks,omitempty"`+ Ports []PortInfo `json:"ports,omitempty"`+ Mounts []MountInfo `json:"mounts,omitempty"`+ Labels map[string]string `json:"labels,omitempty"`+ LastBackup *time.Time `json:"last_backup,omitempty"`+ Image string `json:"image,omitempty"`+ Health string `json:"health,omitempty"`+ RestartCount int `json:"restart_count,omitempty"`+ UpdateAvailable bool `json:"update_available,omitempty"`+}++// ResourceCPU describes CPU usage+type ResourceCPU struct {+ Percent float64 `json:"percent"`+ Cores int `json:"cores"`+}++// ResourceMemory describes memory usage+type ResourceMemory struct {+ Percent float64 `json:"percent"`+ UsedGB float64 `json:"used_gb"`+ TotalGB float64 `json:"total_gb"`+}++// ResourceDisk describes disk usage+type ResourceDisk struct {+ Percent float64 `json:"percent"`+ UsedGB float64 `json:"used_gb"`+ TotalGB float64 `json:"total_gb"`+}++// NetworkInfo describes a network interface+type NetworkInfo struct {+ Name string `json:"name"`+ Addresses []string `json:"addresses"`+}++// PortInfo describes a port mapping+type PortInfo struct {+ Private int `json:"private"`+ Public int `json:"public,omitempty"`+ Protocol string `json:"protocol"`+ IP string `json:"ip,omitempty"`+}++// MountInfo describes a volume mount+type MountInfo struct {+ Source string `json:"source"`+ Destination string `json:"destination"`+ ReadWrite bool `json:"rw"`+}++// URLFetchResponse is returned by pulse_get_url_content+type URLFetchResponse struct {+ URL string `json:"url"`+ StatusCode int `json:"status_code"`+ Headers map[string]string `json:"headers"`+ Body string `json:"body"`+ Error string `json:"error,omitempty"`+}++// AlertsResponse is returned by pulse_list_alerts+type AlertsResponse struct {+ Alerts []ActiveAlert `json:"alerts"`+ Count int `json:"count"`+ Pagination *PaginationInfo `json:"pagination,omitempty"`+}++// FindingsResponse is returned by pulse_list_findings+type FindingsResponse struct {+ Active []Finding `json:"active"`+ Dismissed []Finding `json:"dismissed,omitempty"`+ Counts FindingCounts `json:"counts"`+ Pagination *PaginationInfo `json:"pagination,omitempty"`+}++// FindingCounts for findings response+type FindingCounts struct {+ Active int `json:"active"`+ Dismissed int `json:"dismissed"`+}++// MetricsResponse is returned by pulse_get_metrics+type MetricsResponse struct {+ ResourceID string `json:"resource_id,omitempty"`+ Period string `json:"period"`+ Points []MetricPoint `json:"points,omitempty"`+ Summary map[string]ResourceMetricsSummary `json:"summary,omitempty"`+}++// BaselinesResponse is returned by pulse_get_baselines+type BaselinesResponse struct {+ ResourceID string `json:"resource_id,omitempty"`+ Baselines map[string]map[string]*MetricBaseline `json:"baselines"` // resourceID -> metric -> baseline+}++// PatternsResponse is returned by pulse_get_patterns+type PatternsResponse struct {+ Patterns []Pattern `json:"patterns"`+ Predictions []Prediction `json:"predictions"`+}++// BackupsResponse is returned by pulse_list_backups+type BackupsResponse struct {+ PBS []PBSBackupSummary `json:"pbs,omitempty"`+ PVE []PVEBackupSummary `json:"pve,omitempty"`+ PBSServers []PBSServerSummary `json:"pbs_servers,omitempty"`+ RecentTasks []BackupTaskSummary `json:"recent_tasks,omitempty"`+ Pagination *PaginationInfo `json:"pagination,omitempty"`+}++// PBSBackupSummary is a summarized PBS backup+type PBSBackupSummary struct {+ VMID string `json:"vmid"`+ BackupType string `json:"backup_type"`+ BackupTime time.Time `json:"backup_time"`+ Instance string `json:"instance"`+ Datastore string `json:"datastore"`+ SizeGB float64 `json:"size_gb"`+ Verified bool `json:"verified"`+ Protected bool `json:"protected"`+}++// PVEBackupSummary is a summarized PVE backup+type PVEBackupSummary struct {+ VMID int `json:"vmid"`+ BackupTime time.Time `json:"backup_time"`+ SizeGB float64 `json:"size_gb"`+ Storage string `json:"storage"`+}++// PBSServerSummary is a summarized PBS server+type PBSServerSummary struct {+ Name string `json:"name"`+ Host string `json:"host"`+ Status string `json:"status"`+ Datastores []DatastoreSummary `json:"datastores"`+}++// DatastoreSummary is a summarized datastore+type DatastoreSummary struct {+ Name string `json:"name"`+ UsagePercent float64 `json:"usage_percent"`+ FreeGB float64 `json:"free_gb"`+}++// BackupTaskSummary is a summarized backup task+type BackupTaskSummary struct {+ VMID int `json:"vmid"`+ Node string `json:"node"`+ Status string `json:"status"`+ StartTime time.Time `json:"start_time"`+}++// StorageResponse is returned by pulse_list_storage+type StorageResponse struct {+ Pools []StoragePoolSummary `json:"pools,omitempty"`+ CephClusters []CephClusterSummary `json:"ceph_clusters,omitempty"`+ Pagination *PaginationInfo `json:"pagination,omitempty"`+}++// StoragePoolSummary is a summarized storage pool+type StoragePoolSummary struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Type string `json:"type"`+ Status string `json:"status"`+ UsagePercent float64 `json:"usage_percent"`+ UsedGB float64 `json:"used_gb"`+ TotalGB float64 `json:"total_gb"`+ FreeGB float64 `json:"free_gb"`+ Content string `json:"content"`+ Shared bool `json:"shared"`+ ZFS *ZFSPoolSummary `json:"zfs,omitempty"`+}++// ZFSPoolSummary is a summarized ZFS pool+type ZFSPoolSummary struct {+ Name string `json:"name"`+ State string `json:"state"`+ ReadErrors int64 `json:"read_errors"`+ WriteErrors int64 `json:"write_errors"`+ ChecksumErrors int64 `json:"checksum_errors"`+ Scan string `json:"scan,omitempty"`+}++// CephClusterSummary is a summarized Ceph cluster+type CephClusterSummary struct {+ Name string `json:"name"`+ Health string `json:"health"`+ HealthMessage string `json:"health_message,omitempty"`+ UsagePercent float64 `json:"usage_percent"`+ UsedTB float64 `json:"used_tb"`+ TotalTB float64 `json:"total_tb"`+ NumOSDs int `json:"num_osds"`+ NumOSDsUp int `json:"num_osds_up"`+ NumOSDsIn int `json:"num_osds_in"`+ NumMons int `json:"num_mons"`+ NumMgrs int `json:"num_mgrs"`+}++// DiskHealthResponse is returned by pulse_get_disk_health+type DiskHealthResponse struct {+ Hosts []HostDiskHealth `json:"hosts"`+}++// HostDiskHealth is disk health for a single host+type HostDiskHealth struct {+ Hostname string `json:"hostname"`+ SMART []SMARTDiskSummary `json:"smart,omitempty"`+ RAID []RAIDArraySummary `json:"raid,omitempty"`+ Ceph *CephStatusSummary `json:"ceph,omitempty"`+}++// SMARTDiskSummary is a summarized SMART disk+type SMARTDiskSummary struct {+ Device string `json:"device"`+ Model string `json:"model"`+ Health string `json:"health"`+ Temperature int `json:"temperature,omitempty"`+}++// RAIDArraySummary is a summarized RAID array+type RAIDArraySummary struct {+ Device string `json:"device"`+ Level string `json:"level"`+ State string `json:"state"`+ ActiveDevices int `json:"active_devices"`+ WorkingDevices int `json:"working_devices"`+ FailedDevices int `json:"failed_devices"`+ SpareDevices int `json:"spare_devices"`+ RebuildPercent float64 `json:"rebuild_percent,omitempty"`+}++// CephStatusSummary is a summarized Ceph status from agent+type CephStatusSummary struct {+ Health string `json:"health"`+ NumOSDs int `json:"num_osds"`+ NumOSDsUp int `json:"num_osds_up"`+ NumOSDsIn int `json:"num_osds_in"`+ NumPGs int `json:"num_pgs"`+ UsagePercent float64 `json:"usage_percent"`+}++// AgentScopeResponse is returned by pulse_get_agent_scope+type AgentScopeResponse struct {+ AgentID string `json:"agent_id"`+ AgentLabel string `json:"agent_label"`+ ProfileID string `json:"profile_id,omitempty"`+ ProfileName string `json:"profile_name,omitempty"`+ ProfileVersion int `json:"profile_version,omitempty"`+ Settings map[string]interface{} `json:"settings,omitempty"`+ ObservedModules []string `json:"observed_modules,omitempty"`+ CommandsEnabled *bool `json:"commands_enabled,omitempty"`+}++// CommandResponse is returned by control tools+type CommandResponse struct {+ Success bool `json:"success"`+ Output string `json:"output,omitempty"`+ ExitCode int `json:"exit_code,omitempty"`+ Error string `json:"error,omitempty"`+}++// ControlActionResponse is returned by pulse_control_guest and pulse_control_docker+type ControlActionResponse struct {+ Success bool `json:"success"`+ Action string `json:"action"`+ Target string `json:"target"`+ TargetType string `json:"target_type"` // "vm", "lxc", "docker"+ Output string `json:"output,omitempty"`+ Error string `json:"error,omitempty"`+}diff --git a/internal/ai/mcp/executor.go b/internal/ai/mcp/executor.gonew file mode 100644index 0000000000..3b21125390--- /dev/null+++ b/internal/ai/mcp/executor.go@@ -0,0 +1,298 @@+package mcp++import (+ "context"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rs/zerolog/log"+)++// StateProvider provides access to infrastructure state+type StateProvider interface {+ GetState() models.StateSnapshot+}++// CommandPolicy evaluates command security+type CommandPolicy interface {+ Evaluate(command string) agentexec.PolicyDecision+}++// AgentServer executes commands on agents+type AgentServer interface {+ GetConnectedAgents() []agentexec.ConnectedAgent+ ExecuteCommand(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error)+}++// MetadataUpdater updates resource metadata+type MetadataUpdater interface {+ SetResourceURL(resourceType, resourceID, url string) error+}++// FindingsManager manages patrol findings+type FindingsManager interface {+ ResolveFinding(findingID, note string) error+ DismissFinding(findingID, reason, note string) error+}++// MetricsHistoryProvider provides historical metrics for trend analysis+type MetricsHistoryProvider interface {+ GetResourceMetrics(resourceID string, period time.Duration) ([]MetricPoint, error)+ GetAllMetricsSummary(period time.Duration) (map[string]ResourceMetricsSummary, error)+}++// BaselineProvider provides learned baselines for anomaly detection+type BaselineProvider interface {+ GetBaseline(resourceID, metric string) *MetricBaseline+ GetAllBaselines() map[string]map[string]*MetricBaseline // resourceID -> metric -> baseline+}++// PatternProvider provides detected patterns and predictions+type PatternProvider interface {+ GetPatterns() []Pattern+ GetPredictions() []Prediction+}++// AlertProvider provides active alerts+type AlertProvider interface {+ GetActiveAlerts() []ActiveAlert+}++// FindingsProvider provides patrol findings+type FindingsProvider interface {+ GetActiveFindings() []Finding+ GetDismissedFindings() []Finding+}++// BackupProvider provides backup information+type BackupProvider interface {+ GetBackups() models.Backups+ GetPBSInstances() []models.PBSInstance+}++// StorageProvider provides storage information+type StorageProvider interface {+ GetStorage() []models.Storage+ GetCephClusters() []models.CephCluster+}++// DiskHealthProvider provides disk health information from host agents+type DiskHealthProvider interface {+ GetHosts() []models.Host+}++// ControlLevel represents the AI's permission level for infrastructure control+type ControlLevel string++const (+ // ControlLevelReadOnly - AI can only query, no control tools available+ ControlLevelReadOnly ControlLevel = "read_only"+ // ControlLevelSuggest - AI suggests commands, user must copy/paste to execute+ ControlLevelSuggest ControlLevel = "suggest"+ // ControlLevelControlled - AI can execute with per-command approval+ ControlLevelControlled ControlLevel = "controlled"+ // ControlLevelAutonomous - AI executes without approval (requires Pro license)+ ControlLevelAutonomous ControlLevel = "autonomous"+)++// ExecutorConfig holds all dependencies for the tool executor+type ExecutorConfig struct {+ // Required providers+ StateProvider StateProvider+ Policy CommandPolicy+ AgentServer AgentServer++ // Optional providers - patrol context+ MetricsHistory MetricsHistoryProvider+ BaselineProvider BaselineProvider+ PatternProvider PatternProvider+ AlertProvider AlertProvider+ FindingsProvider FindingsProvider++ // Optional providers - infrastructure+ BackupProvider BackupProvider+ StorageProvider StorageProvider+ DiskHealthProvider DiskHealthProvider++ // Optional providers - management+ MetadataUpdater MetadataUpdater+ FindingsManager FindingsManager+ AgentProfileManager AgentProfileManager++ // Control settings+ ControlLevel ControlLevel+ ProtectedGuests []string // VMIDs that AI cannot control+}++// PulseToolExecutor implements ToolExecutor for Pulse-specific tools+type PulseToolExecutor struct {+ // Core providers+ stateProvider StateProvider+ policy CommandPolicy+ agentServer AgentServer++ // Patrol context providers+ metricsHistory MetricsHistoryProvider+ baselineProvider BaselineProvider+ patternProvider PatternProvider+ alertProvider AlertProvider+ findingsProvider FindingsProvider++ // Infrastructure context providers+ backupProvider BackupProvider+ storageProvider StorageProvider+ diskHealthProvider DiskHealthProvider++ // Management providers+ metadataUpdater MetadataUpdater+ findingsManager FindingsManager+ agentProfileManager AgentProfileManager++ // Control settings+ controlLevel ControlLevel+ protectedGuests []string++ // Current execution context+ targetType string+ targetID string+ isAutonomous bool++ // Tool registry+ registry *ToolRegistry+}++// NewPulseToolExecutor creates a new Pulse tool executor with the given configuration+func NewPulseToolExecutor(cfg ExecutorConfig) *PulseToolExecutor {+ e := &PulseToolExecutor{+ stateProvider: cfg.StateProvider,+ policy: cfg.Policy,+ agentServer: cfg.AgentServer,+ metricsHistory: cfg.MetricsHistory,+ baselineProvider: cfg.BaselineProvider,+ patternProvider: cfg.PatternProvider,+ alertProvider: cfg.AlertProvider,+ findingsProvider: cfg.FindingsProvider,+ backupProvider: cfg.BackupProvider,+ storageProvider: cfg.StorageProvider,+ diskHealthProvider: cfg.DiskHealthProvider,+ metadataUpdater: cfg.MetadataUpdater,+ findingsManager: cfg.FindingsManager,+ agentProfileManager: cfg.AgentProfileManager,+ controlLevel: cfg.ControlLevel,+ protectedGuests: cfg.ProtectedGuests,+ registry: NewToolRegistry(),+ }++ // Register all tools+ e.registerTools()++ return e+}++// SetContext sets the current execution context+func (e *PulseToolExecutor) SetContext(targetType, targetID string, autonomous bool) {+ e.targetType = targetType+ e.targetID = targetID+ e.isAutonomous = autonomous+}++// SetControlLevel updates the control level+func (e *PulseToolExecutor) SetControlLevel(level ControlLevel) {+ e.controlLevel = level+}++// SetProtectedGuests updates the protected guests list+func (e *PulseToolExecutor) SetProtectedGuests(vmids []string) {+ e.protectedGuests = vmids+}++// Runtime setter methods for updating providers after creation++// SetMetadataUpdater sets the metadata updater+func (e *PulseToolExecutor) SetMetadataUpdater(updater MetadataUpdater) {+ e.metadataUpdater = updater+}++// SetFindingsManager sets the findings manager+func (e *PulseToolExecutor) SetFindingsManager(manager FindingsManager) {+ e.findingsManager = manager+}++// SetMetricsHistory sets the metrics history provider+func (e *PulseToolExecutor) SetMetricsHistory(provider MetricsHistoryProvider) {+ e.metricsHistory = provider+}++// SetBaselineProvider sets the baseline provider+func (e *PulseToolExecutor) SetBaselineProvider(provider BaselineProvider) {+ e.baselineProvider = provider+}++// SetPatternProvider sets the pattern provider+func (e *PulseToolExecutor) SetPatternProvider(provider PatternProvider) {+ e.patternProvider = provider+}++// SetAlertProvider sets the alert provider+func (e *PulseToolExecutor) SetAlertProvider(provider AlertProvider) {+ e.alertProvider = provider+}++// SetFindingsProvider sets the findings provider+func (e *PulseToolExecutor) SetFindingsProvider(provider FindingsProvider) {+ e.findingsProvider = provider+}++// SetBackupProvider sets the backup provider+func (e *PulseToolExecutor) SetBackupProvider(provider BackupProvider) {+ e.backupProvider = provider+}++// SetStorageProvider sets the storage provider+func (e *PulseToolExecutor) SetStorageProvider(provider StorageProvider) {+ e.storageProvider = provider+}++// SetDiskHealthProvider sets the disk health provider+func (e *PulseToolExecutor) SetDiskHealthProvider(provider DiskHealthProvider) {+ e.diskHealthProvider = provider+}++// SetAgentProfileManager sets the agent profile manager+func (e *PulseToolExecutor) SetAgentProfileManager(manager AgentProfileManager) {+ e.agentProfileManager = manager+}++// ListTools returns the list of available tools+func (e *PulseToolExecutor) ListTools() []Tool {+ return e.registry.ListTools(e.controlLevel)+}++// ExecuteTool executes a tool and returns the result+func (e *PulseToolExecutor) ExecuteTool(ctx context.Context, name string, args map[string]interface{}) (CallToolResult, error) {+ log.Debug().+ Str("tool", name).+ Interface("args", args).+ Msg("Executing Pulse tool")++ return e.registry.Execute(ctx, e, name, args)+}++// registerTools registers all available tools+func (e *PulseToolExecutor) registerTools() {+ // Query tools (always available)+ e.registerQueryTools()++ // Patrol context tools (always available)+ e.registerPatrolTools()++ // Infrastructure tools (always available)+ e.registerInfrastructureTools()++ // Profile tools - read operations always available+ e.registerProfileTools()++ // Control tools (conditional on control level)+ e.registerControlTools()+}diff --git a/internal/ai/mcp/executor_test.go b/internal/ai/mcp/executor_test.gonew file mode 100644index 0000000000..038d0d1352--- /dev/null+++ b/internal/ai/mcp/executor_test.go@@ -0,0 +1,548 @@+package mcp++import (+ "context"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++// Mock implementations for testing++type mockStateProvider struct {+ state models.StateSnapshot+}++func (m *mockStateProvider) GetState() models.StateSnapshot {+ return m.state+}++type mockCommandPolicy struct {+ decisions map[string]agentexec.PolicyDecision+}++func (m *mockCommandPolicy) Evaluate(command string) agentexec.PolicyDecision {+ if decision, ok := m.decisions[command]; ok {+ return decision+ }+ return agentexec.PolicyAllow+}++type mockAgentServer struct {+ agents []agentexec.ConnectedAgent+ execFunc func(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error)+}++func (m *mockAgentServer) GetConnectedAgents() []agentexec.ConnectedAgent {+ return m.agents+}++func (m *mockAgentServer) ExecuteCommand(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error) {+ if m.execFunc != nil {+ return m.execFunc(ctx, agentID, cmd)+ }+ return &agentexec.CommandResultPayload{+ Stdout: "mock output",+ ExitCode: 0,+ }, nil+}++type mockMetricsHistoryProvider struct {+ metrics map[string][]MetricPoint+ summary map[string]ResourceMetricsSummary+}++func (m *mockMetricsHistoryProvider) GetResourceMetrics(resourceID string, period time.Duration) ([]MetricPoint, error) {+ if metrics, ok := m.metrics[resourceID]; ok {+ return metrics, nil+ }+ return nil, nil+}++func (m *mockMetricsHistoryProvider) GetAllMetricsSummary(period time.Duration) (map[string]ResourceMetricsSummary, error) {+ return m.summary, nil+}++type mockAlertProvider struct {+ alerts []ActiveAlert+}++func (m *mockAlertProvider) GetActiveAlerts() []ActiveAlert {+ return m.alerts+}++type mockFindingsProvider struct {+ active []Finding+ dismissed []Finding+}++func (m *mockFindingsProvider) GetActiveFindings() []Finding {+ return m.active+}++func (m *mockFindingsProvider) GetDismissedFindings() []Finding {+ return m.dismissed+}++// Tests++func TestNewPulseToolExecutor(t *testing.T) {+ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{},+ ControlLevel: ControlLevelReadOnly,+ }++ executor := NewPulseToolExecutor(cfg)+ if executor == nil {+ t.Fatal("expected executor to be created")+ }++ if executor.controlLevel != ControlLevelReadOnly {+ t.Errorf("expected control level %s, got %s", ControlLevelReadOnly, executor.controlLevel)+ }+}++func TestListToolsReadOnlyMode(t *testing.T) {+ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{},+ ControlLevel: ControlLevelReadOnly,+ }++ executor := NewPulseToolExecutor(cfg)+ tools := executor.ListTools()++ // Should not include control tools in read-only mode+ for _, tool := range tools {+ if tool.Name == "pulse_run_command" ||+ tool.Name == "pulse_control_guest" ||+ tool.Name == "pulse_control_docker" {+ t.Errorf("control tool %s should not be available in read-only mode", tool.Name)+ }+ }+}++func TestListToolsControlledMode(t *testing.T) {+ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{},+ ControlLevel: ControlLevelControlled,+ }++ executor := NewPulseToolExecutor(cfg)+ tools := executor.ListTools()++ // Should include control tools+ controlToolsFound := make(map[string]bool)+ for _, tool := range tools {+ controlToolsFound[tool.Name] = true+ }++ if !controlToolsFound["pulse_run_command"] {+ t.Error("expected pulse_run_command in controlled mode")+ }+ if !controlToolsFound["pulse_control_guest"] {+ t.Error("expected pulse_control_guest in controlled mode")+ }+ if !controlToolsFound["pulse_control_docker"] {+ t.Error("expected pulse_control_docker in controlled mode")+ }+}++func TestExecuteToolUnknown(t *testing.T) {+ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{},+ }++ executor := NewPulseToolExecutor(cfg)+ result, err := executor.ExecuteTool(context.Background(), "unknown_tool", nil)++ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ if !result.IsError {+ t.Error("expected error result for unknown tool")+ }+}++func TestExecuteGetInfrastructureState(t *testing.T) {+ state := models.StateSnapshot{+ Nodes: []models.Node{+ {Name: "pve1", Status: "online"},+ },+ VMs: []models.VM{+ {Name: "test-vm", VMID: 100, Status: "running"},+ },+ Containers: []models.Container{+ {Name: "test-ct", VMID: 101, Status: "running"},+ },+ }++ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{state: state},+ }++ executor := NewPulseToolExecutor(cfg)+ result, err := executor.ExecuteTool(context.Background(), "pulse_get_infrastructure_state", nil)++ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result.IsError {+ t.Fatal("expected successful result")+ }+ if len(result.Content) == 0 {+ t.Fatal("expected content in result")+ }++ text := result.Content[0].Text+ if !contains(text, "pve1") {+ t.Error("expected node name in output")+ }+ if !contains(text, "test-vm") {+ t.Error("expected VM name in output")+ }+ if !contains(text, "test-ct") {+ t.Error("expected container name in output")+ }+}++func TestExecuteRunCommandReadOnly(t *testing.T) {+ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{},+ ControlLevel: ControlLevelReadOnly,+ }++ executor := NewPulseToolExecutor(cfg)+ result, err := executor.ExecuteTool(context.Background(), "pulse_run_command", map[string]interface{}{+ "command": "ls -la",+ })++ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }++ text := result.Content[0].Text+ if !contains(text, "Control tools are disabled") {+ t.Error("expected disabled message in read-only mode")+ }+}++func TestExecuteRunCommandSuggestMode(t *testing.T) {+ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{},+ ControlLevel: ControlLevelSuggest,+ }++ executor := NewPulseToolExecutor(cfg)+ result, err := executor.ExecuteTool(context.Background(), "pulse_run_command", map[string]interface{}{+ "command": "ls -la",+ })++ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }++ text := result.Content[0].Text+ if !contains(text, "Suggested command") {+ t.Error("expected suggestion in suggest mode")+ }+ if !contains(text, "ls -la") {+ t.Error("expected command in suggestion")+ }+}++func TestExecuteRunCommandControlled(t *testing.T) {+ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{},+ ControlLevel: ControlLevelControlled,+ }++ executor := NewPulseToolExecutor(cfg)+ result, err := executor.ExecuteTool(context.Background(), "pulse_run_command", map[string]interface{}{+ "command": "ls -la",+ })++ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }++ text := result.Content[0].Text+ if !contains(text, "APPROVAL_REQUIRED") {+ t.Error("expected approval required in controlled mode")+ }+}++func TestExecuteRunCommandPolicyBlocked(t *testing.T) {+ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{},+ Policy: &mockCommandPolicy{+ decisions: map[string]agentexec.PolicyDecision{+ "rm -rf /": agentexec.PolicyBlock,+ },+ },+ ControlLevel: ControlLevelAutonomous,+ }++ executor := NewPulseToolExecutor(cfg)+ result, err := executor.ExecuteTool(context.Background(), "pulse_run_command", map[string]interface{}{+ "command": "rm -rf /",+ })++ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }++ text := result.Content[0].Text+ if !contains(text, "POLICY_BLOCKED") {+ t.Error("expected policy blocked message")+ }+}++func TestExecuteGetActiveAlerts(t *testing.T) {+ alerts := []ActiveAlert{+ {+ ID: "alert-1",+ ResourceName: "test-vm",+ Type: "cpu",+ Severity: "warning",+ Value: 95.0,+ Threshold: 90.0,+ Message: "CPU high",+ },+ }++ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{},+ AlertProvider: &mockAlertProvider{alerts: alerts},+ }++ executor := NewPulseToolExecutor(cfg)+ result, err := executor.ExecuteTool(context.Background(), "pulse_get_active_alerts", nil)++ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result.IsError {+ t.Fatal("expected successful result")+ }++ text := result.Content[0].Text+ if !contains(text, "test-vm") {+ t.Error("expected resource name in output")+ }+ if !contains(text, "95.0%") {+ t.Error("expected value in output")+ }+}++func TestExecuteGetFindingsWithDismissed(t *testing.T) {+ active := []Finding{+ {ID: "finding-1", Title: "Active Issue", Severity: "warning"},+ }+ dismissed := []Finding{+ {ID: "finding-2", Title: "Dismissed Issue", Severity: "info"},+ }++ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{},+ FindingsProvider: &mockFindingsProvider{active: active, dismissed: dismissed},+ }++ executor := NewPulseToolExecutor(cfg)++ // Without dismissed+ result, _ := executor.ExecuteTool(context.Background(), "pulse_get_findings", map[string]interface{}{+ "include_dismissed": false,+ })+ text := result.Content[0].Text+ if !contains(text, "Active Issue") {+ t.Error("expected active finding")+ }+ if contains(text, "Dismissed Issue") {+ t.Error("should not include dismissed findings")+ }++ // With dismissed+ result, _ = executor.ExecuteTool(context.Background(), "pulse_get_findings", map[string]interface{}{+ "include_dismissed": true,+ })+ text = result.Content[0].Text+ if !contains(text, "Dismissed Issue") {+ t.Error("expected dismissed findings when included")+ }+}++func TestControlGuestProtectedGuest(t *testing.T) {+ state := models.StateSnapshot{+ VMs: []models.VM{+ {Name: "protected-vm", VMID: 100, Status: "running", Node: "pve1"},+ },+ }++ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{state: state},+ ControlLevel: ControlLevelAutonomous,+ ProtectedGuests: []string{"100"},+ }++ executor := NewPulseToolExecutor(cfg)+ result, err := executor.ExecuteTool(context.Background(), "pulse_control_guest", map[string]interface{}{+ "guest_id": "100",+ "action": "stop",+ })++ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }++ text := result.Content[0].Text+ if !contains(text, "protected") {+ t.Error("expected protected guest message")+ }+}++func TestSetControlLevelRuntime(t *testing.T) {+ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{},+ ControlLevel: ControlLevelReadOnly,+ }++ executor := NewPulseToolExecutor(cfg)++ // Initially read-only+ tools := executor.ListTools()+ for _, tool := range tools {+ if tool.Name == "pulse_run_command" {+ t.Error("pulse_run_command should not be available in read-only mode")+ }+ }++ // Update to controlled+ executor.SetControlLevel(ControlLevelControlled)+ tools = executor.ListTools()+ found := false+ for _, tool := range tools {+ if tool.Name == "pulse_run_command" {+ found = true+ break+ }+ }+ if !found {+ t.Error("pulse_run_command should be available after setting controlled mode")+ }+}++func TestExecuteGetAgentScope(t *testing.T) {+ state := models.StateSnapshot{+ Hosts: []models.Host{+ {ID: "agent-123", Hostname: "testhost", DisplayName: "Test Host", CommandsEnabled: true},+ },+ }++ cfg := ExecutorConfig{+ StateProvider: &mockStateProvider{state: state},+ }++ executor := NewPulseToolExecutor(cfg)+ result, err := executor.ExecuteTool(context.Background(), "pulse_get_agent_scope", map[string]interface{}{+ "hostname": "testhost",+ })++ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }++ text := result.Content[0].Text+ if !contains(text, "Test Host") || !contains(text, "agent-123") {+ t.Error("expected agent info in output")+ }+}++func TestToolRegistryOrder(t *testing.T) {+ registry := NewToolRegistry()++ registry.Register(RegisteredTool{+ Definition: Tool{Name: "tool_a"},+ Handler: func(ctx context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return CallToolResult{}, nil+ },+ })+ registry.Register(RegisteredTool{+ Definition: Tool{Name: "tool_b"},+ Handler: func(ctx context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return CallToolResult{}, nil+ },+ })+ registry.Register(RegisteredTool{+ Definition: Tool{Name: "tool_c"},+ Handler: func(ctx context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return CallToolResult{}, nil+ },+ })++ tools := registry.ListTools(ControlLevelAutonomous)++ if len(tools) != 3 {+ t.Fatalf("expected 3 tools, got %d", len(tools))+ }++ // Should preserve registration order+ if tools[0].Name != "tool_a" {+ t.Errorf("expected tool_a first, got %s", tools[0].Name)+ }+ if tools[1].Name != "tool_b" {+ t.Errorf("expected tool_b second, got %s", tools[1].Name)+ }+ if tools[2].Name != "tool_c" {+ t.Errorf("expected tool_c third, got %s", tools[2].Name)+ }+}++func TestToolRegistryControlFiltering(t *testing.T) {+ registry := NewToolRegistry()++ registry.Register(RegisteredTool{+ Definition: Tool{Name: "read_tool"},+ Handler: func(ctx context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return CallToolResult{}, nil+ },+ RequireControl: false,+ })+ registry.Register(RegisteredTool{+ Definition: Tool{Name: "control_tool"},+ Handler: func(ctx context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return CallToolResult{}, nil+ },+ RequireControl: true,+ })++ // Read-only should not include control tool+ tools := registry.ListTools(ControlLevelReadOnly)+ if len(tools) != 1 {+ t.Fatalf("expected 1 tool in read-only mode, got %d", len(tools))+ }+ if tools[0].Name != "read_tool" {+ t.Errorf("expected read_tool, got %s", tools[0].Name)+ }++ // Controlled should include both+ tools = registry.ListTools(ControlLevelControlled)+ if len(tools) != 2 {+ t.Fatalf("expected 2 tools in controlled mode, got %d", len(tools))+ }+}++// Helper function+func contains(s, substr string) bool {+ return len(s) >= len(substr) && (s == substr || len(s) > 0 && containsHelper(s, substr))+}++func containsHelper(s, substr string) bool {+ for i := 0; i <= len(s)-len(substr); i++ {+ if s[i:i+len(substr)] == substr {+ return true+ }+ }+ return false+}diff --git a/internal/ai/mcp/protocol.go b/internal/ai/mcp/protocol.goindex bcfc7c43ff..0ebc2793af 100644--- a/internal/ai/mcp/protocol.go+++ b/internal/ai/mcp/protocol.go@@ -231,3 +231,16 @@ func NewTextResult(text string) CallToolResult {IsError: false,}}++// NewJSONResult creates a successful JSON tool result+// The data is marshaled to JSON and returned as text content+func NewJSONResult(data interface{}) CallToolResult {+ b, err := json.Marshal(data)+ if err != nil {+ return NewErrorResult(err)+ }+ return CallToolResult{+ Content: []Content{NewTextContent(string(b))},+ IsError: false,+ }+}diff --git a/internal/ai/mcp/registry.go b/internal/ai/mcp/registry.gonew file mode 100644index 0000000000..e714c6041f--- /dev/null+++ b/internal/ai/mcp/registry.go@@ -0,0 +1,81 @@+package mcp++import (+ "context"+ "fmt"+ "sync"+)++// ToolHandler is a function that handles tool execution+type ToolHandler func(ctx context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error)++// RegisteredTool combines a tool definition with its handler+type RegisteredTool struct {+ Definition Tool+ Handler ToolHandler+ RequireControl bool // If true, only available when control level is not read_only+}++// ToolRegistry manages tool registration and execution+type ToolRegistry struct {+ mu sync.RWMutex+ tools map[string]RegisteredTool+ order []string // Preserve registration order+}++// NewToolRegistry creates a new tool registry+func NewToolRegistry() *ToolRegistry {+ return &ToolRegistry{+ tools: make(map[string]RegisteredTool),+ order: make([]string, 0),+ }+}++// Register adds a tool to the registry+func (r *ToolRegistry) Register(tool RegisteredTool) {+ r.mu.Lock()+ defer r.mu.Unlock()++ name := tool.Definition.Name+ if _, exists := r.tools[name]; !exists {+ r.order = append(r.order, name)+ }+ r.tools[name] = tool+}++// ListTools returns all tools available for the given control level+func (r *ToolRegistry) ListTools(controlLevel ControlLevel) []Tool {+ r.mu.RLock()+ defer r.mu.RUnlock()++ result := make([]Tool, 0, len(r.tools))+ for _, name := range r.order {+ tool := r.tools[name]+ // Skip control tools if in read-only mode+ if tool.RequireControl && (controlLevel == ControlLevelReadOnly || controlLevel == "") {+ continue+ }+ result = append(result, tool.Definition)+ }+ return result+}++// Execute runs a tool by name+func (r *ToolRegistry) Execute(ctx context.Context, e *PulseToolExecutor, name string, args map[string]interface{}) (CallToolResult, error) {+ r.mu.RLock()+ tool, exists := r.tools[name]+ r.mu.RUnlock()++ if !exists {+ return NewErrorResult(fmt.Errorf("unknown tool: %s", name)), nil+ }++ // Centralized control level check+ if tool.RequireControl {+ if e.controlLevel == ControlLevelReadOnly || e.controlLevel == "" {+ return NewTextResult("Control tools are disabled. Enable them in Settings > AI > Control Level."), nil+ }+ }++ return tool.Handler(ctx, e, args)+}diff --git a/internal/ai/mcp/server.go b/internal/ai/mcp/server.goindex b240037cbf..3e2f623435 100644--- a/internal/ai/mcp/server.go+++ b/internal/ai/mcp/server.go@@ -115,20 +115,17 @@ func (s *Server) handleMethod(ctx context.Context, req Request) (interface{}, *Ecase "initialize":return s.handleInitialize(req.Params)case "initialized":- // Client notification that initialization is completereturn nil, nilcase "tools/list":return s.handleListTools()case "tools/call":return s.handleCallTool(ctx, req.Params)case "resources/list":- return s.handleListResources()- case "resources/read":- return s.handleReadResource(ctx, req.Params)+ // Return empty list - resources not implemented+ return &ListResourcesResult{Resources: []Resource{}}, nilcase "prompts/list":- return s.handleListPrompts()- case "prompts/get":- return s.handleGetPrompt(req.Params)+ // Return empty list - prompts not implemented+ return &ListPromptsResult{Prompts: []Prompt{}}, nilcase "ping":return map[string]interface{}{}, nildefault:@@ -162,10 +159,7 @@ func (s *Server) handleInitialize(params json.RawMessage) (*InitializeResult, *ETools: &ToolsCapability{ListChanged: false,},- Resources: &ResourcesCapability{- Subscribe: false,- ListChanged: false,- },+ // Resources and Prompts not advertised - not implemented},ServerInfo: ServerInfo{Name: ServerName,@@ -224,106 +218,6 @@ func (s *Server) handleCallTool(ctx context.Context, params json.RawMessage) (*Creturn &result, nil}-func (s *Server) handleListResources() (*ListResourcesResult, *Error) {- // Pulse exposes infrastructure state as a resource- return &ListResourcesResult{- Resources: []Resource{- {- URI: "pulse://infrastructure/state",- Name: "Infrastructure State",- Description: "Current state of all monitored infrastructure",- MimeType: "application/json",- },- {- URI: "pulse://infrastructure/alerts",- Name: "Active Alerts",- Description: "Currently active alerts",- MimeType: "application/json",- },- },- }, nil-}--func (s *Server) handleReadResource(ctx context.Context, params json.RawMessage) (*ReadResourceResult, *Error) {- var readParams ReadResourceParams- if err := json.Unmarshal(params, &readParams); err != nil {- return nil, &Error{- Code: ErrInvalidParams,- Message: "Failed to parse resource read params",- }- }-- // TODO: Implement resource reading via executor- // For now, return empty result- return &ReadResourceResult{- Contents: []ResourceContent{- {- URI: readParams.URI,- MimeType: "application/json",- Text: "{}",- },- },- }, nil-}--func (s *Server) handleListPrompts() (*ListPromptsResult, *Error) {- // Pulse provides some built-in prompts- return &ListPromptsResult{- Prompts: []Prompt{- {- Name: "analyze_infrastructure",- Description: "Analyze the current infrastructure state and identify issues",- },- {- Name: "investigate_alert",- Description: "Investigate a specific alert",- Arguments: []PromptArgument{- {Name: "alert_id", Description: "The alert ID to investigate", Required: true},- },- },- },- }, nil-}--func (s *Server) handleGetPrompt(params json.RawMessage) (*GetPromptResult, *Error) {- var getParams GetPromptParams- if err := json.Unmarshal(params, &getParams); err != nil {- return nil, &Error{- Code: ErrInvalidParams,- Message: "Failed to parse prompt get params",- }- }-- switch getParams.Name {- case "analyze_infrastructure":- return &GetPromptResult{- Description: "Analyze current infrastructure",- Messages: []PromptMessage{- {- Role: "user",- Content: NewTextContent("Analyze the current infrastructure state. Look for any issues, capacity concerns, or optimization opportunities."),- },- },- }, nil- case "investigate_alert":- alertID := getParams.Arguments["alert_id"]- return &GetPromptResult{- Description: fmt.Sprintf("Investigate alert %s", alertID),- Messages: []PromptMessage{- {- Role: "user",- Content: NewTextContent(fmt.Sprintf("Investigate alert %s. Identify the root cause and suggest remediation steps.", alertID)),- },- },- }, nil- default:- return nil, &Error{- Code: ErrInvalidParams,- Message: fmt.Sprintf("Unknown prompt: %s", getParams.Name),- }- }-}-func (s *Server) writeResult(w http.ResponseWriter, id interface{}, result interface{}) {resultJSON, err := json.Marshal(result)if err != nil {diff --git a/internal/ai/mcp/tools.go b/internal/ai/mcp/tools.godeleted file mode 100644index 7ab08cb9f7..0000000000--- a/internal/ai/mcp/tools.go+++ /dev/null@@ -1,2354 +0,0 @@-package mcp--import (- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "sort"- "strconv"- "strings"- "time"-- "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"- "github.com/rcourtman/pulse-go-rewrite/internal/models"- "github.com/rs/zerolog/log"-)--// StateProvider provides access to infrastructure state-type StateProvider interface {- GetState() models.StateSnapshot-}--// CommandPolicy evaluates command security-type CommandPolicy interface {- Evaluate(command string) agentexec.PolicyDecision-}--// AgentServer executes commands on agents-type AgentServer interface {- GetConnectedAgents() []agentexec.ConnectedAgent- ExecuteCommand(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error)-}--// MetadataUpdater updates resource metadata-type MetadataUpdater interface {- SetResourceURL(resourceType, resourceID, url string) error-}--// FindingsManager manages patrol findings-type FindingsManager interface {- ResolveFinding(findingID, note string) error- DismissFinding(findingID, reason, note string) error-}--// MetricsHistoryProvider provides historical metrics for trend analysis-type MetricsHistoryProvider interface {- GetResourceMetrics(resourceID string, period time.Duration) ([]MetricPoint, error)- GetAllMetricsSummary(period time.Duration) (map[string]ResourceMetricsSummary, error)-}--// MetricPoint represents a single metric data point-type MetricPoint struct {- Timestamp time.Time `json:"timestamp"`- CPU float64 `json:"cpu"`- Memory float64 `json:"memory"`- Disk float64 `json:"disk,omitempty"`-}--// ResourceMetricsSummary summarizes metrics for a resource over a period-type ResourceMetricsSummary struct {- ResourceID string `json:"resource_id"`- ResourceName string `json:"resource_name"`- ResourceType string `json:"resource_type"`- AvgCPU float64 `json:"avg_cpu"`- MaxCPU float64 `json:"max_cpu"`- AvgMemory float64 `json:"avg_memory"`- MaxMemory float64 `json:"max_memory"`- AvgDisk float64 `json:"avg_disk,omitempty"`- MaxDisk float64 `json:"max_disk,omitempty"`- Trend string `json:"trend"` // "stable", "growing", "declining"-}--// BaselineProvider provides learned baselines for anomaly detection-type BaselineProvider interface {- GetBaseline(resourceID, metric string) *MetricBaseline- GetAllBaselines() map[string]map[string]*MetricBaseline // resourceID -> metric -> baseline-}--// MetricBaseline represents learned normal behavior for a metric-type MetricBaseline struct {- Mean float64 `json:"mean"`- StdDev float64 `json:"std_dev"`- Min float64 `json:"min"`- Max float64 `json:"max"`-}--// PatternProvider provides detected patterns and predictions-type PatternProvider interface {- GetPatterns() []Pattern- GetPredictions() []Prediction-}--// Pattern represents a detected operational pattern-type Pattern struct {- ResourceID string `json:"resource_id"`- ResourceName string `json:"resource_name"`- PatternType string `json:"pattern_type"` // "recurring_spike", "gradual_growth", "weekly_cycle"- Description string `json:"description"`- Confidence float64 `json:"confidence"`- LastSeen time.Time `json:"last_seen"`-}--// Prediction represents a predicted future issue-type Prediction struct {- ResourceID string `json:"resource_id"`- ResourceName string `json:"resource_name"`- IssueType string `json:"issue_type"` // "disk_full", "memory_exhaustion", etc.- PredictedTime time.Time `json:"predicted_time"`- Confidence float64 `json:"confidence"`- Recommendation string `json:"recommendation"`-}--// AlertProvider provides active alerts-type AlertProvider interface {- GetActiveAlerts() []ActiveAlert-}--// ActiveAlert represents an active alert-type ActiveAlert struct {- ID string `json:"id"`- ResourceID string `json:"resource_id"`- ResourceName string `json:"resource_name"`- Type string `json:"type"` // "cpu", "memory", "disk", "offline"- Severity string `json:"severity"`- Value float64 `json:"value"`- Threshold float64 `json:"threshold"`- StartTime time.Time `json:"start_time"`- Message string `json:"message"`-}--// FindingsProvider provides patrol findings-type FindingsProvider interface {- GetActiveFindings() []Finding- GetDismissedFindings() []Finding-}--// Finding represents a patrol finding-type Finding struct {- ID string `json:"id"`- Key string `json:"key"`- Severity string `json:"severity"`- Category string `json:"category"`- ResourceID string `json:"resource_id"`- ResourceName string `json:"resource_name"`- ResourceType string `json:"resource_type"`- Title string `json:"title"`- Description string `json:"description"`- Recommendation string `json:"recommendation"`- Evidence string `json:"evidence"`- DetectedAt time.Time `json:"detected_at"`- LastSeenAt time.Time `json:"last_seen_at"`- TimesRaised int `json:"times_raised"`-}--// BackupProvider provides backup information-type BackupProvider interface {- GetBackups() models.Backups- GetPBSInstances() []models.PBSInstance-}--// StorageProvider provides storage information-type StorageProvider interface {- GetStorage() []models.Storage- GetCephClusters() []models.CephCluster-}--// DiskHealthProvider provides disk health information from host agents-type DiskHealthProvider interface {- GetHosts() []models.Host-}--// ControlLevel represents the AI's permission level for infrastructure control-type ControlLevel string--const (- // ControlLevelReadOnly - AI can only query, no control tools available- ControlLevelReadOnly ControlLevel = "read_only"- // ControlLevelSuggest - AI suggests commands, user must copy/paste to execute- ControlLevelSuggest ControlLevel = "suggest"- // ControlLevelControlled - AI can execute with per-command approval- ControlLevelControlled ControlLevel = "controlled"- // ControlLevelAutonomous - AI executes without approval (requires Pro license)- ControlLevelAutonomous ControlLevel = "autonomous"-)--// PulseToolExecutor implements ToolExecutor for Pulse-specific tools-type PulseToolExecutor struct {- stateProvider StateProvider- policy CommandPolicy- agentServer AgentServer- metadataUpdater MetadataUpdater- findingsManager FindingsManager-- // Patrol context providers- metricsHistory MetricsHistoryProvider- baselineProvider BaselineProvider- patternProvider PatternProvider- alertProvider AlertProvider- findingsProvider FindingsProvider-- // Infrastructure context providers- backupProvider BackupProvider- storageProvider StorageProvider- diskHealthProvider DiskHealthProvider-- agentProfileManager AgentProfileManager-- // Control settings- controlLevel ControlLevel- protectedGuests []string // VMIDs that AI cannot control-- // Current execution context- targetType string- targetID string- isAutonomous bool-}--// NewPulseToolExecutor creates a new Pulse tool executor-func NewPulseToolExecutor(- stateProvider StateProvider,- policy CommandPolicy,- agentServer AgentServer,-) *PulseToolExecutor {- return &PulseToolExecutor{- stateProvider: stateProvider,- policy: policy,- agentServer: agentServer,- }-}--// SetMetadataUpdater sets the metadata updater-func (e *PulseToolExecutor) SetMetadataUpdater(updater MetadataUpdater) {- e.metadataUpdater = updater-}--// SetFindingsManager sets the findings manager-func (e *PulseToolExecutor) SetFindingsManager(manager FindingsManager) {- e.findingsManager = manager-}--// SetMetricsHistory sets the metrics history provider-func (e *PulseToolExecutor) SetMetricsHistory(provider MetricsHistoryProvider) {- e.metricsHistory = provider-}--// SetBaselineProvider sets the baseline provider-func (e *PulseToolExecutor) SetBaselineProvider(provider BaselineProvider) {- e.baselineProvider = provider-}--// SetPatternProvider sets the pattern provider-func (e *PulseToolExecutor) SetPatternProvider(provider PatternProvider) {- e.patternProvider = provider-}--// SetAlertProvider sets the alert provider-func (e *PulseToolExecutor) SetAlertProvider(provider AlertProvider) {- e.alertProvider = provider-}--// SetFindingsProvider sets the findings provider-func (e *PulseToolExecutor) SetFindingsProvider(provider FindingsProvider) {- e.findingsProvider = provider-}--// SetBackupProvider sets the backup provider-func (e *PulseToolExecutor) SetBackupProvider(provider BackupProvider) {- e.backupProvider = provider-}--// SetStorageProvider sets the storage provider-func (e *PulseToolExecutor) SetStorageProvider(provider StorageProvider) {- e.storageProvider = provider-}--// SetDiskHealthProvider sets the disk health provider-func (e *PulseToolExecutor) SetDiskHealthProvider(provider DiskHealthProvider) {- e.diskHealthProvider = provider-}--// SetAgentProfileManager sets the manager for centralized agent profiles.-func (e *PulseToolExecutor) SetAgentProfileManager(manager AgentProfileManager) {- e.agentProfileManager = manager-}--// SetControlLevel sets the AI control permission level-func (e *PulseToolExecutor) SetControlLevel(level ControlLevel) {- e.controlLevel = level-}--// SetProtectedGuests sets the list of VMIDs that AI cannot control-func (e *PulseToolExecutor) SetProtectedGuests(vmids []string) {- e.protectedGuests = vmids-}--// SetContext sets the current execution context-func (e *PulseToolExecutor) SetContext(targetType, targetID string, autonomous bool) {- e.targetType = targetType- e.targetID = targetID- e.isAutonomous = autonomous-}--// ListTools returns the list of available tools-func (e *PulseToolExecutor) ListTools() []Tool {- tools := []Tool{- {- Name: "get_agent_scope",- Description: "Get the current unified agent scope (profile assignment and settings).",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "agent_id": {- Type: "string",- Description: "Unified agent ID (preferred if known)",- },- "hostname": {- Type: "string",- Description: "Hostname or display name to resolve the agent ID",- },- },- },- },- {- Name: "pulse_get_agent_scope",- Description: "Get the current unified agent scope (profile assignment and settings).",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "agent_id": {- Type: "string",- Description: "Unified agent ID (preferred if known)",- },- "hostname": {- Type: "string",- Description: "Hostname or display name to resolve the agent ID",- },- },- },- },- {- Name: "pulse_fetch_url",- Description: "Fetch content from a URL. Use to check if web services are responding or read API endpoints.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "url": {- Type: "string",- Description: "The URL to fetch",- },- },- Required: []string{"url"},- },- },- {- Name: "pulse_get_infrastructure_state",- Description: "Get the current state of all monitored infrastructure including VMs, containers, and hosts.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{},- },- },- {- Name: "pulse_set_resource_url",- Description: "Set the web URL for a resource in Pulse after discovering a web service.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "resource_type": {- Type: "string",- Description: "Type of resource: 'guest', 'docker', or 'host'",- Enum: []string{"guest", "docker", "host"},- },- "resource_id": {- Type: "string",- Description: "The resource ID from context",- },- "url": {- Type: "string",- Description: "The URL to set (empty to remove)",- },- },- Required: []string{"resource_type", "resource_id"},- },- },- {- Name: "pulse_resolve_finding",- Description: "Mark an AI patrol finding as resolved after fixing the issue.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "finding_id": {- Type: "string",- Description: "The finding ID to resolve",- },- "resolution_note": {- Type: "string",- Description: "Brief description of how the issue was resolved",- },- },- Required: []string{"finding_id", "resolution_note"},- },- },- {- Name: "pulse_dismiss_finding",- Description: "Dismiss an AI patrol finding as not an issue or expected behavior.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "finding_id": {- Type: "string",- Description: "The finding ID to dismiss",- },- "reason": {- Type: "string",- Description: "Why the finding is being dismissed",- Enum: []string{"not_an_issue", "expected_behavior", "will_fix_later"},- },- "note": {- Type: "string",- Description: "Explanation of why this is being dismissed",- },- },- Required: []string{"finding_id", "reason", "note"},- },- },- // Patrol context tools- {- Name: "pulse_get_metrics_history",- Description: "Get historical metrics (CPU, memory, disk) for resources over 24 hours or 7 days. Use this to understand trends and detect anomalies.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "period": {- Type: "string",- Description: "Time period: '24h' for last 24 hours, '7d' for last 7 days",- Enum: []string{"24h", "7d"},- },- "resource_id": {- Type: "string",- Description: "Optional: specific resource ID. If omitted, returns summary for all resources.",- },- },- Required: []string{"period"},- },- },- {- Name: "pulse_get_baselines",- Description: "Get learned baselines for resources. Baselines represent 'normal' behavior and help detect anomalies.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "resource_id": {- Type: "string",- Description: "Optional: specific resource ID. If omitted, returns all baselines.",- },- },- },- },- {- Name: "pulse_get_patterns",- Description: "Get detected operational patterns and predictions. Includes recurring spikes, growth trends, and predicted issues.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{},- },- },- {- Name: "pulse_get_active_alerts",- Description: "Get all currently active alerts. Use to understand current problems in the infrastructure.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{},- },- },- {- Name: "pulse_get_findings",- Description: "Get AI patrol findings. Active findings are current issues; dismissed findings show user feedback.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "include_dismissed": {- Type: "boolean",- Description: "If true, also include dismissed findings",- },- },- },- },- // Infrastructure context tools- {- Name: "pulse_get_backups",- Description: "Get backup status for VMs and containers. Shows last backup times, backup jobs, and identifies resources without recent backups.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "resource_id": {- Type: "string",- Description: "Optional: filter by specific VM or container ID",- },- },- },- },- {- Name: "pulse_get_storage",- Description: "Get storage pool information including usage, ZFS pool health, and Ceph cluster status.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "storage_id": {- Type: "string",- Description: "Optional: specific storage ID for detailed info",- },- },- },- },- {- Name: "pulse_get_resource_details",- Description: "Get detailed information about a specific VM, container, or Docker container including IPs, ports, labels, mounts, and network configuration.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "resource_type": {- Type: "string",- Description: "Type of resource: 'vm', 'container', 'docker'",- Enum: []string{"vm", "container", "docker"},- },- "resource_id": {- Type: "string",- Description: "The resource ID or name to look up",- },- },- Required: []string{"resource_type", "resource_id"},- },- },- {- Name: "pulse_get_disk_health",- Description: "Get disk health information including SMART data, RAID array status, and Ceph cluster health from host agents.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{},- },- },- }-- // Add control tools if not in read_only mode- if e.controlLevel != ControlLevelReadOnly && e.controlLevel != "" {- controlTools := []Tool{- {- Name: "pulse_run_command",- Description: "Execute a shell command on Pulse-managed infrastructure. By default runs on the current target, set run_on_host=true for host commands.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "command": {- Type: "string",- Description: "The shell command to execute",- },- "run_on_host": {- Type: "boolean",- Description: "If true, run on the host instead of inside the container/VM",- },- "target_host": {- Type: "string",- Description: "Optional hostname of the specific host/node to run the command on",- },- },- Required: []string{"command"},- },- },- {- Name: "pulse_control_guest",- Description: "Control Proxmox VMs and LXC containers. Actions: start, stop, shutdown (graceful), restart. Requires an agent on the Proxmox host.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "guest_id": {- Type: "string",- Description: "The VMID (e.g., '101') or name of the VM/container to control",- },- "action": {- Type: "string",- Description: "Action to perform: start, stop, shutdown, restart",- Enum: []string{"start", "stop", "shutdown", "restart"},- },- "force": {- Type: "boolean",- Description: "If true, force stop without graceful shutdown (use with caution)",- },- },- Required: []string{"guest_id", "action"},- },- },- {- Name: "pulse_control_docker",- Description: "Control Docker containers. Actions: start, stop, restart. Requires an agent on the Docker host.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "container": {- Type: "string",- Description: "The container name or ID to control",- },- "host": {- Type: "string",- Description: "The Docker host name (required if multiple hosts)",- },- "action": {- Type: "string",- Description: "Action to perform: start, stop, restart",- Enum: []string{"start", "stop", "restart"},- },- },- Required: []string{"container", "action"},- },- },- {- Name: "apply_agent_scope",- Description: "Create or update a scope profile for an agent using settings, then assign it.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "agent_id": {- Type: "string",- Description: "Unified agent ID (preferred if known)",- },- "hostname": {- Type: "string",- Description: "Hostname or display name to resolve the agent ID",- },- "settings": {- Type: "object",- Description: "Profile settings (e.g., enable_host, enable_docker, enable_kubernetes, enable_proxmox, proxmox_type, docker_runtime, disable_auto_update, disable_docker_update_checks, kube_include_all_pods, kube_include_all_deployments, log_level, interval, report_ip, disable_ceph)",- },- },- Required: []string{"settings"},- },- },- {- Name: "assign_agent_profile",- Description: "Assign an existing profile to a unified agent.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "agent_id": {- Type: "string",- Description: "Unified agent ID (preferred if known)",- },- "hostname": {- Type: "string",- Description: "Hostname or display name to resolve the agent ID",- },- "profile_id": {- Type: "string",- Description: "Profile ID to assign to the agent",- },- },- Required: []string{"profile_id"},- },- },- {- Name: "pulse_set_agent_scope",- Description: "Update a unified agent's scope via safe profile settings. Use this instead of running raw commands to enable/disable modules like Docker, Kubernetes, or Proxmox.",- InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "agent_id": {- Type: "string",- Description: "Unified agent ID (preferred if known)",- },- "hostname": {- Type: "string",- Description: "Hostname or display name to resolve the agent ID",- },- "profile_id": {- Type: "string",- Description: "Assign an existing profile ID (optional; omit to use settings)",- },- "settings": {- Type: "object",- Description: "Profile settings (e.g., enable_host, enable_docker, enable_kubernetes, enable_proxmox, proxmox_type, docker_runtime, disable_auto_update, disable_docker_update_checks, kube_include_all_pods, kube_include_all_deployments, log_level, interval, report_ip, disable_ceph)",- },- },- },- },- }- tools = append(tools, controlTools...)- }-- return tools-}--// ExecuteTool executes a tool and returns the result-func (e *PulseToolExecutor) ExecuteTool(ctx context.Context, name string, args map[string]interface{}) (CallToolResult, error) {- log.Debug().- Str("tool", name).- Interface("args", args).- Msg("Executing Pulse tool")-- switch name {- case "pulse_run_command":- return e.executeRunCommand(ctx, args)- case "pulse_fetch_url":- return e.executeFetchURL(ctx, args)- case "pulse_get_infrastructure_state":- return e.executeGetInfrastructureState(ctx)- case "get_agent_scope":- return e.executeGetAgentScope(ctx, args)- case "pulse_get_agent_scope":- return e.executeGetAgentScope(ctx, args)- case "pulse_set_resource_url":- return e.executeSetResourceURL(ctx, args)- case "pulse_resolve_finding":- return e.executeResolveFinding(ctx, args)- case "pulse_dismiss_finding":- return e.executeDismissFinding(ctx, args)- case "pulse_get_metrics_history":- return e.executeGetMetricsHistory(ctx, args)- case "pulse_get_baselines":- return e.executeGetBaselines(ctx, args)- case "pulse_get_patterns":- return e.executeGetPatterns(ctx, args)- case "pulse_get_active_alerts":- return e.executeGetActiveAlerts(ctx, args)- case "pulse_get_findings":- return e.executeGetFindings(ctx, args)- case "pulse_get_backups":- return e.executeGetBackups(ctx, args)- case "pulse_get_storage":- return e.executeGetStorage(ctx, args)- case "pulse_get_resource_details":- return e.executeGetResourceDetails(ctx, args)- case "pulse_get_disk_health":- return e.executeGetDiskHealth(ctx, args)- case "pulse_control_guest":- return e.executeControlGuest(ctx, args)- case "pulse_control_docker":- return e.executeControlDocker(ctx, args)- case "apply_agent_scope":- return e.executeApplyAgentScope(ctx, args)- case "assign_agent_profile":- return e.executeAssignAgentProfile(ctx, args)- case "pulse_set_agent_scope":- return e.executeSetAgentScope(ctx, args)- default:- return NewErrorResult(fmt.Errorf("unknown tool: %s", name)), nil- }-}--func (e *PulseToolExecutor) executeRunCommand(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {- command, _ := args["command"].(string)- runOnHost, _ := args["run_on_host"].(bool)- targetHost, _ := args["target_host"].(string)-- if command == "" {- return NewErrorResult(fmt.Errorf("command is required")), nil- }-- if e.controlLevel == ControlLevelReadOnly || e.controlLevel == "" {- return NewTextResult("Control tools are disabled. Enable them in Settings > AI > Control Level."), nil- }-- // Check security policy- decision := agentexec.PolicyAllow- if e.policy != nil {- decision = e.policy.Evaluate(command)- if decision == agentexec.PolicyBlock {- return NewTextResult(formatPolicyBlocked(command, "This command is blocked by security policy")), nil- }- }-- if e.controlLevel == ControlLevelSuggest {- return NewTextResult(formatCommandSuggestion(command, runOnHost, targetHost)), nil- }-- if e.controlLevel == ControlLevelControlled {- return NewTextResult(formatApprovalNeeded(command, "Control level requires approval")), nil- }- if decision == agentexec.PolicyRequireApproval && !e.isAutonomous {- return NewTextResult(formatApprovalNeeded(command, "Security policy requires approval")), nil- }-- // Execute via agent server- if e.agentServer == nil {- return NewErrorResult(fmt.Errorf("no agent server available")), nil- }-- // Find the appropriate agent- agentID := e.findAgentForCommand(runOnHost, targetHost)- if agentID == "" {- return NewErrorResult(fmt.Errorf("no agent available for target")), nil- }-- // Determine target type based on runOnHost- targetType := "container"- if runOnHost {- targetType = "host"- }-- // Execute command- result, err := e.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{- Command: command,- TargetType: targetType,- TargetID: e.targetID,- })- if err != nil {- return NewErrorResult(err), nil- }-- output := result.Stdout- if result.Stderr != "" {- output += "\n" + result.Stderr- }- if result.ExitCode != 0 {- output = fmt.Sprintf("Exit code %d:\n%s", result.ExitCode, output)- }-- return NewTextResult(output), nil-}--func (e *PulseToolExecutor) executeApplyAgentScope(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {- if profileID, _ := args["profile_id"].(string); strings.TrimSpace(profileID) != "" {- return NewErrorResult(fmt.Errorf("profile_id is not supported for apply_agent_scope")), nil- }-- return e.executeSetAgentScope(ctx, args)-}--func (e *PulseToolExecutor) executeAssignAgentProfile(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {- profileID, _ := args["profile_id"].(string)- if strings.TrimSpace(profileID) == "" {- return NewErrorResult(fmt.Errorf("profile_id is required")), nil- }-- if rawSettings, ok := args["settings"].(map[string]interface{}); ok {- for _, value := range rawSettings {- if value != nil {- return NewErrorResult(fmt.Errorf("settings are not supported for assign_agent_profile")), nil- }- }- }-- return e.executeSetAgentScope(ctx, args)-}--func (e *PulseToolExecutor) executeSetAgentScope(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {- if e.agentProfileManager == nil {- return NewTextResult("Agent scope management is not available."), nil- }- if e.controlLevel == ControlLevelReadOnly || e.controlLevel == "" {- return NewTextResult("Agent scope tools are disabled. Enable them in Settings > AI > Control Level."), nil- }-- agentID, _ := args["agent_id"].(string)- hostname, _ := args["hostname"].(string)- profileID, _ := args["profile_id"].(string)-- agentID = strings.TrimSpace(agentID)- hostname = strings.TrimSpace(hostname)- profileID = strings.TrimSpace(profileID)-- settings := map[string]interface{}{}- if rawSettings, ok := args["settings"].(map[string]interface{}); ok {- for key, value := range rawSettings {- if value != nil {- settings[key] = value- }- }- }-- if agentID == "" && hostname == "" {- return NewErrorResult(fmt.Errorf("agent_id or hostname is required")), nil- }-- agentLabel := agentID- if agentID == "" {- if e.stateProvider == nil {- return NewErrorResult(fmt.Errorf("state provider not available to resolve hostname")), nil- }- resolvedID, resolvedLabel := resolveAgentFromHostname(e.stateProvider.GetState(), hostname)- if resolvedID == "" {- return NewTextResult(fmt.Sprintf("No agent found for hostname '%s'.", hostname)), nil- }- agentID = resolvedID- agentLabel = resolvedLabel- } else if e.stateProvider != nil {- if resolvedLabel := resolveAgentLabel(e.stateProvider.GetState(), agentID); resolvedLabel != "" {- agentLabel = resolvedLabel- }- }-- if profileID != "" && len(settings) > 0 {- return NewErrorResult(fmt.Errorf("use either profile_id or settings, not both")), nil- }-- if e.controlLevel == ControlLevelSuggest {- if profileID != "" {- return NewTextResult(fmt.Sprintf("Suggestion: assign profile %s to agent %s.", profileID, agentLabel)), nil- }- if len(settings) == 0 {- return NewErrorResult(fmt.Errorf("settings are required when profile_id is not provided")), nil- }- return NewTextResult(fmt.Sprintf("Suggestion: apply agent scope to %s with settings: %s", agentLabel, formatSettingsSummary(settings))), nil- }-- if profileID != "" {- profileName, err := e.agentProfileManager.AssignProfile(ctx, agentID, profileID)- if err != nil {- return NewErrorResult(err), nil- }- return NewTextResult(fmt.Sprintf("Assigned profile '%s' (%s) to agent %s. Restart the agent to apply changes.", profileName, profileID, agentLabel)), nil- }-- if len(settings) == 0 {- return NewErrorResult(fmt.Errorf("settings are required when profile_id is not provided")), nil- }-- profileID, profileName, created, err := e.agentProfileManager.ApplyAgentScope(ctx, agentID, agentLabel, settings)- if err != nil {- return NewErrorResult(err), nil- }-- action := "Updated"- if created {- action = "Created"- }- return NewTextResult(fmt.Sprintf("%s profile '%s' (%s) and assigned to agent %s. Restart the agent to apply changes. Settings: %s", action, profileName, profileID, agentLabel, formatSettingsSummary(settings))), nil-}--func (e *PulseToolExecutor) executeGetAgentScope(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {- agentID, _ := args["agent_id"].(string)- hostname, _ := args["hostname"].(string)- agentID = strings.TrimSpace(agentID)- hostname = strings.TrimSpace(hostname)-- if agentID == "" && hostname == "" {- return NewErrorResult(fmt.Errorf("agent_id or hostname is required")), nil- }-- agentLabel := agentID- if agentID == "" {- if e.stateProvider == nil {- return NewErrorResult(fmt.Errorf("state provider not available to resolve hostname")), nil- }- resolvedID, resolvedLabel := resolveAgentFromHostname(e.stateProvider.GetState(), hostname)- if resolvedID == "" {- return NewTextResult(fmt.Sprintf("No agent found for hostname '%s'.", hostname)), nil- }- agentID = resolvedID- agentLabel = resolvedLabel- } else if e.stateProvider != nil {- if resolvedLabel := resolveAgentLabel(e.stateProvider.GetState(), agentID); resolvedLabel != "" {- agentLabel = resolvedLabel- }- }-- var scope *AgentScope- if e.agentProfileManager != nil {- var err error- scope, err = e.agentProfileManager.GetAgentScope(ctx, agentID)- if err != nil {- return NewTextResult(fmt.Sprintf("Failed to load agent scope for %s: %v", agentLabel, err)), nil- }- }-- var observed []string- var commandsEnabled *bool- if e.stateProvider != nil {- observed, commandsEnabled = detectAgentModules(e.stateProvider.GetState(), agentID)- }-- var summary strings.Builder- summary.WriteString(fmt.Sprintf("Agent: %s\n", agentLabel))- summary.WriteString(fmt.Sprintf("Agent ID: %s\n", agentID))-- if scope == nil {- summary.WriteString("Assigned profile: none\n")- } else {- summary.WriteString(fmt.Sprintf("Assigned profile: %s (%s)\n", scope.ProfileName, scope.ProfileID))- if scope.ProfileVersion > 0 {- summary.WriteString(fmt.Sprintf("Profile version: %d\n", scope.ProfileVersion))- }- }-- if len(observed) > 0 {- summary.WriteString(fmt.Sprintf("Observed modules: %s\n", strings.Join(observed, ", ")))- }- if commandsEnabled != nil {- if *commandsEnabled {- summary.WriteString("AI commands: enabled\n")- } else {- summary.WriteString("AI commands: disabled\n")- }- }-- if scope != nil && len(scope.Settings) > 0 {- summary.WriteString("Profile settings:\n")- for _, line := range formatSettingsLines(scope.Settings) {- summary.WriteString(line)- }- } else {- summary.WriteString("Profile settings: none\n")- }-- summary.WriteString("Note: profile changes apply after the agent restarts.")-- return NewTextResult(summary.String()), nil-}--func resolveAgentFromHostname(state models.StateSnapshot, hostname string) (string, string) {- needle := strings.TrimSpace(hostname)- if needle == "" {- return "", ""- }- for _, host := range state.Hosts {- if strings.EqualFold(host.Hostname, needle) || strings.EqualFold(host.DisplayName, needle) || strings.EqualFold(host.ID, needle) {- label := firstNonEmpty(host.DisplayName, host.Hostname, host.ID)- return host.ID, label- }- }- for _, host := range state.DockerHosts {- if strings.EqualFold(host.Hostname, needle) || strings.EqualFold(host.DisplayName, needle) || strings.EqualFold(host.CustomDisplayName, needle) || strings.EqualFold(host.ID, needle) {- label := firstNonEmpty(host.CustomDisplayName, host.DisplayName, host.Hostname, host.ID)- agentID := strings.TrimSpace(host.AgentID)- if agentID == "" {- agentID = host.ID- }- return agentID, label- }- }- return "", ""-}--func resolveAgentLabel(state models.StateSnapshot, agentID string) string {- needle := strings.TrimSpace(agentID)- if needle == "" {- return ""- }- for _, host := range state.Hosts {- if strings.EqualFold(host.ID, needle) {- return firstNonEmpty(host.DisplayName, host.Hostname, host.ID)- }- }- for _, host := range state.DockerHosts {- if strings.EqualFold(host.AgentID, needle) || strings.EqualFold(host.ID, needle) {- return firstNonEmpty(host.CustomDisplayName, host.DisplayName, host.Hostname, host.ID)- }- }- return ""-}--func firstNonEmpty(values ...string) string {- for _, value := range values {- value = strings.TrimSpace(value)- if value != "" {- return value- }- }- return ""-}--func formatSettingsSummary(settings map[string]interface{}) string {- if len(settings) == 0 {- return "none"- }- keys := make([]string, 0, len(settings))- for key := range settings {- keys = append(keys, key)- }- sort.Strings(keys)- parts := make([]string, 0, len(keys))- for _, key := range keys {- parts = append(parts, fmt.Sprintf("%s=%v", key, settings[key]))- }- return strings.Join(parts, ", ")-}--func formatSettingsLines(settings map[string]interface{}) []string {- if len(settings) == 0 {- return []string{" - none\n"}- }- keys := make([]string, 0, len(settings))- for key := range settings {- keys = append(keys, key)- }- sort.Strings(keys)- lines := make([]string, 0, len(keys))- for _, key := range keys {- lines = append(lines, fmt.Sprintf(" - %s: %v\n", key, settings[key]))- }- return lines-}--func detectAgentModules(state models.StateSnapshot, agentID string) ([]string, *bool) {- agentID = strings.TrimSpace(agentID)- if agentID == "" {- return nil, nil- }-- var modules []string- var commandsEnabled *bool-- for _, host := range state.Hosts {- if strings.EqualFold(host.ID, agentID) {- modules = append(modules, "host")- val := host.CommandsEnabled- commandsEnabled = &val- if host.LinkedNodeID != "" {- modules = append(modules, "proxmox")- }- break- }- }-- for _, dockerHost := range state.DockerHosts {- if strings.EqualFold(dockerHost.AgentID, agentID) || strings.EqualFold(dockerHost.ID, agentID) {- modules = append(modules, "docker")- break- }- }-- for _, cluster := range state.KubernetesClusters {- if strings.EqualFold(cluster.AgentID, agentID) {- modules = append(modules, "kubernetes")- break- }- }-- if len(modules) == 0 {- return nil, commandsEnabled- }-- sort.Strings(modules)- return modules, commandsEnabled-}--func (e *PulseToolExecutor) executeFetchURL(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {- url, _ := args["url"].(string)- if url == "" {- return NewErrorResult(fmt.Errorf("url is required")), nil- }-- client := &http.Client{Timeout: 30 * time.Second}- resp, err := client.Get(url)- if err != nil {- return NewTextResult(fmt.Sprintf("Error fetching URL: %v", err)), nil- }- defer resp.Body.Close()-- // Limit response size- body, err := io.ReadAll(io.LimitReader(resp.Body, 50*1024)) // 50KB limit- if err != nil {- return NewTextResult(fmt.Sprintf("Error reading response: %v", err)), nil- }-- result := fmt.Sprintf("Status: %d\nHeaders: %v\n\nBody:\n%s",- resp.StatusCode,- resp.Header,- string(body))-- return NewTextResult(result), nil-}--func (e *PulseToolExecutor) executeGetInfrastructureState(ctx context.Context) (CallToolResult, error) {- if e.stateProvider == nil {- return NewErrorResult(fmt.Errorf("state provider not available")), nil- }-- state := e.stateProvider.GetState()-- // Build a summary of the infrastructure- var summary strings.Builder- summary.WriteString("# Infrastructure State\n\n")-- // Proxmox nodes- if len(state.Nodes) > 0 {- summary.WriteString("## Proxmox Nodes\n")- for _, node := range state.Nodes {- summary.WriteString(fmt.Sprintf("- %s (Status: %s)\n", node.Name, node.Status))- }- summary.WriteString("\n")- }-- // VMs- if len(state.VMs) > 0 {- summary.WriteString(fmt.Sprintf("## VMs (%d total)\n", len(state.VMs)))- for _, vm := range state.VMs {- summary.WriteString(fmt.Sprintf("- %s (VMID: %d, Status: %s)\n", vm.Name, vm.VMID, vm.Status))- }- summary.WriteString("\n")- }-- // Containers- if len(state.Containers) > 0 {- summary.WriteString(fmt.Sprintf("## LXC Containers (%d total)\n", len(state.Containers)))- for _, ct := range state.Containers {- summary.WriteString(fmt.Sprintf("- %s (VMID: %d, Status: %s)\n", ct.Name, ct.VMID, ct.Status))- }- summary.WriteString("\n")- }-- // Docker hosts- if len(state.DockerHosts) > 0 {- summary.WriteString(fmt.Sprintf("## Docker Hosts (%d total)\n", len(state.DockerHosts)))- for _, host := range state.DockerHosts {- name := host.DisplayName- if name == "" {- name = host.Hostname- }- summary.WriteString(fmt.Sprintf("- %s (%d containers)\n", name, len(host.Containers)))- }- summary.WriteString("\n")- }-- return NewTextResult(summary.String()), nil-}--func (e *PulseToolExecutor) executeSetResourceURL(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {- resourceType, _ := args["resource_type"].(string)- resourceID, _ := args["resource_id"].(string)- url, _ := args["url"].(string)-- if e.metadataUpdater == nil {- return NewErrorResult(fmt.Errorf("metadata updater not available")), nil- }-- if err := e.metadataUpdater.SetResourceURL(resourceType, resourceID, url); err != nil {- return NewErrorResult(err), nil- }-- if url == "" {- return NewTextResult(fmt.Sprintf("Cleared URL for %s %s", resourceType, resourceID)), nil- }- return NewTextResult(fmt.Sprintf("Set URL for %s %s to %s", resourceType, resourceID, url)), nil-}--func (e *PulseToolExecutor) executeResolveFinding(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {- findingID, _ := args["finding_id"].(string)- resolutionNote, _ := args["resolution_note"].(string)-- if e.findingsManager == nil {- return NewErrorResult(fmt.Errorf("findings manager not available")), nil- }-- if err := e.findingsManager.ResolveFinding(findingID, resolutionNote); err != nil {- return NewErrorResult(err), nil- }-- return NewTextResult(fmt.Sprintf("Finding %s resolved: %s", findingID, resolutionNote)), nil-}--func (e *PulseToolExecutor) executeDismissFinding(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {- findingID, _ := args["finding_id"].(string)- reason, _ := args["reason"].(string)- note, _ := args["note"].(string)-- if e.findingsManager == nil {- return NewErrorResult(fmt.Errorf("findings manager not available")), nil- }-- if err := e.findingsManager.DismissFinding(findingID, reason, note); err != nil {- return NewErrorResult(err), nil- }-- return NewTextResult(fmt.Sprintf("Finding %s dismissed (%s): %s", findingID, reason, note)), nil-}--func (e *PulseToolExecutor) findAgentForCommand(runOnHost bool, targetHost string) string {- if e.agentServer == nil {- return ""- }-- agents := e.agentServer.GetConnectedAgents()- if len(agents) == 0 {- return ""- }-- // If target host is specified, find that agent- if targetHost != "" {- for _, agent := range agents {- if agent.Hostname == targetHost || agent.AgentID == targetHost {- return agent.AgentID- }- }- }-- // Otherwise return first connected agent- return agents[0].AgentID-}--// formatApprovalNeeded formats an approval-needed response-func formatApprovalNeeded(command, reason string) string {- payload := map[string]interface{}{- "type": "approval_required",- "command": command,- "reason": reason,- "how_to_approve": "Ask the user to click the approval button shown in the UI.",- "do_not_retry": true,- }- b, _ := json.Marshal(payload)- return "APPROVAL_REQUIRED: " + string(b)-}--// formatPolicyBlocked formats a policy-blocked response-func formatPolicyBlocked(command, reason string) string {- payload := map[string]interface{}{- "type": "policy_blocked",- "command": command,- "reason": reason,- "do_not_retry": true,- }- b, _ := json.Marshal(payload)- return "POLICY_BLOCKED: " + string(b)-}--func formatCommandSuggestion(command string, runOnHost bool, targetHost string) string {- target := "current target"- if runOnHost {- target = "host"- }- if strings.TrimSpace(targetHost) != "" {- target = fmt.Sprintf("host %s", targetHost)- }- return fmt.Sprintf("Suggested command for %s:\n%s", target, command)-}--// Patrol context tool implementations--func (e *PulseToolExecutor) executeGetMetricsHistory(_ context.Context, args map[string]interface{}) (CallToolResult, error) {- period, _ := args["period"].(string)- resourceID, _ := args["resource_id"].(string)-- if e.metricsHistory == nil {- return NewTextResult("Metrics history not available. The system may still be collecting data."), nil- }-- var duration time.Duration- switch period {- case "24h":- duration = 24 * time.Hour- case "7d":- duration = 7 * 24 * time.Hour- default:- duration = 24 * time.Hour- }-- if resourceID != "" {- // Get metrics for specific resource- metrics, err := e.metricsHistory.GetResourceMetrics(resourceID, duration)- if err != nil {- return NewTextResult(fmt.Sprintf("Error getting metrics: %v", err)), nil- }- if len(metrics) == 0 {- return NewTextResult(fmt.Sprintf("No metrics found for resource %s in last %s", resourceID, period)), nil- }-- // Format as text- var result strings.Builder- result.WriteString(fmt.Sprintf("# Metrics for %s (last %s)\n\n", resourceID, period))- for _, m := range metrics {- result.WriteString(fmt.Sprintf("- %s: CPU=%.1f%%, Mem=%.1f%%, Disk=%.1f%%\n",- m.Timestamp.Format("2006-01-02 15:04"), m.CPU, m.Memory, m.Disk))- }- return NewTextResult(result.String()), nil- }-- // Get summary for all resources- summary, err := e.metricsHistory.GetAllMetricsSummary(duration)- if err != nil {- return NewTextResult(fmt.Sprintf("Error getting metrics summary: %v", err)), nil- }- if len(summary) == 0 {- return NewTextResult("No metrics data available yet. The system is still collecting data."), nil- }-- var result strings.Builder- result.WriteString(fmt.Sprintf("# Metrics Summary (last %s)\n\n", period))- for _, s := range summary {- result.WriteString(fmt.Sprintf("## %s (%s)\n", s.ResourceName, s.ResourceType))- result.WriteString(fmt.Sprintf("- CPU: avg=%.1f%%, max=%.1f%%\n", s.AvgCPU, s.MaxCPU))- result.WriteString(fmt.Sprintf("- Memory: avg=%.1f%%, max=%.1f%%\n", s.AvgMemory, s.MaxMemory))- if s.AvgDisk > 0 {- result.WriteString(fmt.Sprintf("- Disk: avg=%.1f%%, max=%.1f%%\n", s.AvgDisk, s.MaxDisk))- }- result.WriteString(fmt.Sprintf("- Trend: %s\n\n", s.Trend))- }- return NewTextResult(result.String()), nil-}--func (e *PulseToolExecutor) executeGetBaselines(_ context.Context, args map[string]interface{}) (CallToolResult, error) {- resourceID, _ := args["resource_id"].(string)-- if e.baselineProvider == nil {- return NewTextResult("Baseline data not available. The system needs time to learn normal behavior patterns."), nil- }-- if resourceID != "" {- // Get baseline for specific resource- cpuBaseline := e.baselineProvider.GetBaseline(resourceID, "cpu")- memBaseline := e.baselineProvider.GetBaseline(resourceID, "memory")-- if cpuBaseline == nil && memBaseline == nil {- return NewTextResult(fmt.Sprintf("No baseline data for resource %s yet.", resourceID)), nil- }-- var result strings.Builder- result.WriteString(fmt.Sprintf("# Baselines for %s\n\n", resourceID))- if cpuBaseline != nil {- result.WriteString(fmt.Sprintf("CPU: mean=%.1f%%, stddev=%.1f%%, range=[%.1f%%, %.1f%%]\n",- cpuBaseline.Mean, cpuBaseline.StdDev, cpuBaseline.Min, cpuBaseline.Max))- }- if memBaseline != nil {- result.WriteString(fmt.Sprintf("Memory: mean=%.1f%%, stddev=%.1f%%, range=[%.1f%%, %.1f%%]\n",- memBaseline.Mean, memBaseline.StdDev, memBaseline.Min, memBaseline.Max))- }- return NewTextResult(result.String()), nil- }-- // Get all baselines- allBaselines := e.baselineProvider.GetAllBaselines()- if len(allBaselines) == 0 {- return NewTextResult("No baseline data available yet. The system needs time to learn normal behavior patterns."), nil- }-- var result strings.Builder- result.WriteString("# Learned Baselines\n\n")- for resID, metrics := range allBaselines {- result.WriteString(fmt.Sprintf("## %s\n", resID))- for metric, baseline := range metrics {- result.WriteString(fmt.Sprintf("- %s: mean=%.1f%%, stddev=%.1f%%\n",- metric, baseline.Mean, baseline.StdDev))- }- result.WriteString("\n")- }- return NewTextResult(result.String()), nil-}--func (e *PulseToolExecutor) executeGetPatterns(_ context.Context, _ map[string]interface{}) (CallToolResult, error) {- if e.patternProvider == nil {- return NewTextResult("Pattern detection not available. The system needs more historical data."), nil- }-- patterns := e.patternProvider.GetPatterns()- predictions := e.patternProvider.GetPredictions()-- if len(patterns) == 0 && len(predictions) == 0 {- return NewTextResult("No patterns or predictions detected yet. The system is still analyzing historical data."), nil- }-- var result strings.Builder- result.WriteString("# Patterns and Predictions\n\n")-- if len(patterns) > 0 {- result.WriteString("## Detected Patterns\n")- for _, p := range patterns {- result.WriteString(fmt.Sprintf("- %s (%s): %s (confidence: %.0f%%)\n",- p.ResourceName, p.PatternType, p.Description, p.Confidence*100))- }- result.WriteString("\n")- }-- if len(predictions) > 0 {- result.WriteString("## Predictions\n")- for _, p := range predictions {- result.WriteString(fmt.Sprintf("- %s: %s predicted by %s (confidence: %.0f%%)\n",- p.ResourceName, p.IssueType, p.PredictedTime.Format("2006-01-02"), p.Confidence*100))- if p.Recommendation != "" {- result.WriteString(fmt.Sprintf(" Recommendation: %s\n", p.Recommendation))- }- }- }-- return NewTextResult(result.String()), nil-}--func (e *PulseToolExecutor) executeGetActiveAlerts(_ context.Context, _ map[string]interface{}) (CallToolResult, error) {- if e.alertProvider == nil {- return NewTextResult("Alert data not available."), nil- }-- alerts := e.alertProvider.GetActiveAlerts()- if len(alerts) == 0 {- return NewTextResult("No active alerts. All resources are operating within configured thresholds."), nil- }-- var result strings.Builder- result.WriteString(fmt.Sprintf("# Active Alerts (%d)\n\n", len(alerts)))- for _, a := range alerts {- result.WriteString(fmt.Sprintf("## %s - %s\n", a.ResourceName, a.Type))- result.WriteString(fmt.Sprintf("- Severity: %s\n", a.Severity))- result.WriteString(fmt.Sprintf("- Current: %.1f%% (threshold: %.1f%%)\n", a.Value, a.Threshold))- result.WriteString(fmt.Sprintf("- Started: %s\n", a.StartTime.Format("2006-01-02 15:04")))- result.WriteString(fmt.Sprintf("- Message: %s\n\n", a.Message))- }-- return NewTextResult(result.String()), nil-}--func (e *PulseToolExecutor) executeGetFindings(_ context.Context, args map[string]interface{}) (CallToolResult, error) {- includeDismissed, _ := args["include_dismissed"].(bool)-- if e.findingsProvider == nil {- return NewTextResult("Patrol findings not available. AI Patrol may not be running."), nil- }-- activeFindings := e.findingsProvider.GetActiveFindings()- var dismissedFindings []Finding- if includeDismissed {- dismissedFindings = e.findingsProvider.GetDismissedFindings()- }-- if len(activeFindings) == 0 && len(dismissedFindings) == 0 {- return NewTextResult("No patrol findings. Either no issues detected or AI Patrol hasn't run yet."), nil- }-- var result strings.Builder-- if len(activeFindings) > 0 {- result.WriteString(fmt.Sprintf("# Active Findings (%d)\n\n", len(activeFindings)))- for _, f := range activeFindings {- result.WriteString(fmt.Sprintf("## [%s] %s - %s\n", f.Severity, f.ResourceName, f.Title))- result.WriteString(fmt.Sprintf("- Category: %s\n", f.Category))- result.WriteString(fmt.Sprintf("- ID: %s\n", f.ID))- result.WriteString(fmt.Sprintf("- Description: %s\n", f.Description))- result.WriteString(fmt.Sprintf("- Recommendation: %s\n", f.Recommendation))- result.WriteString(fmt.Sprintf("- Evidence: %s\n", f.Evidence))- result.WriteString(fmt.Sprintf("- First detected: %s, seen %d times\n\n",- f.DetectedAt.Format("2006-01-02 15:04"), f.TimesRaised))- }- }-- if len(dismissedFindings) > 0 {- result.WriteString(fmt.Sprintf("# Dismissed Findings (%d)\n\n", len(dismissedFindings)))- result.WriteString("These findings were dismissed by users - do NOT re-raise them:\n\n")- for _, f := range dismissedFindings {- result.WriteString(fmt.Sprintf("- [%s] %s: %s (key: %s)\n", f.Severity, f.ResourceName, f.Title, f.Key))- }- }-- return NewTextResult(result.String()), nil-}--// Infrastructure context tool implementations--func (e *PulseToolExecutor) executeGetBackups(_ context.Context, args map[string]interface{}) (CallToolResult, error) {- resourceID, _ := args["resource_id"].(string)-- if e.backupProvider == nil {- return NewTextResult("Backup information not available."), nil- }-- backups := e.backupProvider.GetBackups()- pbsInstances := e.backupProvider.GetPBSInstances()-- var result strings.Builder- result.WriteString("# Backup Status\n\n")-- // PBS Backups- if len(backups.PBS) > 0 {- result.WriteString(fmt.Sprintf("## PBS Backups (%d)\n", len(backups.PBS)))- for _, b := range backups.PBS {- if resourceID != "" && b.VMID != resourceID {- continue- }- result.WriteString(fmt.Sprintf("- %s %s: %s on %s/%s (%.1f GB)\n",- b.BackupType, b.VMID,- b.BackupTime.Format("2006-01-02 15:04"),- b.Instance, b.Datastore,- float64(b.Size)/(1024*1024*1024)))- if b.Verified {- result.WriteString(" ✓ Verified\n")- }- if b.Protected {- result.WriteString(" 🔒 Protected\n")- }- }- result.WriteString("\n")- }-- // PVE Backups- if len(backups.PVE.StorageBackups) > 0 {- result.WriteString(fmt.Sprintf("## PVE Storage Backups (%d)\n", len(backups.PVE.StorageBackups)))- for _, b := range backups.PVE.StorageBackups {- if resourceID != "" && fmt.Sprintf("%d", b.VMID) != resourceID {- continue- }- result.WriteString(fmt.Sprintf("- VMID %d: %s (%.1f GB)\n",- b.VMID,- b.Time.Format("2006-01-02 15:04"),- float64(b.Size)/(1024*1024*1024)))- }- result.WriteString("\n")- }-- // PBS Instances summary- if len(pbsInstances) > 0 {- result.WriteString("## PBS Servers\n")- for _, pbs := range pbsInstances {- result.WriteString(fmt.Sprintf("- %s (%s): %s\n", pbs.Name, pbs.Host, pbs.Status))- for _, ds := range pbs.Datastores {- result.WriteString(fmt.Sprintf(" - %s: %.1f%% used (%.1f GB free)\n",- ds.Name, ds.Usage*100, float64(ds.Free)/(1024*1024*1024)))- }- }- result.WriteString("\n")- }-- // Backup jobs- if len(backups.PVE.BackupTasks) > 0 {- result.WriteString("## Recent Backup Tasks\n")- for _, t := range backups.PVE.BackupTasks {- status := "✓"- if t.Status != "ok" {- status = "✗ " + t.Status- }- result.WriteString(fmt.Sprintf("- %s: VMID %d on %s (%s)\n",- status, t.VMID, t.Node, t.StartTime.Format("2006-01-02 15:04")))- }- }-- if result.Len() == len("# Backup Status\n\n") {- return NewTextResult("No backup data available. PBS/PVE backup monitoring may not be configured."), nil- }-- return NewTextResult(result.String()), nil-}--func (e *PulseToolExecutor) executeGetStorage(_ context.Context, args map[string]interface{}) (CallToolResult, error) {- storageID, _ := args["storage_id"].(string)-- if e.storageProvider == nil {- return NewTextResult("Storage information not available."), nil- }-- storage := e.storageProvider.GetStorage()- cephClusters := e.storageProvider.GetCephClusters()-- var result strings.Builder- result.WriteString("# Storage Status\n\n")-- // Storage pools- if len(storage) > 0 {- result.WriteString("## Storage Pools\n")- for _, s := range storage {- if storageID != "" && s.ID != storageID && s.Name != storageID {- continue- }- statusIcon := "✓"- if s.Status != "available" {- statusIcon = "⚠"- }- result.WriteString(fmt.Sprintf("### %s %s (%s)\n", statusIcon, s.Name, s.Type))- result.WriteString(fmt.Sprintf("- Usage: %.1f%% (%.1f GB / %.1f GB)\n",- s.Usage*100,- float64(s.Used)/(1024*1024*1024),- float64(s.Total)/(1024*1024*1024)))- result.WriteString(fmt.Sprintf("- Free: %.1f GB\n", float64(s.Free)/(1024*1024*1024)))- result.WriteString(fmt.Sprintf("- Content: %s\n", s.Content))- if s.Shared {- result.WriteString("- Shared: Yes\n")- }-- // ZFS pool details- if s.ZFSPool != nil {- zfs := s.ZFSPool- result.WriteString(fmt.Sprintf("- ZFS Pool: %s (State: %s)\n", zfs.Name, zfs.State))- if zfs.ReadErrors > 0 || zfs.WriteErrors > 0 || zfs.ChecksumErrors > 0 {- result.WriteString(fmt.Sprintf(" ⚠ Errors: read=%d, write=%d, checksum=%d\n",- zfs.ReadErrors, zfs.WriteErrors, zfs.ChecksumErrors))- }- if zfs.Scan != "" {- result.WriteString(fmt.Sprintf(" - Scan: %s\n", zfs.Scan))- }- }- result.WriteString("\n")- }- }-- // Ceph clusters- if len(cephClusters) > 0 {- result.WriteString("## Ceph Clusters\n")- for _, c := range cephClusters {- healthIcon := "✓"- if c.Health != "HEALTH_OK" {- healthIcon = "⚠"- }- result.WriteString(fmt.Sprintf("### %s %s\n", healthIcon, c.Name))- result.WriteString(fmt.Sprintf("- Health: %s", c.Health))- if c.HealthMessage != "" {- result.WriteString(fmt.Sprintf(" - %s", c.HealthMessage))- }- result.WriteString("\n")- result.WriteString(fmt.Sprintf("- Usage: %.1f%% (%.1f TB / %.1f TB)\n",- c.UsagePercent,- float64(c.UsedBytes)/(1024*1024*1024*1024),- float64(c.TotalBytes)/(1024*1024*1024*1024)))- result.WriteString(fmt.Sprintf("- OSDs: %d up, %d in (of %d total)\n",- c.NumOSDsUp, c.NumOSDsIn, c.NumOSDs))- result.WriteString(fmt.Sprintf("- Monitors: %d, Managers: %d\n", c.NumMons, c.NumMgrs))- result.WriteString("\n")- }- }-- if result.Len() == len("# Storage Status\n\n") {- return NewTextResult("No storage data available."), nil- }-- return NewTextResult(result.String()), nil-}--func (e *PulseToolExecutor) executeGetResourceDetails(_ context.Context, args map[string]interface{}) (CallToolResult, error) {- resourceType, _ := args["resource_type"].(string)- resourceID, _ := args["resource_id"].(string)-- if e.stateProvider == nil {- return NewTextResult("State information not available."), nil- }-- state := e.stateProvider.GetState()- var result strings.Builder-- switch resourceType {- case "vm":- for _, vm := range state.VMs {- if fmt.Sprintf("%d", vm.VMID) == resourceID || vm.Name == resourceID || vm.ID == resourceID {- result.WriteString(fmt.Sprintf("# VM: %s (VMID %d)\n\n", vm.Name, vm.VMID))- result.WriteString(fmt.Sprintf("- Status: %s\n", vm.Status))- result.WriteString(fmt.Sprintf("- Node: %s\n", vm.Node))- result.WriteString(fmt.Sprintf("- CPU: %.1f%% (%d cores)\n", vm.CPU*100, vm.CPUs))- result.WriteString(fmt.Sprintf("- Memory: %.1f%% (%.1f GB / %.1f GB)\n",- vm.Memory.Usage*100,- float64(vm.Memory.Used)/(1024*1024*1024),- float64(vm.Memory.Total)/(1024*1024*1024)))- if vm.OSName != "" {- result.WriteString(fmt.Sprintf("- OS: %s\n", vm.OSName))- }- if len(vm.Tags) > 0 {- result.WriteString(fmt.Sprintf("- Tags: %s\n", strings.Join(vm.Tags, ", ")))- }- if len(vm.NetworkInterfaces) > 0 {- result.WriteString("- Network Interfaces:\n")- for _, nic := range vm.NetworkInterfaces {- result.WriteString(fmt.Sprintf(" - %s: %s\n", nic.Name, strings.Join(nic.Addresses, ", ")))- }- }- if !vm.LastBackup.IsZero() {- result.WriteString(fmt.Sprintf("- Last Backup: %s\n", vm.LastBackup.Format("2006-01-02 15:04")))- }- return NewTextResult(result.String()), nil- }- }- return NewTextResult(fmt.Sprintf("VM '%s' not found.", resourceID)), nil-- case "container":- for _, ct := range state.Containers {- if fmt.Sprintf("%d", ct.VMID) == resourceID || ct.Name == resourceID || ct.ID == resourceID {- result.WriteString(fmt.Sprintf("# Container: %s (VMID %d)\n\n", ct.Name, ct.VMID))- result.WriteString(fmt.Sprintf("- Status: %s\n", ct.Status))- result.WriteString(fmt.Sprintf("- Node: %s\n", ct.Node))- result.WriteString(fmt.Sprintf("- CPU: %.1f%% (%d cores)\n", ct.CPU*100, ct.CPUs))- result.WriteString(fmt.Sprintf("- Memory: %.1f%% (%.1f GB / %.1f GB)\n",- ct.Memory.Usage*100,- float64(ct.Memory.Used)/(1024*1024*1024),- float64(ct.Memory.Total)/(1024*1024*1024)))- if ct.OSName != "" {- result.WriteString(fmt.Sprintf("- OS: %s\n", ct.OSName))- }- if len(ct.Tags) > 0 {- result.WriteString(fmt.Sprintf("- Tags: %s\n", strings.Join(ct.Tags, ", ")))- }- if len(ct.NetworkInterfaces) > 0 {- result.WriteString("- Network Interfaces:\n")- for _, nic := range ct.NetworkInterfaces {- result.WriteString(fmt.Sprintf(" - %s: %s\n", nic.Name, strings.Join(nic.Addresses, ", ")))- }- }- if !ct.LastBackup.IsZero() {- result.WriteString(fmt.Sprintf("- Last Backup: %s\n", ct.LastBackup.Format("2006-01-02 15:04")))- }- return NewTextResult(result.String()), nil- }- }- return NewTextResult(fmt.Sprintf("Container '%s' not found.", resourceID)), nil-- case "docker":- for _, host := range state.DockerHosts {- for _, c := range host.Containers {- if c.ID == resourceID || c.Name == resourceID || strings.HasPrefix(c.ID, resourceID) {- result.WriteString(fmt.Sprintf("# Docker Container: %s\n\n", c.Name))- result.WriteString(fmt.Sprintf("- Host: %s\n", host.Hostname))- result.WriteString(fmt.Sprintf("- Image: %s\n", c.Image))- result.WriteString(fmt.Sprintf("- State: %s (%s)\n", c.State, c.Status))- if c.Health != "" {- result.WriteString(fmt.Sprintf("- Health: %s\n", c.Health))- }- result.WriteString(fmt.Sprintf("- CPU: %.1f%%\n", c.CPUPercent))- result.WriteString(fmt.Sprintf("- Memory: %.1f%% (%.1f MB / %.1f MB)\n",- c.MemoryPercent,- float64(c.MemoryUsage)/(1024*1024),- float64(c.MemoryLimit)/(1024*1024)))- result.WriteString(fmt.Sprintf("- Restart Count: %d\n", c.RestartCount))-- if len(c.Ports) > 0 {- result.WriteString("- Ports:\n")- for _, p := range c.Ports {- if p.PublicPort > 0 {- result.WriteString(fmt.Sprintf(" - %s:%d -> %d/%s\n", p.IP, p.PublicPort, p.PrivatePort, p.Protocol))- } else {- result.WriteString(fmt.Sprintf(" - %d/%s (internal)\n", p.PrivatePort, p.Protocol))- }- }- }-- if len(c.Networks) > 0 {- result.WriteString("- Networks:\n")- for _, n := range c.Networks {- result.WriteString(fmt.Sprintf(" - %s: %s\n", n.Name, n.IPv4))- }- }-- if len(c.Mounts) > 0 {- result.WriteString("- Mounts:\n")- for _, m := range c.Mounts {- rw := "ro"- if m.RW {- rw = "rw"- }- result.WriteString(fmt.Sprintf(" - %s -> %s (%s)\n", m.Source, m.Destination, rw))- }- }-- if len(c.Labels) > 0 {- result.WriteString("- Labels:\n")- for k, v := range c.Labels {- // Skip long or internal labels- if len(v) > 50 || strings.HasPrefix(k, "org.opencontainers") {- continue- }- result.WriteString(fmt.Sprintf(" - %s: %s\n", k, v))- }- }-- if c.UpdateStatus != nil && c.UpdateStatus.UpdateAvailable {- result.WriteString("- ⚠ Image update available!\n")- }-- return NewTextResult(result.String()), nil- }- }- }- return NewTextResult(fmt.Sprintf("Docker container '%s' not found.", resourceID)), nil-- default:- return NewTextResult("Invalid resource_type. Use 'vm', 'container', or 'docker'."), nil- }-}--func (e *PulseToolExecutor) executeGetDiskHealth(_ context.Context, _ map[string]interface{}) (CallToolResult, error) {- if e.diskHealthProvider == nil && e.storageProvider == nil {- return NewTextResult("Disk health information not available."), nil- }-- var result strings.Builder- result.WriteString("# Disk Health Status\n\n")-- hasData := false-- // SMART and RAID data from host agents- if e.diskHealthProvider != nil {- hosts := e.diskHealthProvider.GetHosts()- for _, host := range hosts {- hostHasData := false-- // SMART data- if len(host.Sensors.SMART) > 0 {- if !hostHasData {- result.WriteString(fmt.Sprintf("## Host: %s\n\n", host.Hostname))- hostHasData = true- hasData = true- }- result.WriteString("### SMART Data\n")- for _, disk := range host.Sensors.SMART {- healthIcon := "✓"- if disk.Health != "PASSED" && disk.Health != "" {- healthIcon = "⚠"- }- result.WriteString(fmt.Sprintf("- %s %s: %s", healthIcon, disk.Device, disk.Model))- if disk.Temperature > 0 {- result.WriteString(fmt.Sprintf(" (%d°C)", disk.Temperature))- }- if disk.Health != "" {- result.WriteString(fmt.Sprintf(" [%s]", disk.Health))- }- result.WriteString("\n")- }- result.WriteString("\n")- }-- // RAID arrays- if len(host.RAID) > 0 {- if !hostHasData {- result.WriteString(fmt.Sprintf("## Host: %s\n\n", host.Hostname))- hostHasData = true- hasData = true- }- result.WriteString("### RAID Arrays\n")- for _, raid := range host.RAID {- stateIcon := "✓"- if raid.State != "active" && raid.State != "clean" {- stateIcon = "⚠"- }- result.WriteString(fmt.Sprintf("- %s %s (%s): %s\n",- stateIcon, raid.Device, raid.Level, raid.State))- result.WriteString(fmt.Sprintf(" - Devices: %d active, %d working, %d failed, %d spare\n",- raid.ActiveDevices, raid.WorkingDevices, raid.FailedDevices, raid.SpareDevices))- if raid.RebuildPercent > 0 {- result.WriteString(fmt.Sprintf(" - Rebuilding: %.1f%%\n", raid.RebuildPercent))- }- }- result.WriteString("\n")- }-- // Host Ceph data- if host.Ceph != nil {- ceph := host.Ceph- if !hostHasData {- result.WriteString(fmt.Sprintf("## Host: %s\n\n", host.Hostname))- hostHasData = true- hasData = true- }- result.WriteString("### Ceph Status (from agent)\n")- healthIcon := "✓"- if ceph.Health.Status != "HEALTH_OK" {- healthIcon = "⚠"- }- result.WriteString(fmt.Sprintf("- %s Health: %s\n", healthIcon, ceph.Health.Status))- result.WriteString(fmt.Sprintf("- OSDs: %d up / %d in / %d total\n",- ceph.OSDMap.NumUp, ceph.OSDMap.NumIn, ceph.OSDMap.NumOSDs))- result.WriteString(fmt.Sprintf("- PGs: %d (%.1f%% used)\n",- ceph.PGMap.NumPGs, ceph.PGMap.UsagePercent))- result.WriteString("\n")- }- }- }-- // Ceph clusters from Proxmox API- if e.storageProvider != nil {- cephClusters := e.storageProvider.GetCephClusters()- if len(cephClusters) > 0 {- result.WriteString("## Ceph Clusters (from Proxmox)\n\n")- hasData = true- for _, c := range cephClusters {- healthIcon := "✓"- if c.Health != "HEALTH_OK" {- healthIcon = "⚠"- }- result.WriteString(fmt.Sprintf("### %s %s\n", healthIcon, c.Name))- result.WriteString(fmt.Sprintf("- Health: %s", c.Health))- if c.HealthMessage != "" {- result.WriteString(fmt.Sprintf(" - %s", c.HealthMessage))- }- result.WriteString("\n")- result.WriteString(fmt.Sprintf("- OSDs: %d up, %d in (of %d)\n",- c.NumOSDsUp, c.NumOSDsIn, c.NumOSDs))- result.WriteString("\n")- }- }- }-- if !hasData {- return NewTextResult("No disk health data available. Host agents may not be reporting SMART/RAID data, or no Ceph clusters are configured."), nil- }-- return NewTextResult(result.String()), nil-}--// Control tool implementations--// GuestInfo represents resolved guest information-type GuestInfo struct {- VMID int- Name string- Node string- Type string // "vm" or "lxc"- Status string- Instance string-}--func (e *PulseToolExecutor) executeControlGuest(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {- guestID, _ := args["guest_id"].(string)- action, _ := args["action"].(string)- force, _ := args["force"].(bool)-- if guestID == "" {- return NewErrorResult(fmt.Errorf("guest_id is required")), nil- }- if action == "" {- return NewErrorResult(fmt.Errorf("action is required")), nil- }-- // Validate action- validActions := map[string]bool{"start": true, "stop": true, "shutdown": true, "restart": true}- if !validActions[action] {- return NewErrorResult(fmt.Errorf("invalid action: %s. Use start, stop, shutdown, or restart", action)), nil- }-- // Check control level- if e.controlLevel == ControlLevelReadOnly || e.controlLevel == "" {- return NewTextResult("Control tools are disabled. Enable them in Settings > AI > Control Level."), nil- }-- // Resolve guest to find VMID, node, and type- guest, err := e.resolveGuest(guestID)- if err != nil {- return NewTextResult(fmt.Sprintf("Could not find guest '%s': %v", guestID, err)), nil- }-- // Check if guest is protected- vmidStr := fmt.Sprintf("%d", guest.VMID)- for _, protected := range e.protectedGuests {- if protected == vmidStr || protected == guest.Name {- return NewTextResult(fmt.Sprintf("Guest %s (VMID %d) is protected and cannot be controlled by AI.", guest.Name, guest.VMID)), nil- }- }-- // Build the command based on guest type and action- var command string- cmdTool := "pct" // LXC containers- if guest.Type == "vm" {- cmdTool = "qm"- }-- switch action {- case "start":- command = fmt.Sprintf("%s start %d", cmdTool, guest.VMID)- case "stop":- command = fmt.Sprintf("%s stop %d", cmdTool, guest.VMID)- case "shutdown":- command = fmt.Sprintf("%s shutdown %d", cmdTool, guest.VMID)- case "restart":- // Restart is shutdown + start, but we'll use reboot for simplicity- command = fmt.Sprintf("%s reboot %d", cmdTool, guest.VMID)- }-- // Add force flag if requested (only for stop)- if force && action == "stop" {- command = fmt.Sprintf("%s stop %d --skiplock", cmdTool, guest.VMID)- }-- // Check security policy- if e.policy != nil {- decision := e.policy.Evaluate(command)- if decision == agentexec.PolicyBlock {- return NewTextResult(formatPolicyBlocked(command, "This command is blocked by security policy")), nil- }- // For control level "controlled", always require approval- if e.controlLevel == ControlLevelControlled || (decision == agentexec.PolicyRequireApproval && !e.isAutonomous) {- return NewTextResult(formatControlApprovalNeeded(guest.Name, guest.VMID, action, command)), nil- }- }-- // For "suggest" mode, just return the command suggestion- if e.controlLevel == ControlLevelSuggest {- return NewTextResult(formatControlSuggestion(guest.Name, guest.VMID, action, command, guest.Node)), nil- }-- // Execute the command via agent- if e.agentServer == nil {- return NewErrorResult(fmt.Errorf("no agent server available")), nil- }-- // Find agent for the node that owns this guest- agentID := e.findAgentForNode(guest.Node)- if agentID == "" {- return NewTextResult(fmt.Sprintf("No agent available on node '%s'. Install Pulse Unified Agent on the Proxmox host to enable control.", guest.Node)), nil- }-- // Execute command- result, err := e.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{- Command: command,- TargetType: "host",- TargetID: "",- })- if err != nil {- return NewErrorResult(err), nil- }-- // Format result- output := result.Stdout- if result.Stderr != "" {- output += "\n" + result.Stderr- }-- if result.ExitCode == 0 {- return NewTextResult(fmt.Sprintf("Successfully executed '%s' on %s (VMID %d).\n%s", action, guest.Name, guest.VMID, output)), nil- }-- return NewTextResult(fmt.Sprintf("Command failed (exit code %d):\n%s", result.ExitCode, output)), nil-}--func (e *PulseToolExecutor) executeControlDocker(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {- containerName, _ := args["container"].(string)- hostName, _ := args["host"].(string)- action, _ := args["action"].(string)-- if containerName == "" {- return NewErrorResult(fmt.Errorf("container name is required")), nil- }- if action == "" {- return NewErrorResult(fmt.Errorf("action is required")), nil- }-- // Validate action- validActions := map[string]bool{"start": true, "stop": true, "restart": true}- if !validActions[action] {- return NewErrorResult(fmt.Errorf("invalid action: %s. Use start, stop, or restart", action)), nil- }-- // Check control level- if e.controlLevel == ControlLevelReadOnly || e.controlLevel == "" {- return NewTextResult("Control tools are disabled. Enable them in Settings > AI > Control Level."), nil- }-- // Find the Docker container and its host- container, dockerHost, err := e.resolveDockerContainer(containerName, hostName)- if err != nil {- return NewTextResult(fmt.Sprintf("Could not find Docker container '%s': %v", containerName, err)), nil- }-- // Build the command- command := fmt.Sprintf("docker %s %s", action, container.Name)-- // Check security policy- if e.policy != nil {- decision := e.policy.Evaluate(command)- if decision == agentexec.PolicyBlock {- return NewTextResult(formatPolicyBlocked(command, "This command is blocked by security policy")), nil- }- if e.controlLevel == ControlLevelControlled || (decision == agentexec.PolicyRequireApproval && !e.isAutonomous) {- return NewTextResult(formatDockerApprovalNeeded(container.Name, dockerHost.Hostname, action, command)), nil- }- }-- // For "suggest" mode, just return the command suggestion- if e.controlLevel == ControlLevelSuggest {- return NewTextResult(formatDockerSuggestion(container.Name, dockerHost.Hostname, action, command)), nil- }-- // Execute the command via agent- if e.agentServer == nil {- return NewErrorResult(fmt.Errorf("no agent server available")), nil- }-- // Find agent for this Docker host- agentID := e.findAgentForDockerHost(dockerHost)- if agentID == "" {- return NewTextResult(fmt.Sprintf("No agent available on Docker host '%s'. Install Pulse Unified Agent on the host to enable control.", dockerHost.Hostname)), nil- }-- // Execute command- result, err := e.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{- Command: command,- TargetType: "host",- TargetID: "",- })- if err != nil {- return NewErrorResult(err), nil- }-- // Format result- output := result.Stdout- if result.Stderr != "" {- output += "\n" + result.Stderr- }-- if result.ExitCode == 0 {- return NewTextResult(fmt.Sprintf("Successfully executed 'docker %s' on container '%s' (host: %s).\n%s", action, container.Name, dockerHost.Hostname, output)), nil- }-- return NewTextResult(fmt.Sprintf("Command failed (exit code %d):\n%s", result.ExitCode, output)), nil-}--// resolveGuest finds a guest (VM or container) by VMID or name-func (e *PulseToolExecutor) resolveGuest(guestID string) (*GuestInfo, error) {- if e.stateProvider == nil {- return nil, fmt.Errorf("state provider not available")- }-- state := e.stateProvider.GetState()-- // Try to parse as VMID- vmid, err := strconv.Atoi(guestID)-- // Search VMs- for _, vm := range state.VMs {- if (err == nil && vm.VMID == vmid) || vm.Name == guestID || vm.ID == guestID {- return &GuestInfo{- VMID: vm.VMID,- Name: vm.Name,- Node: vm.Node,- Type: "vm",- Status: vm.Status,- Instance: vm.Instance,- }, nil- }- }-- // Search containers- for _, ct := range state.Containers {- if (err == nil && ct.VMID == vmid) || ct.Name == guestID || ct.ID == guestID {- return &GuestInfo{- VMID: ct.VMID,- Name: ct.Name,- Node: ct.Node,- Type: "lxc",- Status: ct.Status,- Instance: ct.Instance,- }, nil- }- }-- return nil, fmt.Errorf("no VM or container found with ID or name '%s'", guestID)-}--// resolveDockerContainer finds a Docker container by name or ID-func (e *PulseToolExecutor) resolveDockerContainer(containerName, hostName string) (*models.DockerContainer, *models.DockerHost, error) {- if e.stateProvider == nil {- return nil, nil, fmt.Errorf("state provider not available")- }-- state := e.stateProvider.GetState()-- for _, host := range state.DockerHosts {- // If host name specified, only search that host- if hostName != "" && host.Hostname != hostName && host.DisplayName != hostName {- continue- }-- for i, container := range host.Containers {- if container.Name == containerName ||- container.ID == containerName ||- strings.HasPrefix(container.ID, containerName) {- return &host.Containers[i], &host, nil- }- }- }-- if hostName != "" {- return nil, nil, fmt.Errorf("container '%s' not found on host '%s'", containerName, hostName)- }- return nil, nil, fmt.Errorf("container '%s' not found on any Docker host", containerName)-}--// findAgentForNode finds an agent connected to a specific Proxmox node-func (e *PulseToolExecutor) findAgentForNode(nodeName string) string {- if e.agentServer == nil {- return ""- }-- agents := e.agentServer.GetConnectedAgents()- for _, agent := range agents {- // Check if agent hostname matches node name (common setup)- if agent.Hostname == nodeName {- return agent.AgentID- }- // Also check if agent has a linked node- // Note: This requires the Host model to have LinkedNodeID populated- }-- // If no exact match, check hosts for linked agents- if e.stateProvider != nil {- state := e.stateProvider.GetState()- for _, host := range state.Hosts {- if host.LinkedNodeID != "" {- // Check if this host's linked node matches- for _, node := range state.Nodes {- if node.ID == host.LinkedNodeID && node.Name == nodeName {- // Find agent for this host- for _, agent := range agents {- if agent.Hostname == host.Hostname || agent.AgentID == host.ID {- return agent.AgentID- }- }- }- }- }- }- }-- return ""-}--// findAgentForDockerHost finds an agent connected to a Docker host-func (e *PulseToolExecutor) findAgentForDockerHost(dockerHost *models.DockerHost) string {- if e.agentServer == nil {- return ""- }-- agents := e.agentServer.GetConnectedAgents()- for _, agent := range agents {- if agent.Hostname == dockerHost.Hostname {- return agent.AgentID- }- }-- return ""-}--// formatControlApprovalNeeded formats a response for guest control needing approval-func formatControlApprovalNeeded(name string, vmid int, action, command string) string {- payload := map[string]interface{}{- "type": "control_approval_required",- "guest_name": name,- "guest_vmid": vmid,- "action": action,- "command": command,- "how_to_approve": "This action requires approval. Ask the user to confirm they want to proceed.",- "do_not_retry": true,- }- b, _ := json.Marshal(payload)- return "APPROVAL_REQUIRED: " + string(b)-}--// formatDockerApprovalNeeded formats a response for Docker control needing approval-func formatDockerApprovalNeeded(name, host, action, command string) string {- payload := map[string]interface{}{- "type": "control_approval_required",- "container_name": name,- "docker_host": host,- "action": action,- "command": command,- "how_to_approve": "This action requires approval. Ask the user to confirm they want to proceed.",- "do_not_retry": true,- }- b, _ := json.Marshal(payload)- return "APPROVAL_REQUIRED: " + string(b)-}--// formatControlSuggestion formats a command suggestion for "suggest" mode-func formatControlSuggestion(name string, vmid int, action, command, node string) string {- return fmt.Sprintf(`To %s %s (VMID %d), run this command on node %s:--%s--Copy and paste this command to execute it manually.`, action, name, vmid, node, command)-}--// formatDockerSuggestion formats a Docker command suggestion for "suggest" mode-func formatDockerSuggestion(name, host, action, command string) string {- return fmt.Sprintf(`To %s container '%s' on host %s, run:--%s--Copy and paste this command to execute it manually.`, action, name, host, command)-}diff --git a/internal/ai/mcp/tools_control.go b/internal/ai/mcp/tools_control.gonew file mode 100644index 0000000000..64a4b87604--- /dev/null+++ b/internal/ai/mcp/tools_control.go@@ -0,0 +1,596 @@+package mcp++import (+ "context"+ "encoding/json"+ "fmt"+ "strconv"+ "strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rs/zerolog/log"+)++// registerControlTools registers control tools (conditional on control level)+func (e *PulseToolExecutor) registerControlTools() {+ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_run_command",+ Description: "Execute a shell command on Pulse-managed infrastructure. By default runs on the current target, set run_on_host=true for host commands.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "command": {+ Type: "string",+ Description: "The shell command to execute",+ },+ "run_on_host": {+ Type: "boolean",+ Description: "If true, run on the host instead of inside the container/VM",+ },+ "target_host": {+ Type: "string",+ Description: "Optional hostname of the specific host/node to run the command on",+ },+ },+ Required: []string{"command"},+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeRunCommand(ctx, args)+ },+ RequireControl: true,+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_control_guest",+ Description: "Control Proxmox VMs and LXC containers. Actions: start, stop, shutdown (graceful), restart. Requires an agent on the Proxmox host.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "guest_id": {+ Type: "string",+ Description: "The VMID (e.g., '101') or name of the VM/container to control",+ },+ "action": {+ Type: "string",+ Description: "Action to perform: start, stop, shutdown, restart",+ Enum: []string{"start", "stop", "shutdown", "restart"},+ },+ "force": {+ Type: "boolean",+ Description: "If true, force stop without graceful shutdown (use with caution)",+ },+ },+ Required: []string{"guest_id", "action"},+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeControlGuest(ctx, args)+ },+ RequireControl: true,+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_control_docker",+ Description: "Control Docker containers. Actions: start, stop, restart. Requires an agent on the Docker host.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "container": {+ Type: "string",+ Description: "The container name or ID to control",+ },+ "host": {+ Type: "string",+ Description: "The Docker host name (required if multiple hosts)",+ },+ "action": {+ Type: "string",+ Description: "Action to perform: start, stop, restart",+ Enum: []string{"start", "stop", "restart"},+ },+ },+ Required: []string{"container", "action"},+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeControlDocker(ctx, args)+ },+ RequireControl: true,+ })+}++func (e *PulseToolExecutor) executeRunCommand(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {+ command, _ := args["command"].(string)+ runOnHost, _ := args["run_on_host"].(bool)+ targetHost, _ := args["target_host"].(string)++ if command == "" {+ return NewErrorResult(fmt.Errorf("command is required")), nil+ }++ // Note: Control level read_only check is now centralized in registry.Execute()++ // Check security policy+ decision := agentexec.PolicyAllow+ if e.policy != nil {+ decision = e.policy.Evaluate(command)+ if decision == agentexec.PolicyBlock {+ return NewTextResult(formatPolicyBlocked(command, "This command is blocked by security policy")), nil+ }+ }++ if e.controlLevel == ControlLevelSuggest {+ return NewTextResult(formatCommandSuggestion(command, runOnHost, targetHost)), nil+ }++ if e.controlLevel == ControlLevelControlled {+ targetType := "container"+ if runOnHost {+ targetType = "host"+ }+ approvalID := createApprovalRecord(command, targetType, e.targetID, targetHost, "Control level requires approval")+ return NewTextResult(formatApprovalNeeded(command, "Control level requires approval", approvalID)), nil+ }+ if decision == agentexec.PolicyRequireApproval && !e.isAutonomous {+ targetType := "container"+ if runOnHost {+ targetType = "host"+ }+ approvalID := createApprovalRecord(command, targetType, e.targetID, targetHost, "Security policy requires approval")+ return NewTextResult(formatApprovalNeeded(command, "Security policy requires approval", approvalID)), nil+ }++ // Execute via agent server+ if e.agentServer == nil {+ return NewErrorResult(fmt.Errorf("no agent server available")), nil+ }++ agentID := e.findAgentForCommand(runOnHost, targetHost)+ if agentID == "" {+ return NewErrorResult(fmt.Errorf("no agent available for target")), nil+ }++ targetType := "container"+ if runOnHost {+ targetType = "host"+ }++ result, err := e.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{+ Command: command,+ TargetType: targetType,+ TargetID: e.targetID,+ })+ if err != nil {+ return NewErrorResult(err), nil+ }++ output := result.Stdout+ if result.Stderr != "" {+ output += "\n" + result.Stderr+ }+ if result.ExitCode != 0 {+ output = fmt.Sprintf("Exit code %d:\n%s", result.ExitCode, output)+ }++ return NewTextResult(output), nil+}++func (e *PulseToolExecutor) executeControlGuest(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {+ guestID, _ := args["guest_id"].(string)+ action, _ := args["action"].(string)+ force, _ := args["force"].(bool)++ if guestID == "" {+ return NewErrorResult(fmt.Errorf("guest_id is required")), nil+ }+ if action == "" {+ return NewErrorResult(fmt.Errorf("action is required")), nil+ }++ validActions := map[string]bool{"start": true, "stop": true, "shutdown": true, "restart": true}+ if !validActions[action] {+ return NewErrorResult(fmt.Errorf("invalid action: %s. Use start, stop, shutdown, or restart", action)), nil+ }++ // Note: Control level read_only check is now centralized in registry.Execute()++ guest, err := e.resolveGuest(guestID)+ if err != nil {+ return NewTextResult(fmt.Sprintf("Could not find guest '%s': %v", guestID, err)), nil+ }++ // Check if guest is protected+ vmidStr := fmt.Sprintf("%d", guest.VMID)+ for _, protected := range e.protectedGuests {+ if protected == vmidStr || protected == guest.Name {+ return NewTextResult(fmt.Sprintf("Guest %s (VMID %d) is protected and cannot be controlled by AI.", guest.Name, guest.VMID)), nil+ }+ }++ // Build the command+ cmdTool := "pct"+ if guest.Type == "vm" {+ cmdTool = "qm"+ }++ var command string+ switch action {+ case "start":+ command = fmt.Sprintf("%s start %d", cmdTool, guest.VMID)+ case "stop":+ command = fmt.Sprintf("%s stop %d", cmdTool, guest.VMID)+ case "shutdown":+ command = fmt.Sprintf("%s shutdown %d", cmdTool, guest.VMID)+ case "restart":+ command = fmt.Sprintf("%s reboot %d", cmdTool, guest.VMID)+ }++ if force && action == "stop" {+ command = fmt.Sprintf("%s stop %d --skiplock", cmdTool, guest.VMID)+ }++ // Check security policy+ if e.policy != nil {+ decision := e.policy.Evaluate(command)+ if decision == agentexec.PolicyBlock {+ return NewTextResult(formatPolicyBlocked(command, "This command is blocked by security policy")), nil+ }+ if e.controlLevel == ControlLevelControlled || (decision == agentexec.PolicyRequireApproval && !e.isAutonomous) {+ approvalID := createApprovalRecord(command, guest.Type, fmt.Sprintf("%d", guest.VMID), guest.Name, fmt.Sprintf("%s guest %s", action, guest.Name))+ return NewTextResult(formatControlApprovalNeeded(guest.Name, guest.VMID, action, command, approvalID)), nil+ }+ }++ if e.controlLevel == ControlLevelSuggest {+ return NewTextResult(formatControlSuggestion(guest.Name, guest.VMID, action, command, guest.Node)), nil+ }++ if e.agentServer == nil {+ return NewErrorResult(fmt.Errorf("no agent server available")), nil+ }++ agentID := e.findAgentForNode(guest.Node)+ if agentID == "" {+ return NewTextResult(fmt.Sprintf("No agent available on node '%s'. Install Pulse Unified Agent on the Proxmox host to enable control.", guest.Node)), nil+ }++ result, err := e.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{+ Command: command,+ TargetType: "host",+ TargetID: "",+ })+ if err != nil {+ return NewErrorResult(err), nil+ }++ output := result.Stdout+ if result.Stderr != "" {+ output += "\n" + result.Stderr+ }++ if result.ExitCode == 0 {+ return NewTextResult(fmt.Sprintf("Successfully executed '%s' on %s (VMID %d).\n%s", action, guest.Name, guest.VMID, output)), nil+ }++ return NewTextResult(fmt.Sprintf("Command failed (exit code %d):\n%s", result.ExitCode, output)), nil+}++func (e *PulseToolExecutor) executeControlDocker(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {+ containerName, _ := args["container"].(string)+ hostName, _ := args["host"].(string)+ action, _ := args["action"].(string)++ if containerName == "" {+ return NewErrorResult(fmt.Errorf("container name is required")), nil+ }+ if action == "" {+ return NewErrorResult(fmt.Errorf("action is required")), nil+ }++ validActions := map[string]bool{"start": true, "stop": true, "restart": true}+ if !validActions[action] {+ return NewErrorResult(fmt.Errorf("invalid action: %s. Use start, stop, or restart", action)), nil+ }++ // Note: Control level read_only check is now centralized in registry.Execute()++ container, dockerHost, err := e.resolveDockerContainer(containerName, hostName)+ if err != nil {+ return NewTextResult(fmt.Sprintf("Could not find Docker container '%s': %v", containerName, err)), nil+ }++ command := fmt.Sprintf("docker %s %s", action, container.Name)++ if e.policy != nil {+ decision := e.policy.Evaluate(command)+ if decision == agentexec.PolicyBlock {+ return NewTextResult(formatPolicyBlocked(command, "This command is blocked by security policy")), nil+ }+ if e.controlLevel == ControlLevelControlled || (decision == agentexec.PolicyRequireApproval && !e.isAutonomous) {+ approvalID := createApprovalRecord(command, "docker", container.Name, dockerHost.Hostname, fmt.Sprintf("%s Docker container %s", action, container.Name))+ return NewTextResult(formatDockerApprovalNeeded(container.Name, dockerHost.Hostname, action, command, approvalID)), nil+ }+ }++ if e.controlLevel == ControlLevelSuggest {+ return NewTextResult(formatDockerSuggestion(container.Name, dockerHost.Hostname, action, command)), nil+ }++ if e.agentServer == nil {+ return NewErrorResult(fmt.Errorf("no agent server available")), nil+ }++ agentID := e.findAgentForDockerHost(dockerHost)+ if agentID == "" {+ return NewTextResult(fmt.Sprintf("No agent available on Docker host '%s'. Install Pulse Unified Agent on the host to enable control.", dockerHost.Hostname)), nil+ }++ result, err := e.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{+ Command: command,+ TargetType: "host",+ TargetID: "",+ })+ if err != nil {+ return NewErrorResult(err), nil+ }++ output := result.Stdout+ if result.Stderr != "" {+ output += "\n" + result.Stderr+ }++ if result.ExitCode == 0 {+ return NewTextResult(fmt.Sprintf("Successfully executed 'docker %s' on container '%s' (host: %s).\n%s", action, container.Name, dockerHost.Hostname, output)), nil+ }++ return NewTextResult(fmt.Sprintf("Command failed (exit code %d):\n%s", result.ExitCode, output)), nil+}++// Helper methods for control tools++func (e *PulseToolExecutor) findAgentForCommand(runOnHost bool, targetHost string) string {+ if e.agentServer == nil {+ return ""+ }++ agents := e.agentServer.GetConnectedAgents()+ if len(agents) == 0 {+ return ""+ }++ if targetHost != "" {+ for _, agent := range agents {+ if agent.Hostname == targetHost || agent.AgentID == targetHost {+ return agent.AgentID+ }+ }+ }++ return agents[0].AgentID+}++func (e *PulseToolExecutor) resolveGuest(guestID string) (*GuestInfo, error) {+ if e.stateProvider == nil {+ return nil, fmt.Errorf("state provider not available")+ }++ state := e.stateProvider.GetState()+ vmid, err := strconv.Atoi(guestID)++ for _, vm := range state.VMs {+ if (err == nil && vm.VMID == vmid) || vm.Name == guestID || vm.ID == guestID {+ return &GuestInfo{+ VMID: vm.VMID,+ Name: vm.Name,+ Node: vm.Node,+ Type: "vm",+ Status: vm.Status,+ Instance: vm.Instance,+ }, nil+ }+ }++ for _, ct := range state.Containers {+ if (err == nil && ct.VMID == vmid) || ct.Name == guestID || ct.ID == guestID {+ return &GuestInfo{+ VMID: ct.VMID,+ Name: ct.Name,+ Node: ct.Node,+ Type: "lxc",+ Status: ct.Status,+ Instance: ct.Instance,+ }, nil+ }+ }++ return nil, fmt.Errorf("no VM or container found with ID or name '%s'", guestID)+}++func (e *PulseToolExecutor) resolveDockerContainer(containerName, hostName string) (*models.DockerContainer, *models.DockerHost, error) {+ if e.stateProvider == nil {+ return nil, nil, fmt.Errorf("state provider not available")+ }++ state := e.stateProvider.GetState()++ for _, host := range state.DockerHosts {+ if hostName != "" && host.Hostname != hostName && host.DisplayName != hostName {+ continue+ }++ for i, container := range host.Containers {+ if container.Name == containerName ||+ container.ID == containerName ||+ strings.HasPrefix(container.ID, containerName) {+ return &host.Containers[i], &host, nil+ }+ }+ }++ if hostName != "" {+ return nil, nil, fmt.Errorf("container '%s' not found on host '%s'", containerName, hostName)+ }+ return nil, nil, fmt.Errorf("container '%s' not found on any Docker host", containerName)+}++func (e *PulseToolExecutor) findAgentForNode(nodeName string) string {+ if e.agentServer == nil {+ return ""+ }++ agents := e.agentServer.GetConnectedAgents()+ for _, agent := range agents {+ if agent.Hostname == nodeName {+ return agent.AgentID+ }+ }++ if e.stateProvider != nil {+ state := e.stateProvider.GetState()+ for _, host := range state.Hosts {+ if host.LinkedNodeID != "" {+ for _, node := range state.Nodes {+ if node.ID == host.LinkedNodeID && node.Name == nodeName {+ for _, agent := range agents {+ if agent.Hostname == host.Hostname || agent.AgentID == host.ID {+ return agent.AgentID+ }+ }+ }+ }+ }+ }+ }++ return ""+}++func (e *PulseToolExecutor) findAgentForDockerHost(dockerHost *models.DockerHost) string {+ if e.agentServer == nil {+ return ""+ }++ agents := e.agentServer.GetConnectedAgents()+ for _, agent := range agents {+ if agent.Hostname == dockerHost.Hostname {+ return agent.AgentID+ }+ }++ return ""+}++// createApprovalRecord creates an approval record in the store and returns the approval ID.+// Returns empty string if store is not available (approvals will still work, just without persistence).+func createApprovalRecord(command, targetType, targetID, targetName, context string) string {+ store := approval.GetStore()+ if store == nil {+ log.Debug().Msg("Approval store not available, approval will not be persisted")+ return ""+ }++ req := &approval.ApprovalRequest{+ Command: command,+ TargetType: targetType,+ TargetID: targetID,+ TargetName: targetName,+ Context: context,+ }++ if err := store.CreateApproval(req); err != nil {+ log.Warn().Err(err).Msg("Failed to create approval record")+ return ""+ }++ log.Debug().Str("approval_id", req.ID).Str("command", command).Msg("Created approval record")+ return req.ID+}++// Formatting helpers for control tools++func formatApprovalNeeded(command, reason, approvalID string) string {+ payload := map[string]interface{}{+ "type": "approval_required",+ "approval_id": approvalID,+ "command": command,+ "reason": reason,+ "how_to_approve": "Click the approval button in the chat to execute this command.",+ "do_not_retry": true,+ }+ b, _ := json.Marshal(payload)+ return "APPROVAL_REQUIRED: " + string(b)+}++func formatPolicyBlocked(command, reason string) string {+ payload := map[string]interface{}{+ "type": "policy_blocked",+ "command": command,+ "reason": reason,+ "do_not_retry": true,+ }+ b, _ := json.Marshal(payload)+ return "POLICY_BLOCKED: " + string(b)+}++func formatCommandSuggestion(command string, runOnHost bool, targetHost string) string {+ target := "current target"+ if runOnHost {+ target = "host"+ }+ if strings.TrimSpace(targetHost) != "" {+ target = fmt.Sprintf("host %s", targetHost)+ }+ return fmt.Sprintf("Suggested command for %s:\n%s", target, command)+}++func formatControlApprovalNeeded(name string, vmid int, action, command, approvalID string) string {+ payload := map[string]interface{}{+ "type": "approval_required",+ "approval_id": approvalID,+ "guest_name": name,+ "guest_vmid": vmid,+ "action": action,+ "command": command,+ "how_to_approve": "Click the approval button in the chat to execute this action.",+ "do_not_retry": true,+ }+ b, _ := json.Marshal(payload)+ return "APPROVAL_REQUIRED: " + string(b)+}++func formatDockerApprovalNeeded(name, host, action, command, approvalID string) string {+ payload := map[string]interface{}{+ "type": "approval_required",+ "approval_id": approvalID,+ "container_name": name,+ "docker_host": host,+ "action": action,+ "command": command,+ "how_to_approve": "Click the approval button in the chat to execute this action.",+ "do_not_retry": true,+ }+ b, _ := json.Marshal(payload)+ return "APPROVAL_REQUIRED: " + string(b)+}++func formatControlSuggestion(name string, vmid int, action, command, node string) string {+ return fmt.Sprintf(`To %s %s (VMID %d), run this command on node %s:++%s++Copy and paste this command to execute it manually.`, action, name, vmid, node, command)+}++func formatDockerSuggestion(name, host, action, command string) string {+ return fmt.Sprintf(`To %s container '%s' on host %s, run:++%s++Copy and paste this command to execute it manually.`, action, name, host, command)+}diff --git a/internal/ai/mcp/tools_infrastructure.go b/internal/ai/mcp/tools_infrastructure.gonew file mode 100644index 0000000000..e81a1aac0b--- /dev/null+++ b/internal/ai/mcp/tools_infrastructure.go@@ -0,0 +1,339 @@+package mcp++import (+ "context"+)++// registerInfrastructureTools registers infrastructure context tools (backup, storage, disk health)+func (e *PulseToolExecutor) registerInfrastructureTools() {+ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_list_backups",+ Description: "List backup status for VMs and containers. Shows last backup times, backup jobs, and identifies resources without recent backups.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "resource_id": {+ Type: "string",+ Description: "Optional: filter by specific VM or container ID",+ },+ "limit": {+ Type: "integer",+ Description: "Maximum number of results (default: 100)",+ },+ "offset": {+ Type: "integer",+ Description: "Number of results to skip",+ },+ },+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeListBackups(ctx, args)+ },+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_list_storage",+ Description: "List storage pool information including usage, ZFS pool health, and Ceph cluster status.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "storage_id": {+ Type: "string",+ Description: "Optional: specific storage ID for detailed info",+ },+ "limit": {+ Type: "integer",+ Description: "Maximum number of results (default: 100)",+ },+ "offset": {+ Type: "integer",+ Description: "Number of results to skip",+ },+ },+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeListStorage(ctx, args)+ },+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_get_disk_health",+ Description: "Get disk health information including SMART data, RAID array status, and Ceph cluster health from host agents.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{},+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeGetDiskHealth(ctx, args)+ },+ })+}++func (e *PulseToolExecutor) executeListBackups(_ context.Context, args map[string]interface{}) (CallToolResult, error) {+ resourceID, _ := args["resource_id"].(string)+ limit := intArg(args, "limit", 100)+ offset := intArg(args, "offset", 0)++ if e.backupProvider == nil {+ return NewTextResult("Backup information not available."), nil+ }++ backups := e.backupProvider.GetBackups()+ pbsInstances := e.backupProvider.GetPBSInstances()++ response := BackupsResponse{}++ // PBS Backups+ count := 0+ for _, b := range backups.PBS {+ if resourceID != "" && b.VMID != resourceID {+ continue+ }+ if count < offset {+ count+++ continue+ }+ if len(response.PBS) >= limit {+ break+ }+ response.PBS = append(response.PBS, PBSBackupSummary{+ VMID: b.VMID,+ BackupType: b.BackupType,+ BackupTime: b.BackupTime,+ Instance: b.Instance,+ Datastore: b.Datastore,+ SizeGB: float64(b.Size) / (1024 * 1024 * 1024),+ Verified: b.Verified,+ Protected: b.Protected,+ })+ count+++ }++ // PVE Backups+ count = 0+ for _, b := range backups.PVE.StorageBackups {+ if resourceID != "" && string(rune(b.VMID)) != resourceID {+ continue+ }+ if count < offset {+ count+++ continue+ }+ if len(response.PVE) >= limit {+ break+ }+ response.PVE = append(response.PVE, PVEBackupSummary{+ VMID: b.VMID,+ BackupTime: b.Time,+ SizeGB: float64(b.Size) / (1024 * 1024 * 1024),+ Storage: b.Storage,+ })+ count+++ }++ // PBS Servers+ for _, pbs := range pbsInstances {+ server := PBSServerSummary{+ Name: pbs.Name,+ Host: pbs.Host,+ Status: pbs.Status,+ }+ for _, ds := range pbs.Datastores {+ server.Datastores = append(server.Datastores, DatastoreSummary{+ Name: ds.Name,+ UsagePercent: ds.Usage * 100,+ FreeGB: float64(ds.Free) / (1024 * 1024 * 1024),+ })+ }+ response.PBSServers = append(response.PBSServers, server)+ }++ // Recent tasks+ for _, t := range backups.PVE.BackupTasks {+ if len(response.RecentTasks) >= 20 {+ break+ }+ response.RecentTasks = append(response.RecentTasks, BackupTaskSummary{+ VMID: t.VMID,+ Node: t.Node,+ Status: t.Status,+ StartTime: t.StartTime,+ })+ }++ // Ensure non-nil slices+ if response.PBS == nil {+ response.PBS = []PBSBackupSummary{}+ }+ if response.PVE == nil {+ response.PVE = []PVEBackupSummary{}+ }+ if response.PBSServers == nil {+ response.PBSServers = []PBSServerSummary{}+ }+ if response.RecentTasks == nil {+ response.RecentTasks = []BackupTaskSummary{}+ }++ return NewJSONResult(response), nil+}++func (e *PulseToolExecutor) executeListStorage(_ context.Context, args map[string]interface{}) (CallToolResult, error) {+ storageID, _ := args["storage_id"].(string)+ limit := intArg(args, "limit", 100)+ offset := intArg(args, "offset", 0)++ if e.storageProvider == nil {+ return NewTextResult("Storage information not available."), nil+ }++ storage := e.storageProvider.GetStorage()+ cephClusters := e.storageProvider.GetCephClusters()++ response := StorageResponse{}++ // Storage pools+ count := 0+ for _, s := range storage {+ if storageID != "" && s.ID != storageID && s.Name != storageID {+ continue+ }+ if count < offset {+ count+++ continue+ }+ if len(response.Pools) >= limit {+ break+ }++ pool := StoragePoolSummary{+ ID: s.ID,+ Name: s.Name,+ Type: s.Type,+ Status: s.Status,+ UsagePercent: s.Usage * 100,+ UsedGB: float64(s.Used) / (1024 * 1024 * 1024),+ TotalGB: float64(s.Total) / (1024 * 1024 * 1024),+ FreeGB: float64(s.Free) / (1024 * 1024 * 1024),+ Content: s.Content,+ Shared: s.Shared,+ }++ if s.ZFSPool != nil {+ pool.ZFS = &ZFSPoolSummary{+ Name: s.ZFSPool.Name,+ State: s.ZFSPool.State,+ ReadErrors: s.ZFSPool.ReadErrors,+ WriteErrors: s.ZFSPool.WriteErrors,+ ChecksumErrors: s.ZFSPool.ChecksumErrors,+ Scan: s.ZFSPool.Scan,+ }+ }++ response.Pools = append(response.Pools, pool)+ count+++ }++ // Ceph clusters+ for _, c := range cephClusters {+ response.CephClusters = append(response.CephClusters, CephClusterSummary{+ Name: c.Name,+ Health: c.Health,+ HealthMessage: c.HealthMessage,+ UsagePercent: c.UsagePercent,+ UsedTB: float64(c.UsedBytes) / (1024 * 1024 * 1024 * 1024),+ TotalTB: float64(c.TotalBytes) / (1024 * 1024 * 1024 * 1024),+ NumOSDs: c.NumOSDs,+ NumOSDsUp: c.NumOSDsUp,+ NumOSDsIn: c.NumOSDsIn,+ NumMons: c.NumMons,+ NumMgrs: c.NumMgrs,+ })+ }++ // Ensure non-nil slices+ if response.Pools == nil {+ response.Pools = []StoragePoolSummary{}+ }+ if response.CephClusters == nil {+ response.CephClusters = []CephClusterSummary{}+ }++ return NewJSONResult(response), nil+}++func (e *PulseToolExecutor) executeGetDiskHealth(_ context.Context, _ map[string]interface{}) (CallToolResult, error) {+ if e.diskHealthProvider == nil && e.storageProvider == nil {+ return NewTextResult("Disk health information not available."), nil+ }++ response := DiskHealthResponse{+ Hosts: []HostDiskHealth{},+ }++ // SMART and RAID data from host agents+ if e.diskHealthProvider != nil {+ hosts := e.diskHealthProvider.GetHosts()+ for _, host := range hosts {+ hostHealth := HostDiskHealth{+ Hostname: host.Hostname,+ }++ // SMART data+ for _, disk := range host.Sensors.SMART {+ hostHealth.SMART = append(hostHealth.SMART, SMARTDiskSummary{+ Device: disk.Device,+ Model: disk.Model,+ Health: disk.Health,+ Temperature: disk.Temperature,+ })+ }++ // RAID arrays+ for _, raid := range host.RAID {+ hostHealth.RAID = append(hostHealth.RAID, RAIDArraySummary{+ Device: raid.Device,+ Level: raid.Level,+ State: raid.State,+ ActiveDevices: raid.ActiveDevices,+ WorkingDevices: raid.WorkingDevices,+ FailedDevices: raid.FailedDevices,+ SpareDevices: raid.SpareDevices,+ RebuildPercent: raid.RebuildPercent,+ })+ }++ // Ceph from agent+ if host.Ceph != nil {+ hostHealth.Ceph = &CephStatusSummary{+ Health: host.Ceph.Health.Status,+ NumOSDs: host.Ceph.OSDMap.NumOSDs,+ NumOSDsUp: host.Ceph.OSDMap.NumUp,+ NumOSDsIn: host.Ceph.OSDMap.NumIn,+ NumPGs: host.Ceph.PGMap.NumPGs,+ UsagePercent: host.Ceph.PGMap.UsagePercent,+ }+ }++ // Only add if there's data+ if len(hostHealth.SMART) > 0 || len(hostHealth.RAID) > 0 || hostHealth.Ceph != nil {+ // Ensure non-nil slices+ if hostHealth.SMART == nil {+ hostHealth.SMART = []SMARTDiskSummary{}+ }+ if hostHealth.RAID == nil {+ hostHealth.RAID = []RAIDArraySummary{}+ }+ response.Hosts = append(response.Hosts, hostHealth)+ }+ }+ }++ return NewJSONResult(response), nil+}diff --git a/internal/ai/mcp/tools_patrol.go b/internal/ai/mcp/tools_patrol.gonew file mode 100644index 0000000000..f5396afe21--- /dev/null+++ b/internal/ai/mcp/tools_patrol.go@@ -0,0 +1,454 @@+package mcp++import (+ "context"+ "fmt"+ "time"+)++// registerPatrolTools registers patrol context tools (metrics, baselines, patterns, alerts, findings)+func (e *PulseToolExecutor) registerPatrolTools() {+ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_get_metrics",+ Description: "Get historical metrics (CPU, memory, disk) for resources over 24 hours or 7 days. Use this to understand trends and detect anomalies.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "period": {+ Type: "string",+ Description: "Time period: '24h' for last 24 hours, '7d' for last 7 days",+ Enum: []string{"24h", "7d"},+ },+ "resource_id": {+ Type: "string",+ Description: "Optional: specific resource ID. If omitted, returns summary for all resources.",+ },+ },+ Required: []string{"period"},+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeGetMetrics(ctx, args)+ },+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_get_baselines",+ Description: "Get learned baselines for resources. Baselines represent 'normal' behavior and help detect anomalies.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "resource_id": {+ Type: "string",+ Description: "Optional: specific resource ID. If omitted, returns all baselines.",+ },+ },+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeGetBaselines(ctx, args)+ },+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_get_patterns",+ Description: "Get detected operational patterns and predictions. Includes recurring spikes, growth trends, and predicted issues.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{},+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeGetPatterns(ctx, args)+ },+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_list_alerts",+ Description: "List all currently active alerts. Use to understand current problems in the infrastructure.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "severity": {+ Type: "string",+ Description: "Filter by severity: 'critical', 'warning', 'info'. Omit for all.",+ Enum: []string{"critical", "warning", "info"},+ },+ "limit": {+ Type: "integer",+ Description: "Maximum number of results (default: 100)",+ },+ "offset": {+ Type: "integer",+ Description: "Number of results to skip",+ },+ },+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeListAlerts(ctx, args)+ },+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_list_findings",+ Description: "List AI patrol findings. Active findings are current issues; dismissed findings show user feedback.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "include_dismissed": {+ Type: "boolean",+ Description: "If true, also include dismissed findings",+ },+ "severity": {+ Type: "string",+ Description: "Filter by severity: 'critical', 'warning', 'info'. Omit for all.",+ Enum: []string{"critical", "warning", "info"},+ },+ "limit": {+ Type: "integer",+ Description: "Maximum number of results (default: 100)",+ },+ "offset": {+ Type: "integer",+ Description: "Number of results to skip",+ },+ },+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeListFindings(ctx, args)+ },+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_resolve_finding",+ Description: "Mark an AI patrol finding as resolved after fixing the issue.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "finding_id": {+ Type: "string",+ Description: "The finding ID to resolve",+ },+ "resolution_note": {+ Type: "string",+ Description: "Brief description of how the issue was resolved",+ },+ },+ Required: []string{"finding_id", "resolution_note"},+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeResolveFinding(ctx, args)+ },+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_dismiss_finding",+ Description: "Dismiss an AI patrol finding as not an issue or expected behavior.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "finding_id": {+ Type: "string",+ Description: "The finding ID to dismiss",+ },+ "reason": {+ Type: "string",+ Description: "Why the finding is being dismissed",+ Enum: []string{"not_an_issue", "expected_behavior", "will_fix_later"},+ },+ "note": {+ Type: "string",+ Description: "Explanation of why this is being dismissed",+ },+ },+ Required: []string{"finding_id", "reason", "note"},+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeDismissFinding(ctx, args)+ },+ })+}++func (e *PulseToolExecutor) executeGetMetrics(_ context.Context, args map[string]interface{}) (CallToolResult, error) {+ period, _ := args["period"].(string)+ resourceID, _ := args["resource_id"].(string)++ if e.metricsHistory == nil {+ return NewTextResult("Metrics history not available. The system may still be collecting data."), nil+ }++ var duration time.Duration+ switch period {+ case "24h":+ duration = 24 * time.Hour+ case "7d":+ duration = 7 * 24 * time.Hour+ default:+ duration = 24 * time.Hour+ period = "24h"+ }++ response := MetricsResponse{+ Period: period,+ }++ if resourceID != "" {+ response.ResourceID = resourceID+ metrics, err := e.metricsHistory.GetResourceMetrics(resourceID, duration)+ if err != nil {+ return NewErrorResult(err), nil+ }+ response.Points = metrics+ } else {+ summary, err := e.metricsHistory.GetAllMetricsSummary(duration)+ if err != nil {+ return NewErrorResult(err), nil+ }+ response.Summary = summary+ }++ return NewJSONResult(response), nil+}++func (e *PulseToolExecutor) executeGetBaselines(_ context.Context, args map[string]interface{}) (CallToolResult, error) {+ resourceID, _ := args["resource_id"].(string)++ if e.baselineProvider == nil {+ return NewTextResult("Baseline data not available. The system needs time to learn normal behavior patterns."), nil+ }++ response := BaselinesResponse{+ Baselines: make(map[string]map[string]*MetricBaseline),+ }++ if resourceID != "" {+ response.ResourceID = resourceID+ cpuBaseline := e.baselineProvider.GetBaseline(resourceID, "cpu")+ memBaseline := e.baselineProvider.GetBaseline(resourceID, "memory")++ if cpuBaseline != nil || memBaseline != nil {+ response.Baselines[resourceID] = make(map[string]*MetricBaseline)+ if cpuBaseline != nil {+ response.Baselines[resourceID]["cpu"] = cpuBaseline+ }+ if memBaseline != nil {+ response.Baselines[resourceID]["memory"] = memBaseline+ }+ }+ } else {+ response.Baselines = e.baselineProvider.GetAllBaselines()+ }++ return NewJSONResult(response), nil+}++func (e *PulseToolExecutor) executeGetPatterns(_ context.Context, _ map[string]interface{}) (CallToolResult, error) {+ if e.patternProvider == nil {+ return NewTextResult("Pattern detection not available. The system needs more historical data."), nil+ }++ response := PatternsResponse{+ Patterns: e.patternProvider.GetPatterns(),+ Predictions: e.patternProvider.GetPredictions(),+ }++ // Ensure non-nil slices for clean JSON+ if response.Patterns == nil {+ response.Patterns = []Pattern{}+ }+ if response.Predictions == nil {+ response.Predictions = []Prediction{}+ }++ return NewJSONResult(response), nil+}++func (e *PulseToolExecutor) executeListAlerts(_ context.Context, args map[string]interface{}) (CallToolResult, error) {+ if e.alertProvider == nil {+ return NewTextResult("Alert data not available."), nil+ }++ severityFilter, _ := args["severity"].(string)+ limit := intArg(args, "limit", 100)+ offset := intArg(args, "offset", 0)++ allAlerts := e.alertProvider.GetActiveAlerts()++ var filtered []ActiveAlert+ for i, a := range allAlerts {+ if i < offset {+ continue+ }+ if len(filtered) >= limit {+ break+ }+ if severityFilter != "" && a.Severity != severityFilter {+ continue+ }+ filtered = append(filtered, a)+ }++ if filtered == nil {+ filtered = []ActiveAlert{}+ }++ response := AlertsResponse{+ Alerts: filtered,+ Count: len(filtered),+ }++ if offset > 0 || len(allAlerts) > limit {+ response.Pagination = &PaginationInfo{+ Total: len(allAlerts),+ Limit: limit,+ Offset: offset,+ }+ }++ return NewJSONResult(response), nil+}++func (e *PulseToolExecutor) executeListFindings(_ context.Context, args map[string]interface{}) (CallToolResult, error) {+ includeDismissed, _ := args["include_dismissed"].(bool)+ severityFilter, _ := args["severity"].(string)+ limit := intArg(args, "limit", 100)+ offset := intArg(args, "offset", 0)++ if e.findingsProvider == nil {+ return NewTextResult("Patrol findings not available. AI Patrol may not be running."), nil+ }++ allActive := e.findingsProvider.GetActiveFindings()+ var allDismissed []Finding+ if includeDismissed {+ allDismissed = e.findingsProvider.GetDismissedFindings()+ }++ // Filter active+ var active []Finding+ for i, f := range allActive {+ if i < offset {+ continue+ }+ if len(active) >= limit {+ break+ }+ if severityFilter != "" && f.Severity != severityFilter {+ continue+ }+ active = append(active, f)+ }++ // Filter dismissed+ var dismissed []Finding+ if includeDismissed {+ for i, f := range allDismissed {+ if i < offset {+ continue+ }+ if len(dismissed) >= limit {+ break+ }+ if severityFilter != "" && f.Severity != severityFilter {+ continue+ }+ dismissed = append(dismissed, f)+ }+ }++ if active == nil {+ active = []Finding{}+ }+ if dismissed == nil {+ dismissed = []Finding{}+ }++ response := FindingsResponse{+ Active: active,+ Dismissed: dismissed,+ Counts: FindingCounts{+ Active: len(allActive),+ Dismissed: len(allDismissed),+ },+ }++ if offset > 0 || len(allActive) > limit || len(allDismissed) > limit {+ response.Pagination = &PaginationInfo{+ Total: len(allActive) + len(allDismissed),+ Limit: limit,+ Offset: offset,+ }+ }++ return NewJSONResult(response), nil+}++func (e *PulseToolExecutor) executeResolveFinding(_ context.Context, args map[string]interface{}) (CallToolResult, error) {+ findingID, _ := args["finding_id"].(string)+ resolutionNote, _ := args["resolution_note"].(string)++ if findingID == "" {+ return NewErrorResult(fmt.Errorf("finding_id is required")), nil+ }+ if resolutionNote == "" {+ return NewErrorResult(fmt.Errorf("resolution_note is required")), nil+ }++ if e.findingsManager == nil {+ return NewTextResult("Findings manager not available."), nil+ }++ if err := e.findingsManager.ResolveFinding(findingID, resolutionNote); err != nil {+ return NewErrorResult(err), nil+ }++ return NewJSONResult(map[string]interface{}{+ "success": true,+ "finding_id": findingID,+ "action": "resolved",+ "resolution_note": resolutionNote,+ }), nil+}++func (e *PulseToolExecutor) executeDismissFinding(_ context.Context, args map[string]interface{}) (CallToolResult, error) {+ findingID, _ := args["finding_id"].(string)+ reason, _ := args["reason"].(string)+ note, _ := args["note"].(string)++ if findingID == "" {+ return NewErrorResult(fmt.Errorf("finding_id is required")), nil+ }+ if reason == "" {+ return NewErrorResult(fmt.Errorf("reason is required")), nil+ }+ if note == "" {+ return NewErrorResult(fmt.Errorf("note is required")), nil+ }++ if e.findingsManager == nil {+ return NewTextResult("Findings manager not available."), nil+ }++ if err := e.findingsManager.DismissFinding(findingID, reason, note); err != nil {+ return NewErrorResult(err), nil+ }++ return NewJSONResult(map[string]interface{}{+ "success": true,+ "finding_id": findingID,+ "action": "dismissed",+ "reason": reason,+ "note": note,+ }), nil+}diff --git a/internal/ai/mcp/tools_profiles.go b/internal/ai/mcp/tools_profiles.gonew file mode 100644index 0000000000..d0104bb966--- /dev/null+++ b/internal/ai/mcp/tools_profiles.go@@ -0,0 +1,368 @@+package mcp++import (+ "context"+ "fmt"+ "sort"+ "strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++// registerProfileTools registers agent profile tools+func (e *PulseToolExecutor) registerProfileTools() {+ // Read-only profile tool (always available)+ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_get_agent_scope",+ Description: "Get the current unified agent scope (profile assignment and settings).",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "agent_id": {+ Type: "string",+ Description: "Unified agent ID (preferred if known)",+ },+ "hostname": {+ Type: "string",+ Description: "Hostname or display name to resolve the agent ID",+ },+ },+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeGetAgentScope(ctx, args)+ },+ RequireControl: false,+ })++ // Unified write tool for profile management+ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_set_agent_scope",+ Description: "Update a unified agent's scope via profile settings or assign an existing profile. Use this to enable/disable modules like Docker, Kubernetes, or Proxmox.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "agent_id": {+ Type: "string",+ Description: "Unified agent ID (preferred if known)",+ },+ "hostname": {+ Type: "string",+ Description: "Hostname or display name to resolve the agent ID",+ },+ "profile_id": {+ Type: "string",+ Description: "Assign an existing profile ID (optional; omit to use settings)",+ },+ "settings": {+ Type: "object",+ Description: "Profile settings (e.g., enable_host, enable_docker, enable_kubernetes, enable_proxmox, proxmox_type, docker_runtime, disable_auto_update, disable_docker_update_checks, kube_include_all_pods, kube_include_all_deployments, log_level, interval, report_ip, disable_ceph)",+ },+ },+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeSetAgentScope(ctx, args)+ },+ RequireControl: true,+ })+}++func (e *PulseToolExecutor) executeGetAgentScope(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {+ agentID, _ := args["agent_id"].(string)+ hostname, _ := args["hostname"].(string)+ agentID = strings.TrimSpace(agentID)+ hostname = strings.TrimSpace(hostname)++ if agentID == "" && hostname == "" {+ return NewErrorResult(fmt.Errorf("agent_id or hostname is required")), nil+ }++ agentLabel := agentID+ if agentID == "" {+ if e.stateProvider == nil {+ return NewErrorResult(fmt.Errorf("state provider not available to resolve hostname")), nil+ }+ resolvedID, resolvedLabel := resolveAgentFromHostname(e.stateProvider.GetState(), hostname)+ if resolvedID == "" {+ return NewJSONResult(map[string]interface{}{+ "error": "not_found",+ "hostname": hostname,+ "message": fmt.Sprintf("No agent found for hostname '%s'", hostname),+ }), nil+ }+ agentID = resolvedID+ agentLabel = resolvedLabel+ } else if e.stateProvider != nil {+ if resolvedLabel := resolveAgentLabel(e.stateProvider.GetState(), agentID); resolvedLabel != "" {+ agentLabel = resolvedLabel+ }+ }++ response := AgentScopeResponse{+ AgentID: agentID,+ AgentLabel: agentLabel,+ }++ // Get profile info+ if e.agentProfileManager != nil {+ scope, err := e.agentProfileManager.GetAgentScope(ctx, agentID)+ if err != nil {+ return NewJSONResult(map[string]interface{}{+ "error": "failed_to_load",+ "agent_id": agentID,+ "agent_label": agentLabel,+ "message": fmt.Sprintf("Failed to load agent scope: %v", err),+ }), nil+ }+ if scope != nil {+ response.ProfileID = scope.ProfileID+ response.ProfileName = scope.ProfileName+ response.ProfileVersion = scope.ProfileVersion+ response.Settings = scope.Settings+ }+ }++ // Get observed modules+ if e.stateProvider != nil {+ observed, commandsEnabled := detectAgentModules(e.stateProvider.GetState(), agentID)+ response.ObservedModules = observed+ response.CommandsEnabled = commandsEnabled+ }++ return NewJSONResult(response), nil+}++func (e *PulseToolExecutor) executeSetAgentScope(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {+ if e.agentProfileManager == nil {+ return NewTextResult("Agent scope management is not available."), nil+ }++ // Note: Control level check is now centralized in registry.Execute()++ agentID, _ := args["agent_id"].(string)+ hostname, _ := args["hostname"].(string)+ profileID, _ := args["profile_id"].(string)++ agentID = strings.TrimSpace(agentID)+ hostname = strings.TrimSpace(hostname)+ profileID = strings.TrimSpace(profileID)++ settings := map[string]interface{}{}+ if rawSettings, ok := args["settings"].(map[string]interface{}); ok {+ for key, value := range rawSettings {+ if value != nil {+ settings[key] = value+ }+ }+ }++ if agentID == "" && hostname == "" {+ return NewErrorResult(fmt.Errorf("agent_id or hostname is required")), nil+ }++ agentLabel := agentID+ if agentID == "" {+ if e.stateProvider == nil {+ return NewErrorResult(fmt.Errorf("state provider not available to resolve hostname")), nil+ }+ resolvedID, resolvedLabel := resolveAgentFromHostname(e.stateProvider.GetState(), hostname)+ if resolvedID == "" {+ return NewJSONResult(map[string]interface{}{+ "error": "not_found",+ "hostname": hostname,+ "message": fmt.Sprintf("No agent found for hostname '%s'", hostname),+ }), nil+ }+ agentID = resolvedID+ agentLabel = resolvedLabel+ } else if e.stateProvider != nil {+ if resolvedLabel := resolveAgentLabel(e.stateProvider.GetState(), agentID); resolvedLabel != "" {+ agentLabel = resolvedLabel+ }+ }++ if profileID != "" && len(settings) > 0 {+ return NewErrorResult(fmt.Errorf("use either profile_id or settings, not both")), nil+ }++ if e.controlLevel == ControlLevelSuggest {+ if profileID != "" {+ return NewJSONResult(map[string]interface{}{+ "type": "suggestion",+ "action": "assign_profile",+ "agent_id": agentID,+ "agent_label": agentLabel,+ "profile_id": profileID,+ "message": fmt.Sprintf("Suggestion: assign profile %s to agent %s.", profileID, agentLabel),+ }), nil+ }+ if len(settings) == 0 {+ return NewErrorResult(fmt.Errorf("settings are required when profile_id is not provided")), nil+ }+ return NewJSONResult(map[string]interface{}{+ "type": "suggestion",+ "action": "apply_settings",+ "agent_id": agentID,+ "agent_label": agentLabel,+ "settings": settings,+ "message": fmt.Sprintf("Suggestion: apply agent scope to %s with settings: %s", agentLabel, formatSettingsSummary(settings)),+ }), nil+ }++ if profileID != "" {+ profileName, err := e.agentProfileManager.AssignProfile(ctx, agentID, profileID)+ if err != nil {+ return NewErrorResult(err), nil+ }+ return NewJSONResult(map[string]interface{}{+ "success": true,+ "action": "assigned",+ "agent_id": agentID,+ "agent_label": agentLabel,+ "profile_id": profileID,+ "profile_name": profileName,+ "message": fmt.Sprintf("Assigned profile '%s' to agent %s. Restart the agent to apply changes.", profileName, agentLabel),+ }), nil+ }++ if len(settings) == 0 {+ return NewErrorResult(fmt.Errorf("settings are required when profile_id is not provided")), nil+ }++ newProfileID, profileName, created, err := e.agentProfileManager.ApplyAgentScope(ctx, agentID, agentLabel, settings)+ if err != nil {+ return NewErrorResult(err), nil+ }++ action := "updated"+ if created {+ action = "created"+ }++ return NewJSONResult(map[string]interface{}{+ "success": true,+ "action": action,+ "agent_id": agentID,+ "agent_label": agentLabel,+ "profile_id": newProfileID,+ "profile_name": profileName,+ "settings": settings,+ "message": fmt.Sprintf("%s profile '%s' and assigned to agent %s. Restart the agent to apply changes.", strings.Title(action), profileName, agentLabel),+ }), nil+}++// Helper functions for profile tools++func resolveAgentFromHostname(state models.StateSnapshot, hostname string) (string, string) {+ needle := strings.TrimSpace(hostname)+ if needle == "" {+ return "", ""+ }+ for _, host := range state.Hosts {+ if strings.EqualFold(host.Hostname, needle) || strings.EqualFold(host.DisplayName, needle) || strings.EqualFold(host.ID, needle) {+ label := firstNonEmpty(host.DisplayName, host.Hostname, host.ID)+ return host.ID, label+ }+ }+ for _, host := range state.DockerHosts {+ if strings.EqualFold(host.Hostname, needle) || strings.EqualFold(host.DisplayName, needle) || strings.EqualFold(host.CustomDisplayName, needle) || strings.EqualFold(host.ID, needle) {+ label := firstNonEmpty(host.CustomDisplayName, host.DisplayName, host.Hostname, host.ID)+ agentID := strings.TrimSpace(host.AgentID)+ if agentID == "" {+ agentID = host.ID+ }+ return agentID, label+ }+ }+ return "", ""+}++func resolveAgentLabel(state models.StateSnapshot, agentID string) string {+ needle := strings.TrimSpace(agentID)+ if needle == "" {+ return ""+ }+ for _, host := range state.Hosts {+ if strings.EqualFold(host.ID, needle) {+ return firstNonEmpty(host.DisplayName, host.Hostname, host.ID)+ }+ }+ for _, host := range state.DockerHosts {+ if strings.EqualFold(host.AgentID, needle) || strings.EqualFold(host.ID, needle) {+ return firstNonEmpty(host.CustomDisplayName, host.DisplayName, host.Hostname, host.ID)+ }+ }+ return ""+}++func firstNonEmpty(values ...string) string {+ for _, value := range values {+ value = strings.TrimSpace(value)+ if value != "" {+ return value+ }+ }+ return ""+}++func formatSettingsSummary(settings map[string]interface{}) string {+ if len(settings) == 0 {+ return "none"+ }+ keys := make([]string, 0, len(settings))+ for key := range settings {+ keys = append(keys, key)+ }+ sort.Strings(keys)+ parts := make([]string, 0, len(keys))+ for _, key := range keys {+ parts = append(parts, fmt.Sprintf("%s=%v", key, settings[key]))+ }+ return strings.Join(parts, ", ")+}++func detectAgentModules(state models.StateSnapshot, agentID string) ([]string, *bool) {+ agentID = strings.TrimSpace(agentID)+ if agentID == "" {+ return nil, nil+ }++ var modules []string+ var commandsEnabled *bool++ for _, host := range state.Hosts {+ if strings.EqualFold(host.ID, agentID) {+ modules = append(modules, "host")+ val := host.CommandsEnabled+ commandsEnabled = &val+ if host.LinkedNodeID != "" {+ modules = append(modules, "proxmox")+ }+ break+ }+ }++ for _, dockerHost := range state.DockerHosts {+ if strings.EqualFold(dockerHost.AgentID, agentID) || strings.EqualFold(dockerHost.ID, agentID) {+ modules = append(modules, "docker")+ break+ }+ }++ for _, cluster := range state.KubernetesClusters {+ if strings.EqualFold(cluster.AgentID, agentID) {+ modules = append(modules, "kubernetes")+ break+ }+ }++ if len(modules) == 0 {+ return nil, commandsEnabled+ }++ sort.Strings(modules)+ return modules, commandsEnabled+}diff --git a/internal/ai/mcp/tools_query.go b/internal/ai/mcp/tools_query.gonew file mode 100644index 0000000000..f4c4efecaa--- /dev/null+++ b/internal/ai/mcp/tools_query.go@@ -0,0 +1,534 @@+package mcp++import (+ "context"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"+)++// registerQueryTools registers infrastructure query tools+func (e *PulseToolExecutor) registerQueryTools() {+ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_get_capabilities",+ Description: "Get server capabilities, available features, and current configuration. Call this first to understand what tools and data are available.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{},+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeGetCapabilities(ctx)+ },+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_get_url_content",+ Description: "Fetch content from a URL. Use to check if web services are responding or read API endpoints.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "url": {+ Type: "string",+ Description: "The URL to fetch",+ },+ },+ Required: []string{"url"},+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeGetURLContent(ctx, args)+ },+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_list_infrastructure",+ Description: "List all monitored infrastructure including VMs, containers, Docker hosts, and Proxmox nodes.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "type": {+ Type: "string",+ Description: "Filter by type: 'nodes', 'vms', 'containers', 'docker'. Omit for all.",+ Enum: []string{"nodes", "vms", "containers", "docker"},+ },+ "status": {+ Type: "string",+ Description: "Filter by status: 'running', 'stopped', 'all'. Default: all.",+ Enum: []string{"running", "stopped", "all"},+ },+ "limit": {+ Type: "integer",+ Description: "Maximum number of results per category (default: 100)",+ },+ "offset": {+ Type: "integer",+ Description: "Number of results to skip per category",+ },+ },+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeListInfrastructure(ctx, args)+ },+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_set_resource_url",+ Description: "Set the web URL for a resource in Pulse after discovering a web service.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "resource_type": {+ Type: "string",+ Description: "Type of resource: 'guest', 'docker', or 'host'",+ Enum: []string{"guest", "docker", "host"},+ },+ "resource_id": {+ Type: "string",+ Description: "The resource ID from context",+ },+ "url": {+ Type: "string",+ Description: "The URL to set (empty to remove)",+ },+ },+ Required: []string{"resource_type", "resource_id"},+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeSetResourceURL(ctx, args)+ },+ })++ e.registry.Register(RegisteredTool{+ Definition: Tool{+ Name: "pulse_get_resource",+ Description: "Get detailed information about a specific VM, container, or Docker container including IPs, ports, labels, mounts, and network configuration.",+ InputSchema: InputSchema{+ Type: "object",+ Properties: map[string]PropertySchema{+ "resource_type": {+ Type: "string",+ Description: "Type of resource: 'vm', 'container', 'docker'",+ Enum: []string{"vm", "container", "docker"},+ },+ "resource_id": {+ Type: "string",+ Description: "The resource ID, VMID, or name to look up",+ },+ },+ Required: []string{"resource_type", "resource_id"},+ },+ },+ Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {+ return exec.executeGetResource(ctx, args)+ },+ })+}++func (e *PulseToolExecutor) executeGetCapabilities(_ context.Context) (CallToolResult, error) {+ connectedAgents := 0+ if e.agentServer != nil {+ connectedAgents = len(e.agentServer.GetConnectedAgents())+ }++ response := CapabilitiesResponse{+ ControlLevel: string(e.controlLevel),+ Features: FeatureFlags{+ MetricsHistory: e.metricsHistory != nil,+ Baselines: e.baselineProvider != nil,+ Patterns: e.patternProvider != nil,+ Alerts: e.alertProvider != nil,+ Findings: e.findingsProvider != nil,+ Backups: e.backupProvider != nil,+ Storage: e.storageProvider != nil,+ DiskHealth: e.diskHealthProvider != nil,+ AgentProfiles: e.agentProfileManager != nil,+ Control: e.controlLevel != ControlLevelReadOnly && e.controlLevel != "",+ },+ ProtectedGuests: e.protectedGuests,+ ConnectedAgents: connectedAgents,+ Version: ServerVersion,+ }++ return NewJSONResult(response), nil+}++func (e *PulseToolExecutor) executeGetURLContent(_ context.Context, args map[string]interface{}) (CallToolResult, error) {+ url, _ := args["url"].(string)+ if url == "" {+ return NewErrorResult(fmt.Errorf("url is required")), nil+ }++ client := &http.Client{Timeout: 30 * time.Second}+ resp, err := client.Get(url)+ if err != nil {+ return NewJSONResult(URLFetchResponse{+ URL: url,+ Error: err.Error(),+ }), nil+ }+ defer resp.Body.Close()++ body, err := io.ReadAll(io.LimitReader(resp.Body, 50*1024))+ if err != nil {+ return NewJSONResult(URLFetchResponse{+ URL: url,+ Error: fmt.Sprintf("error reading response: %v", err),+ }), nil+ }++ headers := make(map[string]string)+ for k, v := range resp.Header {+ if len(v) > 0 {+ headers[k] = v[0]+ }+ }++ return NewJSONResult(URLFetchResponse{+ URL: url,+ StatusCode: resp.StatusCode,+ Headers: headers,+ Body: string(body),+ }), nil+}++func (e *PulseToolExecutor) executeListInfrastructure(_ context.Context, args map[string]interface{}) (CallToolResult, error) {+ if e.stateProvider == nil {+ return NewErrorResult(fmt.Errorf("state provider not available")), nil+ }++ filterType, _ := args["type"].(string)+ filterStatus, _ := args["status"].(string)+ limit := intArg(args, "limit", 100)+ offset := intArg(args, "offset", 0)++ state := e.stateProvider.GetState()+ response := InfrastructureResponse{+ Total: TotalCounts{+ Nodes: len(state.Nodes),+ VMs: len(state.VMs),+ Containers: len(state.Containers),+ DockerHosts: len(state.DockerHosts),+ },+ }++ // Nodes+ if filterType == "" || filterType == "nodes" {+ for i, node := range state.Nodes {+ if i < offset {+ continue+ }+ if len(response.Nodes) >= limit {+ break+ }+ if filterStatus != "" && filterStatus != "all" && node.Status != filterStatus {+ continue+ }+ response.Nodes = append(response.Nodes, NodeSummary{+ Name: node.Name,+ Status: node.Status,+ ID: node.ID,+ })+ }+ }++ // VMs+ if filterType == "" || filterType == "vms" {+ for i, vm := range state.VMs {+ if i < offset {+ continue+ }+ if len(response.VMs) >= limit {+ break+ }+ if filterStatus != "" && filterStatus != "all" && vm.Status != filterStatus {+ continue+ }+ response.VMs = append(response.VMs, VMSummary{+ VMID: vm.VMID,+ Name: vm.Name,+ Status: vm.Status,+ Node: vm.Node,+ CPU: vm.CPU * 100,+ Memory: vm.Memory.Usage * 100,+ })+ }+ }++ // Containers (LXC)+ if filterType == "" || filterType == "containers" {+ for i, ct := range state.Containers {+ if i < offset {+ continue+ }+ if len(response.Containers) >= limit {+ break+ }+ if filterStatus != "" && filterStatus != "all" && ct.Status != filterStatus {+ continue+ }+ response.Containers = append(response.Containers, ContainerSummary{+ VMID: ct.VMID,+ Name: ct.Name,+ Status: ct.Status,+ Node: ct.Node,+ CPU: ct.CPU * 100,+ Memory: ct.Memory.Usage * 100,+ })+ }+ }++ // Docker hosts+ if filterType == "" || filterType == "docker" {+ for i, host := range state.DockerHosts {+ if i < offset {+ continue+ }+ if len(response.DockerHosts) >= limit {+ break+ }+ dockerHost := DockerHostSummary{+ ID: host.ID,+ Hostname: host.Hostname,+ DisplayName: host.DisplayName,+ ContainerCount: len(host.Containers),+ }+ for _, c := range host.Containers {+ if filterStatus != "" && filterStatus != "all" && c.State != filterStatus {+ continue+ }+ dockerHost.Containers = append(dockerHost.Containers, DockerContainerSummary{+ ID: c.ID,+ Name: c.Name,+ State: c.State,+ Image: c.Image,+ Health: c.Health,+ })+ }+ response.DockerHosts = append(response.DockerHosts, dockerHost)+ }+ }++ return NewJSONResult(response), nil+}++func (e *PulseToolExecutor) executeSetResourceURL(_ context.Context, args map[string]interface{}) (CallToolResult, error) {+ resourceType, _ := args["resource_type"].(string)+ resourceID, _ := args["resource_id"].(string)+ url, _ := args["url"].(string)++ if resourceType == "" {+ return NewErrorResult(fmt.Errorf("resource_type is required")), nil+ }+ if resourceID == "" {+ return NewErrorResult(fmt.Errorf("resource_id is required")), nil+ }++ if e.metadataUpdater == nil {+ return NewTextResult("Metadata updater not available."), nil+ }++ if err := e.metadataUpdater.SetResourceURL(resourceType, resourceID, url); err != nil {+ return NewErrorResult(err), nil+ }++ result := map[string]interface{}{+ "success": true,+ "resource_type": resourceType,+ "resource_id": resourceID,+ "url": url,+ }+ if url == "" {+ result["action"] = "cleared"+ } else {+ result["action"] = "set"+ }++ return NewJSONResult(result), nil+}++func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[string]interface{}) (CallToolResult, error) {+ resourceType, _ := args["resource_type"].(string)+ resourceID, _ := args["resource_id"].(string)++ if resourceType == "" {+ return NewErrorResult(fmt.Errorf("resource_type is required")), nil+ }+ if resourceID == "" {+ return NewErrorResult(fmt.Errorf("resource_id is required")), nil+ }++ if e.stateProvider == nil {+ return NewTextResult("State information not available."), nil+ }++ state := e.stateProvider.GetState()++ switch resourceType {+ case "vm":+ for _, vm := range state.VMs {+ if fmt.Sprintf("%d", vm.VMID) == resourceID || vm.Name == resourceID || vm.ID == resourceID {+ response := ResourceResponse{+ Type: "vm",+ ID: vm.ID,+ Name: vm.Name,+ Status: vm.Status,+ Node: vm.Node,+ CPU: ResourceCPU{+ Percent: vm.CPU * 100,+ Cores: vm.CPUs,+ },+ Memory: ResourceMemory{+ Percent: vm.Memory.Usage * 100,+ UsedGB: float64(vm.Memory.Used) / (1024 * 1024 * 1024),+ TotalGB: float64(vm.Memory.Total) / (1024 * 1024 * 1024),+ },+ OS: vm.OSName,+ Tags: vm.Tags,+ }+ if !vm.LastBackup.IsZero() {+ response.LastBackup = &vm.LastBackup+ }+ for _, nic := range vm.NetworkInterfaces {+ response.Networks = append(response.Networks, NetworkInfo{+ Name: nic.Name,+ Addresses: nic.Addresses,+ })+ }+ return NewJSONResult(response), nil+ }+ }+ return NewJSONResult(map[string]interface{}{+ "error": "not_found",+ "resource_id": resourceID,+ "type": "vm",+ }), nil++ case "container":+ for _, ct := range state.Containers {+ if fmt.Sprintf("%d", ct.VMID) == resourceID || ct.Name == resourceID || ct.ID == resourceID {+ response := ResourceResponse{+ Type: "container",+ ID: ct.ID,+ Name: ct.Name,+ Status: ct.Status,+ Node: ct.Node,+ CPU: ResourceCPU{+ Percent: ct.CPU * 100,+ Cores: ct.CPUs,+ },+ Memory: ResourceMemory{+ Percent: ct.Memory.Usage * 100,+ UsedGB: float64(ct.Memory.Used) / (1024 * 1024 * 1024),+ TotalGB: float64(ct.Memory.Total) / (1024 * 1024 * 1024),+ },+ OS: ct.OSName,+ Tags: ct.Tags,+ }+ if !ct.LastBackup.IsZero() {+ response.LastBackup = &ct.LastBackup+ }+ for _, nic := range ct.NetworkInterfaces {+ response.Networks = append(response.Networks, NetworkInfo{+ Name: nic.Name,+ Addresses: nic.Addresses,+ })+ }+ return NewJSONResult(response), nil+ }+ }+ return NewJSONResult(map[string]interface{}{+ "error": "not_found",+ "resource_id": resourceID,+ "type": "container",+ }), nil++ case "docker":+ for _, host := range state.DockerHosts {+ for _, c := range host.Containers {+ if c.ID == resourceID || c.Name == resourceID || strings.HasPrefix(c.ID, resourceID) {+ response := ResourceResponse{+ Type: "docker",+ ID: c.ID,+ Name: c.Name,+ Status: c.State,+ Host: host.Hostname,+ Image: c.Image,+ Health: c.Health,+ CPU: ResourceCPU{+ Percent: c.CPUPercent,+ },+ Memory: ResourceMemory{+ Percent: c.MemoryPercent,+ UsedGB: float64(c.MemoryUsage) / (1024 * 1024 * 1024),+ TotalGB: float64(c.MemoryLimit) / (1024 * 1024 * 1024),+ },+ RestartCount: c.RestartCount,+ Labels: c.Labels,+ }++ if c.UpdateStatus != nil && c.UpdateStatus.UpdateAvailable {+ response.UpdateAvailable = true+ }++ for _, p := range c.Ports {+ response.Ports = append(response.Ports, PortInfo{+ Private: p.PrivatePort,+ Public: p.PublicPort,+ Protocol: p.Protocol,+ IP: p.IP,+ })+ }++ for _, n := range c.Networks {+ response.Networks = append(response.Networks, NetworkInfo{+ Name: n.Name,+ Addresses: []string{n.IPv4},+ })+ }++ for _, m := range c.Mounts {+ response.Mounts = append(response.Mounts, MountInfo{+ Source: m.Source,+ Destination: m.Destination,+ ReadWrite: m.RW,+ })+ }++ return NewJSONResult(response), nil+ }+ }+ }+ return NewJSONResult(map[string]interface{}{+ "error": "not_found",+ "resource_id": resourceID,+ "type": "docker",+ }), nil++ default:+ return NewErrorResult(fmt.Errorf("invalid resource_type: %s. Use 'vm', 'container', or 'docker'", resourceType)), nil+ }+}++// Helper to get int args with default+func intArg(args map[string]interface{}, key string, defaultVal int) int {+ if v, ok := args[key]; ok {+ switch val := v.(type) {+ case int:+ return val+ case float64:+ return int(val)+ case int64:+ return int(val)+ }+ }+ return defaultVal+}diff --git a/internal/ai/mcp/types.go b/internal/ai/mcp/types.gonew file mode 100644index 0000000000..57db0fb9d1--- /dev/null+++ b/internal/ai/mcp/types.go@@ -0,0 +1,19 @@+package mcp++import "context"++// AgentProfileManager manages centralized agent profiles and assignments.+type AgentProfileManager interface {+ ApplyAgentScope(ctx context.Context, agentID, agentLabel string, settings map[string]interface{}) (profileID, profileName string, created bool, err error)+ AssignProfile(ctx context.Context, agentID, profileID string) (profileName string, err error)+ GetAgentScope(ctx context.Context, agentID string) (*AgentScope, error)+}++// AgentScope summarizes profile scope applied to an agent.+type AgentScope struct {+ AgentID string+ ProfileID string+ ProfileName string+ ProfileVersion int+ Settings map[string]interface{}+}diff --git a/internal/ai/opencode/bridge.go b/internal/ai/opencode/bridge.goindex d60722901f..fe7d8d47b5 100644--- a/internal/ai/opencode/bridge.go+++ b/internal/ai/opencode/bridge.go@@ -19,7 +19,7 @@ func (b *Bridge) TransformEvent(ocEvent StreamEvent) (ai.StreamEvent, error) {switch ocEvent.Type {case "tool_use", "tool_call":return b.transformToolUse(ocEvent)- case "tool_result":+ case "tool_result", "tool_end":return b.transformToolResult(ocEvent)case "content", "text":return b.transformContent(ocEvent)@@ -170,26 +170,60 @@ func (b *Bridge) handleApprovalNeeded(toolResult ToolResultEvent) (ai.StreamEvenToolName: mapToolName(toolResult.Name),RunOnHost: approvalData.RunOnHost,TargetHost: approvalData.TargetHost,+ ApprovalID: approvalData.ApprovalID,},}, nil}// mapToolName maps OpenCode/MCP tool names to Pulse tool namesfunc mapToolName(name string) string {- // Map pulse_ prefixed MCP tools back to original names+ // Map pulse_ prefixed MCP tools back to display namesswitch name {+ // Control toolscase "pulse_run_command":return "run_command"- case "pulse_fetch_url":- return "fetch_url"+ case "pulse_control_guest":+ return "control_guest"+ case "pulse_control_docker":+ return "control_docker"+ // Query tools+ case "pulse_get_capabilities":+ return "get_capabilities"+ case "pulse_get_url_content":+ return "get_url_content"+ case "pulse_list_infrastructure":+ return "list_infrastructure"case "pulse_set_resource_url":return "set_resource_url"+ case "pulse_get_resource":+ return "get_resource"+ // Patrol tools+ case "pulse_get_metrics":+ return "get_metrics"+ case "pulse_get_baselines":+ return "get_baselines"+ case "pulse_get_patterns":+ return "get_patterns"+ case "pulse_list_alerts":+ return "list_alerts"+ case "pulse_list_findings":+ return "list_findings"case "pulse_resolve_finding":return "resolve_finding"case "pulse_dismiss_finding":return "dismiss_finding"- case "pulse_get_infrastructure_state":- return "get_infrastructure_state"+ // Infrastructure tools+ case "pulse_list_backups":+ return "list_backups"+ case "pulse_list_storage":+ return "list_storage"+ case "pulse_get_disk_health":+ return "get_disk_health"+ // Profile tools+ case "pulse_get_agent_scope":+ return "get_agent_scope"+ case "pulse_set_agent_scope":+ return "set_agent_scope"default:return name}@@ -223,6 +257,7 @@ type approvalInfo struct {Command stringRunOnHost boolTargetHost string+ ApprovalID string}// parseApprovalFromOutput parses approval data from tool output@@ -237,6 +272,7 @@ func parseApprovalFromOutput(output string) approvalInfo {Command string `json:"command"`RunOnHost bool `json:"run_on_host"`TargetHost string `json:"target_host"`+ ApprovalID string `json:"approval_id"`}if err := json.Unmarshal([]byte(jsonStr), &data); err != nil {@@ -248,6 +284,7 @@ func parseApprovalFromOutput(output string) approvalInfo {Command: data.Command,RunOnHost: data.RunOnHost,TargetHost: data.TargetHost,+ ApprovalID: data.ApprovalID,}}diff --git a/internal/ai/opencode/bridge_test.go b/internal/ai/opencode/bridge_test.gonew file mode 100644index 0000000000..347e31343e--- /dev/null+++ b/internal/ai/opencode/bridge_test.go@@ -0,0 +1,250 @@+package opencode++import (+ "encoding/json"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestBridge_TransformEvent(t *testing.T) {+ bridge := NewBridge()++ tests := []struct {+ name string+ input StreamEvent+ wantType string+ checkData func(*testing.T, interface{})+ wantErr bool+ }{+ {+ name: "content event (text)",+ input: StreamEvent{+ Type: "content",+ Data: json.RawMessage(`{"content":"hello world"}`),+ },+ wantType: "content",+ checkData: func(t *testing.T, data interface{}) {+ assert.Equal(t, "hello world", data)+ },+ },+ {+ name: "content event (delta)",+ input: StreamEvent{+ Type: "content",+ Data: json.RawMessage(`{"delta":"hello"}`),+ },+ wantType: "content",+ checkData: func(t *testing.T, data interface{}) {+ assert.Equal(t, "hello", data)+ },+ },+ {+ name: "thinking event",+ input: StreamEvent{+ Type: "thinking",+ Data: json.RawMessage(`{"content":"hmm..."}`),+ },+ wantType: "thinking",+ checkData: func(t *testing.T, data interface{}) {+ assert.Equal(t, "hmm...", data)+ },+ },+ {+ name: "tool use event",+ input: StreamEvent{+ Type: "tool_use",+ Data: json.RawMessage(`{"id":"call_1","name":"pulse_run_command","input":{"command":"ls -la"}}`),+ },+ wantType: "tool_start",+ checkData: func(t *testing.T, data interface{}) {+ d, ok := data.(ai.ToolStartData)+ require.True(t, ok)+ assert.Equal(t, "run_command", d.Name)+ assert.Equal(t, "ls -la", d.Input)+ },+ },+ {+ name: "tool use event (generic)",+ input: StreamEvent{+ Type: "tool_use",+ Data: json.RawMessage(`{"id":"call_2","name":"unknown_tool","input":{"foo":"bar"}}`),+ },+ wantType: "tool_start",+ checkData: func(t *testing.T, data interface{}) {+ d, ok := data.(ai.ToolStartData)+ require.True(t, ok)+ assert.Equal(t, "unknown_tool", d.Name)+ // JSON string check might be flaky due to key ordering, but simple map usually ok+ assert.Contains(t, d.Input, `"foo":"bar"`)+ },+ },+ {+ name: "tool result event (success)",+ input: StreamEvent{+ Type: "tool_result",+ Data: json.RawMessage(`{"id":"call_1","name":"pulse_run_command","output":"file1 file2","success":true}`),+ },+ wantType: "tool_end",+ checkData: func(t *testing.T, data interface{}) {+ d, ok := data.(ai.ToolEndData)+ require.True(t, ok)+ assert.Equal(t, "run_command", d.Name)+ assert.Equal(t, "file1 file2", d.Output)+ assert.True(t, d.Success)+ },+ },+ {+ name: "tool result event (approval needed)",+ input: StreamEvent{+ Type: "tool_result",+ Data: json.RawMessage(`{"id":"call_3","name":"pulse_run_command","output":"APPROVAL_REQUIRED: {\"command\":\"rm -rf /\",\"run_on_host\":true}","success":true}`),+ },+ wantType: "approval_needed",+ checkData: func(t *testing.T, data interface{}) {+ d, ok := data.(ai.ApprovalNeededData)+ require.True(t, ok)+ assert.Equal(t, "run_command", d.ToolName)+ assert.Equal(t, "call_3", d.ToolID)+ assert.Equal(t, "rm -rf /", d.Command)+ assert.True(t, d.RunOnHost)+ },+ },+ {+ name: "complete event",+ input: StreamEvent{+ Type: "complete",+ Data: json.RawMessage(`{"sessionId":"ses-123","usage":{"inputTokens":10,"outputTokens":20},"model":{"id":"gpt-4","provider":"openai"}}`),+ },+ wantType: "done",+ checkData: func(t *testing.T, data interface{}) {+ m, ok := data.(map[string]interface{})+ require.True(t, ok)+ assert.Equal(t, "ses-123", m["session_id"])+ assert.Equal(t, "gpt-4", m["model"])+ },+ },+ {+ name: "error event (structured)",+ input: StreamEvent{+ Type: "error",+ Data: json.RawMessage(`{"error":"bad_request","message":"Something went wrong"}`),+ },+ wantType: "error",+ checkData: func(t *testing.T, data interface{}) {+ assert.Equal(t, "Something went wrong", data)+ },+ },+ {+ name: "error event (simple)",+ input: StreamEvent{+ Type: "error",+ Data: json.RawMessage(`{"error":"Just an error"}`),+ },+ wantType: "error",+ checkData: func(t *testing.T, data interface{}) {+ assert.Equal(t, "Just an error", data)+ },+ },+ {+ name: "unknown event",+ input: StreamEvent{+ Type: "unknown_type",+ Data: json.RawMessage(`"raw data"`),+ },+ wantType: "content",+ checkData: func(t *testing.T, data interface{}) {+ assert.Equal(t, "\"raw data\"", data)+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got, err := bridge.TransformEvent(tt.input)+ if tt.wantErr {+ assert.Error(t, err)+ return+ }+ assert.NoError(t, err)+ assert.Equal(t, tt.wantType, got.Type)+ if tt.checkData != nil {+ tt.checkData(t, got.Data)+ }+ })+ }+}++func TestBridge_StreamEvents(t *testing.T) {+ bridge := NewBridge()+ ocEvents := make(chan StreamEvent, 5)+ ocErrors := make(chan error, 5)++ // Feed some events+ ocEvents <- StreamEvent{+ Type: "content",+ Data: json.RawMessage(`{"delta":"hello"}`),+ }+ ocEvents <- StreamEvent{+ Type: "complete",+ Data: json.RawMessage(`{"sessionId":"ses-1"}`),+ }++ // Dont close ocEvents immediately to avoid race if we want to ensure processing order,+ // but here we want to ensure it handles the events we sent.+ // We MUST close ocEvents eventually or it will block if it drains them all and waits for more.+ // But since we sent "complete" (which maps to "done"), the bridge should exit upon seeing "complete".+ // So we technically don't need to close ocEvents if the bridge logic works.+ // But let's close it to be safe.+ close(ocEvents)+ // Do NOT close ocErrors, to prevent the "return on closed ocErrors" race path.+ // close(ocErrors)++ pulseEvents, pulseErrors := bridge.StreamEvents(ocEvents, ocErrors)++ // helpers to collect+ var events []ai.StreamEvent+ var errs []error++ done := make(chan bool)+ go func() {+ t.Log("Starting to collect events")+ for e := range pulseEvents {+ t.Logf("Got event: %s", e.Type)+ events = append(events, e)+ }+ t.Log("Finished collecting events, collecting errors")+ for e := range pulseErrors {+ t.Logf("Got error: %v", e)+ errs = append(errs, e)+ }+ t.Log("Finished collecting all")+ done <- true+ }()++ <-done++ require.Len(t, events, 2)+ assert.Equal(t, "content", events[0].Type)+ assert.Equal(t, "hello", events[0].Data)+ assert.Equal(t, "done", events[1].Type)+ assert.Empty(t, errs)+}++func TestMapToolName(t *testing.T) {+ tests := []struct {+ input string+ want string+ }{+ {"pulse_run_command", "run_command"},+ {"pulse_control_guest", "control_guest"},+ {"pulse_list_findings", "list_findings"},+ {"other_tool", "other_tool"},+ }++ for _, tt := range tests {+ assert.Equal(t, tt.want, mapToolName(tt.input))+ }+}diff --git a/internal/ai/opencode/client.go b/internal/ai/opencode/client.goindex 5b06e1f7ee..ca55c9a76f 100644--- a/internal/ai/opencode/client.go+++ b/internal/ai/opencode/client.go@@ -316,12 +316,18 @@ func (c *Client) PromptStream(ctx context.Context, req PromptRequest) (<-chan St// OpenCode session anywaysessionID := req.SessionIDif sessionID == "" || !strings.HasPrefix(sessionID, "ses") {+ log.Debug().+ Str("provided_session_id", req.SessionID).+ Msg("OpenCode: Creating new session (no valid session ID provided)")session, err := c.CreateSession(ctx)if err != nil {errs <- fmt.Errorf("failed to create session: %w", err)return}sessionID = session.ID+ log.Debug().Str("new_session_id", sessionID).Msg("OpenCode: Created new session")+ } else {+ log.Debug().Str("session_id", sessionID).Msg("OpenCode: Using existing session")}// OpenCode uses /session/{id}/prompt_async for async/streaming with parts array format@@ -590,6 +596,34 @@ func (c *Client) PromptStream(ctx context.Context, req PromptRequest) (<-chan Streturn}}++ case "question.asked":+ // OpenCode is asking the user a question+ var props struct {+ ID string `json:"id"`+ Questions []struct {+ ID string `json:"id"`+ Type string `json:"type"` // "text" or "select"+ Question string `json:"question"`+ Options []struct {+ Label string `json:"label"`+ Value string `json:"value"`+ } `json:"options,omitempty"`+ } `json:"questions"`+ }+ if err := json.Unmarshal(envelope.Payload.Properties, &props); err != nil {+ log.Warn().Err(err).Msg("OpenCode: Failed to parse question.asked event")+ continue+ }+ log.Debug().Str("questionID", props.ID).Int("count", len(props.Questions)).Msg("OpenCode: Question asked")++ // Send question event to frontend+ questionData, _ := json.Marshal(map[string]interface{}{+ "question_id": props.ID,+ "questions": props.Questions,+ "session_id": sessionID,+ })+ events <- StreamEvent{Type: "question", Data: questionData}}}@@ -646,6 +680,44 @@ func (c *Client) AbortSession(ctx context.Context, sessionID string) error {return nil}+// AnswerQuestion answers a pending question from OpenCode+func (c *Client) AnswerQuestion(ctx context.Context, questionID string, answers []QuestionAnswer) error {+ // Build answers in OpenCode format+ answerReq := map[string]interface{}{+ "answers": answers,+ }++ body, err := json.Marshal(answerReq)+ if err != nil {+ return err+ }++ req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/question/"+questionID+"/answer", bytes.NewReader(body))+ if err != nil {+ return err+ }+ req.Header.Set("Content-Type", "application/json")++ resp, err := c.httpClient.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {+ bodyBytes, _ := io.ReadAll(resp.Body)+ return fmt.Errorf("answer question failed: status %d, body: %s", resp.StatusCode, string(bodyBytes))+ }++ return nil+}++// QuestionAnswer represents an answer to a question+type QuestionAnswer struct {+ ID string `json:"id"` // Question ID this answer is for+ Value string `json:"value"` // The answer value (text or selected option)+}+// ListModels returns available modelsfunc (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error) {req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/config/providers", nil)diff --git a/internal/ai/opencode/service.go b/internal/ai/opencode/service.goindex 567cd412a7..4e9e373b59 100644--- a/internal/ai/opencode/service.go+++ b/internal/ai/opencode/service.go@@ -46,6 +46,21 @@ type AgentServer interface {// StreamCallback is called for each streaming eventtype StreamCallback func(event StreamEvent)+// convertModelToOpenCode converts Pulse model format (provider:model) to OpenCode format (provider/model)+// Also handles provider name mappings (e.g., gemini -> google)+func convertModelToOpenCode(pulseModel string) string {+ // Replace first colon with slash+ model := strings.Replace(pulseModel, ":", "/", 1)++ // Map Pulse provider names to OpenCode provider names+ // OpenCode uses "google" instead of "gemini" for Gemini models+ if strings.HasPrefix(model, "gemini/") {+ model = "google/" + strings.TrimPrefix(model, "gemini/")+ }++ return model+}+// Service manages OpenCode as Pulse's AI enginetype Service struct {mu sync.RWMutex@@ -84,15 +99,21 @@ func NewService(cfg Config) *Service {agentServer = &agentServerAdapter{cfg.AgentServer}}- executor := mcp.NewPulseToolExecutor(stateProvider, policy, agentServer)+ // Build executor config+ execCfg := mcp.ExecutorConfig{+ StateProvider: stateProvider,+ Policy: policy,+ AgentServer: agentServer,+ }- // Set control level from config+ // Set control level from AI configif cfg.AIConfig != nil {- controlLevel := cfg.AIConfig.GetControlLevel()- executor.SetControlLevel(mcp.ControlLevel(controlLevel))- executor.SetProtectedGuests(cfg.AIConfig.GetProtectedGuests())+ execCfg.ControlLevel = mcp.ControlLevel(cfg.AIConfig.GetControlLevel())+ execCfg.ProtectedGuests = cfg.AIConfig.GetProtectedGuests()}+ executor := mcp.NewPulseToolExecutor(execCfg)+return &Service{cfg: cfg.AIConfig,executor: executor,@@ -182,8 +203,7 @@ func (s *Service) Start(ctx context.Context) error {// Convert model from Pulse format (provider:model) to OpenCode format (provider/model)chatModel := s.cfg.GetChatModel()if chatModel != "" {- // Replace first colon with slash for OpenCode format- sidecarCfg.Model = strings.Replace(chatModel, ":", "/", 1)+ sidecarCfg.Model = convertModelToOpenCode(chatModel)}}s.sidecar = NewSidecar(sidecarCfg)@@ -260,8 +280,7 @@ func (s *Service) Restart(ctx context.Context, newCfg *config.AIConfig) error {chatModel := cfg.GetChatModel()if chatModel != "" {- // Convert from Pulse format (provider:model) to OpenCode format (provider/model)- model := strings.Replace(chatModel, ":", "/", 1)+ model := convertModelToOpenCode(chatModel)s.sidecar.UpdateModel(model)log.Info().Str("model", model).Msg("Updating OpenCode model")}@@ -331,6 +350,9 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbacModel: req.Model,})+ // Use bridge to transform specific events (tool_end -> approval_needed for approvals)+ bridge := NewBridge()+// Relay events to callbackfor {select {@@ -346,10 +368,28 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbacif !ok {return nil}++ // Only transform tool_end events (to detect approvals)+ // Pass through all other events directly for best compatibility+ if event.Type == "tool_end" {+ transformed, err := bridge.TransformEvent(event)+ if err == nil && transformed.Type == "approval_needed" {+ // This is an approval event - marshal and send+ transformedData, _ := json.Marshal(transformed.Data)+ callback(StreamEvent{+ Type: transformed.Type,+ Data: transformedData,+ })+ continue+ }+ }++ // Pass through event directlycallback(StreamEvent{Type: event.Type,Data: event.Data,})+if event.Type == "done" || event.Type == "error" {return nil}@@ -422,6 +462,19 @@ func (s *Service) AbortSession(ctx context.Context, sessionID string) error {return client.AbortSession(ctx, sessionID)}+// AnswerQuestion answers a pending question from OpenCode+func (s *Service) AnswerQuestion(ctx context.Context, questionID string, answers []QuestionAnswer) error {+ s.mu.RLock()+ client := s.client+ s.mu.RUnlock()++ if client == nil {+ return fmt.Errorf("OpenCode not initialized")+ }++ return client.AnswerQuestion(ctx, questionID, answers)+}+// GetClient returns the underlying OpenCode client for direct accessfunc (s *Service) GetClient() *Client {s.mu.RLock()diff --git a/internal/ai/service.go b/internal/ai/service.goindex 3b0b29376d..dfa22ff3ca 100644--- a/internal/ai/service.go+++ b/internal/ai/service.go@@ -1167,6 +1167,7 @@ type ApprovalNeededData struct {ToolName string `json:"tool_name"` // "run_command"RunOnHost bool `json:"run_on_host"`TargetHost string `json:"target_host,omitempty"` // Explicit host to route to+ ApprovalID string `json:"approval_id,omitempty"` // ID of the approval record in the store}// Execute sends a prompt to the AI and returns the responsediff --git a/internal/api/agent_profiles_mcp.go b/internal/api/agent_profiles_mcp.gonew file mode 100644index 0000000000..99b919cb01--- /dev/null+++ b/internal/api/agent_profiles_mcp.go@@ -0,0 +1,309 @@+package api++import (+ "context"+ "fmt"+ "strings"+ "time"++ "github.com/google/uuid"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/mcp"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/license"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rs/zerolog/log"+)++const aiProfileDescription = "Managed by Pulse AI"++// MCPAgentProfileManager manages agent profiles for MCP tools.+type MCPAgentProfileManager struct {+ persistence *config.ConfigPersistence+ licenseService *license.Service+ validator *models.ProfileValidator+}++func NewMCPAgentProfileManager(persistence *config.ConfigPersistence, licenseService *license.Service) *MCPAgentProfileManager {+ return &MCPAgentProfileManager{+ persistence: persistence,+ licenseService: licenseService,+ validator: models.NewProfileValidator(),+ }+}++func (m *MCPAgentProfileManager) ApplyAgentScope(_ context.Context, agentID, agentLabel string, settings map[string]interface{}) (string, string, bool, error) {+ if err := m.requireLicense(); err != nil {+ return "", "", false, err+ }+ if m.persistence == nil {+ return "", "", false, fmt.Errorf("profile persistence unavailable")+ }+ if strings.TrimSpace(agentID) == "" {+ return "", "", false, fmt.Errorf("agent ID is required")+ }+ if len(settings) == 0 {+ return "", "", false, fmt.Errorf("settings are required")+ }+ if err := m.validateSettings(settings); err != nil {+ return "", "", false, err+ }++ profileName := buildScopeProfileName(agentLabel, agentID)+ now := time.Now()+ username := "ai"++ profiles, err := m.persistence.LoadAgentProfiles()+ if err != nil {+ return "", "", false, fmt.Errorf("failed to load profiles: %w", err)+ }++ created := true+ var profile models.AgentProfile+ for i := range profiles {+ if profiles[i].Name == profileName {+ created = false+ profiles[i].Config = settings+ profiles[i].Description = aiProfileDescription+ profiles[i].UpdatedAt = now+ profiles[i].UpdatedBy = username+ profiles[i].Version+++ profile = profiles[i]+ break+ }+ }++ if created {+ profile = models.AgentProfile{+ ID: uuid.New().String(),+ Name: profileName,+ Description: aiProfileDescription,+ Config: settings,+ Version: 1,+ CreatedAt: now,+ UpdatedAt: now,+ CreatedBy: username,+ UpdatedBy: username,+ }+ profiles = append(profiles, profile)+ }++ if err := m.persistence.SaveAgentProfiles(profiles); err != nil {+ return "", "", false, fmt.Errorf("failed to save profile: %w", err)+ }++ if err := m.saveVersion(profile, "AI scope update"); err != nil {+ log.Warn().Err(err).Msg("Failed to record profile version history")+ }++ changeAction := "update"+ if created {+ changeAction = "create"+ }+ m.logChange(models.ProfileChangeLog{+ ID: uuid.New().String(),+ ProfileID: profile.ID,+ ProfileName: profile.Name,+ Action: changeAction,+ OldVersion: profile.Version - 1,+ NewVersion: profile.Version,+ User: username,+ Timestamp: now,+ })++ if err := m.assignProfile(agentID, profile, username); err != nil {+ return "", "", created, err+ }++ return profile.ID, profile.Name, created, nil+}++func (m *MCPAgentProfileManager) AssignProfile(_ context.Context, agentID, profileID string) (string, error) {+ if err := m.requireLicense(); err != nil {+ return "", err+ }+ if m.persistence == nil {+ return "", fmt.Errorf("profile persistence unavailable")+ }+ agentID = strings.TrimSpace(agentID)+ profileID = strings.TrimSpace(profileID)+ if agentID == "" || profileID == "" {+ return "", fmt.Errorf("agent ID and profile ID are required")+ }++ profiles, err := m.persistence.LoadAgentProfiles()+ if err != nil {+ return "", fmt.Errorf("failed to load profiles: %w", err)+ }++ var profile models.AgentProfile+ found := false+ for _, p := range profiles {+ if p.ID == profileID {+ profile = p+ found = true+ break+ }+ }+ if !found {+ return "", fmt.Errorf("profile %s not found", profileID)+ }++ if err := m.assignProfile(agentID, profile, "ai"); err != nil {+ return "", err+ }++ return profile.Name, nil+}++func (m *MCPAgentProfileManager) GetAgentScope(_ context.Context, agentID string) (*mcp.AgentScope, error) {+ if err := m.requireLicense(); err != nil {+ return nil, err+ }+ if m.persistence == nil {+ return nil, fmt.Errorf("profile persistence unavailable")+ }+ agentID = strings.TrimSpace(agentID)+ if agentID == "" {+ return nil, fmt.Errorf("agent ID is required")+ }++ assignments, err := m.persistence.LoadAgentProfileAssignments()+ if err != nil {+ return nil, fmt.Errorf("failed to load assignments: %w", err)+ }++ var assignment *models.AgentProfileAssignment+ for i := range assignments {+ if assignments[i].AgentID == agentID {+ assignment = &assignments[i]+ break+ }+ }+ if assignment == nil {+ return nil, nil+ }++ profiles, err := m.persistence.LoadAgentProfiles()+ if err != nil {+ return nil, fmt.Errorf("failed to load profiles: %w", err)+ }++ for _, profile := range profiles {+ if profile.ID == assignment.ProfileID {+ return &mcp.AgentScope{+ AgentID: agentID,+ ProfileID: profile.ID,+ ProfileName: profile.Name,+ ProfileVersion: assignment.ProfileVersion,+ Settings: profile.Config,+ }, nil+ }+ }++ return nil, nil+}++func (m *MCPAgentProfileManager) assignProfile(agentID string, profile models.AgentProfile, username string) error {+ assignments, err := m.persistence.LoadAgentProfileAssignments()+ if err != nil {+ return fmt.Errorf("failed to load assignments: %w", err)+ }++ trimmed := []models.AgentProfileAssignment{}+ for _, a := range assignments {+ if a.AgentID != agentID {+ trimmed = append(trimmed, a)+ }+ }++ trimmed = append(trimmed, models.AgentProfileAssignment{+ AgentID: agentID,+ ProfileID: profile.ID,+ ProfileVersion: profile.Version,+ UpdatedAt: time.Now(),+ AssignedBy: username,+ })++ if err := m.persistence.SaveAgentProfileAssignments(trimmed); err != nil {+ return fmt.Errorf("failed to save assignment: %w", err)+ }++ m.logChange(models.ProfileChangeLog{+ ID: uuid.New().String(),+ ProfileID: profile.ID,+ ProfileName: profile.Name,+ Action: "assign",+ AgentID: agentID,+ User: username,+ Timestamp: time.Now(),+ })++ return nil+}++func (m *MCPAgentProfileManager) validateSettings(settings map[string]interface{}) error {+ if m.validator == nil {+ return nil+ }+ result := m.validator.Validate(settings)+ if !result.Valid || len(result.Warnings) > 0 {+ return fmt.Errorf("invalid settings: %s", formatValidationIssues(result))+ }+ return nil+}++func formatValidationIssues(result models.ValidationResult) string {+ parts := make([]string, 0, len(result.Errors)+len(result.Warnings))+ for _, err := range result.Errors {+ parts = append(parts, fmt.Sprintf("%s (%s)", err.Key, err.Message))+ }+ for _, warn := range result.Warnings {+ parts = append(parts, fmt.Sprintf("warning: %s (%s)", warn.Key, warn.Message))+ }+ if len(parts) == 0 {+ return "unknown validation error"+ }+ return strings.Join(parts, "; ")+}++func (m *MCPAgentProfileManager) saveVersion(profile models.AgentProfile, note string) error {+ versions, err := m.persistence.LoadAgentProfileVersions()+ if err != nil {+ return err+ }++ versions = append(versions, models.AgentProfileVersion{+ ProfileID: profile.ID,+ Version: profile.Version,+ Name: profile.Name,+ Description: profile.Description,+ Config: profile.Config,+ ParentID: profile.ParentID,+ CreatedAt: time.Now(),+ CreatedBy: "ai",+ ChangeNote: note,+ })++ return m.persistence.SaveAgentProfileVersions(versions)+}++func (m *MCPAgentProfileManager) logChange(entry models.ProfileChangeLog) {+ if err := m.persistence.AppendProfileChangeLog(entry); err != nil {+ log.Warn().Err(err).Msg("Failed to log profile change")+ }+}++func (m *MCPAgentProfileManager) requireLicense() error {+ if m.licenseService == nil {+ return nil+ }+ return m.licenseService.RequireFeature(license.FeatureAgentProfiles)+}++func buildScopeProfileName(agentLabel, agentID string) string {+ label := strings.TrimSpace(agentLabel)+ if label == "" || strings.EqualFold(label, agentID) {+ return fmt.Sprintf("AI Scope: %s", agentID)+ }+ return fmt.Sprintf("AI Scope: %s (%s)", label, agentID)+}diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.goindex b26b2f30c9..cfc3ae0a45 100644--- a/internal/api/ai_handler.go+++ b/internal/api/ai_handler.go@@ -8,6 +8,7 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval""github.com/rcourtman/pulse-go-rewrite/internal/ai/opencode""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models"@@ -61,6 +62,25 @@ func (h *AIHandler) Start(ctx context.Context, stateProvider AIStateProvider) erreturn err}+ // Initialize approval store for command approval workflow+ dataDir := aiCfg.OpenCodeDataDir+ if dataDir == "" {+ dataDir = "/tmp/pulse-opencode"+ }++ approvalStore, err := approval.NewStore(approval.StoreConfig{+ DataDir: dataDir,+ DefaultTimeout: 5 * time.Minute,+ MaxApprovals: 100,+ })+ if err != nil {+ log.Warn().Err(err).Msg("Failed to create approval store, approvals will not be persisted")+ } else {+ approval.SetStore(approvalStore)+ approvalStore.StartCleanup(ctx)+ log.Info().Str("data_dir", dataDir).Msg("Approval store initialized")+ }+log.Info().Msg("Pulse AI started (powered by OpenCode)")return nil}@@ -355,6 +375,49 @@ func (h *AIHandler) HandleStatus(w http.ResponseWriter, r *http.Request) {json.NewEncoder(w).Encode(status)}+// AnswerQuestionRequest represents a request to answer a question+type AnswerQuestionRequest struct {+ Answers []struct {+ ID string `json:"id"`+ Value string `json:"value"`+ } `json:"answers"`+}++// HandleAnswerQuestion handles POST /api/ai/question/{questionID}/answer+func (h *AIHandler) HandleAnswerQuestion(w http.ResponseWriter, r *http.Request, questionID string) {+ if !CheckAuth(h.config, w, r) {+ return+ }++ if !h.IsRunning() {+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)+ return+ }++ var req AnswerQuestionRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ http.Error(w, "Invalid request body", http.StatusBadRequest)+ return+ }++ // Convert to opencode.QuestionAnswer+ answers := make([]opencode.QuestionAnswer, len(req.Answers))+ for i, a := range req.Answers {+ answers[i] = opencode.QuestionAnswer{+ ID: a.ID,+ Value: a.Value,+ }+ }++ if err := h.service.AnswerQuestion(r.Context(), questionID, answers); err != nil {+ log.Error().Err(err).Str("questionID", questionID).Msg("Failed to answer question")+ http.Error(w, err.Error(), http.StatusInternalServerError)+ return+ }++ w.WriteHeader(http.StatusOK)+}+// SetAlertProvider sets the alert provider for MCP toolsfunc (h *AIHandler) SetAlertProvider(provider opencode.MCPAlertProvider) {if h.service != nil {diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.goindex d072cfdb59..5a69dbbdf7 100644--- a/internal/api/ai_handlers.go+++ b/internal/api/ai_handlers.go@@ -3809,16 +3809,59 @@ func (h *AISettingsHandler) HandleApproveCommand(w http.ResponseWriter, r *http.LogAuditEvent("ai_command_approved", username, GetClientIP(r), r.URL.Path, true,fmt.Sprintf("Approved command: %s", truncateForLog(req.Command, 100)))- // TODO: Resume execution with the approved command- // For now, just return the approval status- // The actual execution resumption will be added when we integrate with the AI service+ // Execute the approved command+ var execResult *agentexec.CommandResultPayload+ var execErr error++ if h.agentServer != nil && req.TargetName != "" {+ // Find agent for the target host+ agentID, found := h.agentServer.GetAgentForHost(req.TargetName)+ if found {+ ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)+ defer cancel()++ execResult, execErr = h.agentServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{+ Command: req.Command,+ TargetType: req.TargetType,+ TargetID: req.TargetID,+ })- w.Header().Set("Content-Type", "application/json")- json.NewEncoder(w).Encode(map[string]interface{}{+ if execErr == nil {+ LogAuditEvent("ai_command_executed", username, GetClientIP(r), r.URL.Path, true,+ fmt.Sprintf("Executed command: %s (exit: %d)", truncateForLog(req.Command, 100), execResult.ExitCode))+ } else {+ LogAuditEvent("ai_command_failed", username, GetClientIP(r), r.URL.Path, false,+ fmt.Sprintf("Failed to execute command: %s - %v", truncateForLog(req.Command, 100), execErr))+ }+ } else {+ execErr = fmt.Errorf("no agent available for host %s", req.TargetName)+ }+ }++ response := map[string]interface{}{"approved": true,"request": req,- "message": "Command approved. Execution will resume.",- })+ }++ if execResult != nil {+ response["executed"] = true+ response["result"] = map[string]interface{}{+ "stdout": execResult.Stdout,+ "stderr": execResult.Stderr,+ "exit_code": execResult.ExitCode,+ }+ response["message"] = "Command approved and executed."+ } else if execErr != nil {+ response["executed"] = false+ response["error"] = execErr.Error()+ response["message"] = "Command approved but execution failed."+ } else {+ response["executed"] = false+ response["message"] = "Command approved. No agent available for execution."+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(response)}// HandleDenyCommand denies a pending command.diff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.goindex 19329f8347..c9fe5863b7 100644--- a/internal/api/config_handlers.go+++ b/internal/api/config_handlers.go@@ -6945,6 +6945,7 @@ func (h *ConfigHandlers) HandleAgentInstallCommand(w http.ResponseWriter, r *htttokenName := fmt.Sprintf("proxmox-agent-%s-%d", req.Type, time.Now().Unix())scopes := []string{config.ScopeHostReport,+ config.ScopeHostConfigRead,config.ScopeHostManage,}diff --git a/internal/api/config_profiles.go b/internal/api/config_profiles.goindex eb010443b9..444764982c 100644--- a/internal/api/config_profiles.go+++ b/internal/api/config_profiles.go@@ -501,6 +501,13 @@ func (h *ConfigProfileHandler) AssignProfile(w http.ResponseWriter, r *http.RequTimestamp: time.Now(),})+ tokenID := ""+ if record := getAPITokenRecordFromRequest(r); record != nil {+ tokenID = record.ID+ }+ LogAuditEvent("agent_profile_assigned", username, GetClientIP(r), r.URL.Path, true,+ fmt.Sprintf("agent_id=%s profile_id=%s token_id=%s", input.AgentID, input.ProfileID, tokenID))+json.NewEncoder(w).Encode(input)}@@ -561,6 +568,13 @@ func (h *ConfigProfileHandler) UnassignProfile(w http.ResponseWriter, r *http.ReUser: username,Timestamp: time.Now(),})++ tokenID := ""+ if record := getAPITokenRecordFromRequest(r); record != nil {+ tokenID = record.ID+ }+ LogAuditEvent("agent_profile_unassigned", username, GetClientIP(r), r.URL.Path, true,+ fmt.Sprintf("agent_id=%s profile_id=%s token_id=%s", agentID, removedAssignment.ProfileID, tokenID))}}diff --git a/internal/api/config_profiles_test.go b/internal/api/config_profiles_test.goindex 8d01e711eb..b7e4142800 100644--- a/internal/api/config_profiles_test.go+++ b/internal/api/config_profiles_test.go@@ -233,4 +233,87 @@ func TestConfigProfileHandlers(t *testing.T) {t.Errorf("expected 0 assignments after profile delete, got %d", len(assignments))}})++ // 11. Get Schema+ t.Run("GetSchema", func(t *testing.T) {+ req := httptest.NewRequest(http.MethodGet, "/schema", nil)+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status 200, got %d", rec.Code)+ }++ var defs []models.ConfigKeyDefinition+ if err := json.NewDecoder(rec.Body).Decode(&defs); err != nil {+ t.Fatalf("failed to decode: %v", err)+ }+ if len(defs) == 0 {+ t.Fatalf("expected schema definitions, got 0")+ }++ found := false+ for _, def := range defs {+ if def.Key == "interval" {+ found = true+ break+ }+ }+ if !found {+ t.Errorf("expected schema to include interval")+ }+ })++ // 12. Validate Config+ t.Run("ValidateConfig", func(t *testing.T) {+ payload := map[string]interface{}{+ "interval": 5,+ "unknown_key": true,+ }+ body, _ := json.Marshal(payload)+ req := httptest.NewRequest(http.MethodPost, "/validate", bytes.NewBuffer(body))+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status 200, got %d: %s", rec.Code, rec.Body.String())+ }++ var result models.ValidationResult+ if err := json.NewDecoder(rec.Body).Decode(&result); err != nil {+ t.Fatalf("failed to decode: %v", err)+ }++ if result.Valid {+ t.Fatalf("expected invalid result, got valid")+ }+ if len(result.Errors) == 0 {+ t.Fatalf("expected validation errors, got none")+ }+ if len(result.Warnings) == 0 {+ t.Fatalf("expected validation warnings, got none")+ }++ hasIntervalError := false+ for _, err := range result.Errors {+ if err.Key == "interval" {+ hasIntervalError = true+ break+ }+ }+ if !hasIntervalError {+ t.Errorf("expected interval error, got %+v", result.Errors)+ }++ hasUnknownWarning := false+ for _, warn := range result.Warnings {+ if warn.Key == "unknown_key" {+ hasUnknownWarning = true+ break+ }+ }+ if !hasUnknownWarning {+ t.Errorf("expected unknown_key warning, got %+v", result.Warnings)+ }+ })}diff --git a/internal/api/host_agents.go b/internal/api/host_agents.goindex e842fe144d..ec26b4b287 100644--- a/internal/api/host_agents.go+++ b/internal/api/host_agents.go@@ -1,20 +1,33 @@package apiimport (+ "crypto/ed25519""encoding/json"+ "fmt""net/http""strings"+ "sync""time""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/monitoring"+ "github.com/rcourtman/pulse-go-rewrite/internal/remoteconfig""github.com/rcourtman/pulse-go-rewrite/internal/utils""github.com/rcourtman/pulse-go-rewrite/internal/websocket"agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth""github.com/rs/zerolog/log")+const configSignatureTTL = 15 * time.Minute++var configSigningState struct {+ once sync.Once+ key ed25519.PrivateKey+ err error+}+// HostAgentHandlers manages ingest from the pulse-host-agent.type HostAgentHandlers struct {monitor *monitoring.Monitor@@ -246,23 +259,152 @@ func (h *HostAgentHandlers) HandleConfig(w http.ResponseWriter, r *http.Request)}}+func (h *HostAgentHandlers) canReadConfig(record *config.APITokenRecord) bool {+ if record == nil {+ return true+ }+ return record.HasScope(config.ScopeHostConfigRead) ||+ record.HasScope(config.ScopeHostManage) ||+ record.HasScope(config.ScopeSettingsWrite)+}++func (h *HostAgentHandlers) resolveConfigHost(hostID string, record *config.APITokenRecord) (models.Host, bool) {+ state := h.monitor.GetState()++ if record == nil || record.HasScope(config.ScopeHostManage) || record.HasScope(config.ScopeSettingsWrite) {+ for _, candidate := range state.Hosts {+ if candidate.ID == hostID {+ return candidate, true+ }+ }+ return models.Host{}, false+ }++ for _, candidate := range state.Hosts {+ if candidate.TokenID != "" && candidate.TokenID == record.ID {+ return candidate, true+ }+ }++ return models.Host{}, false+}++func (h *HostAgentHandlers) signHostConfig(hostID string, cfg monitoring.HostAgentConfig) (monitoring.HostAgentConfig, error) {+ signatureRequired := isConfigSignatureRequired()+ key, err := getConfigSigningKey()+ if err != nil {+ if signatureRequired {+ return cfg, fmt.Errorf("failed to load config signing key: %w", err)+ }+ log.Warn().Err(err).Msg("Failed to load config signing key")+ return cfg, nil+ }+ if len(key) == 0 {+ if signatureRequired {+ return cfg, fmt.Errorf("config signing required but PULSE_AGENT_CONFIG_SIGNING_KEY is not set")+ }+ return cfg, nil+ }++ issuedAt := time.Now().UTC()+ expiresAt := issuedAt.Add(configSignatureTTL)++ payload := remoteconfig.SignedConfigPayload{+ HostID: hostID,+ IssuedAt: issuedAt,+ ExpiresAt: expiresAt,+ CommandsEnabled: cfg.CommandsEnabled,+ Settings: cfg.Settings,+ }++ signature, err := remoteconfig.SignConfigPayload(payload, key)+ if err != nil {+ if signatureRequired {+ return cfg, fmt.Errorf("failed to sign host config payload: %w", err)+ }+ log.Warn().Err(err).Msg("Failed to sign host config payload")+ return cfg, nil+ }++ cfg.IssuedAt = &issuedAt+ cfg.ExpiresAt = &expiresAt+ cfg.Signature = signature+ return cfg, nil+}++func getConfigSigningKey() (ed25519.PrivateKey, error) {+ configSigningState.once.Do(func() {+ raw := utils.GetenvTrim("PULSE_AGENT_CONFIG_SIGNING_KEY")+ if raw == "" {+ return+ }+ key, err := remoteconfig.DecodeEd25519PrivateKey(raw)+ if err != nil {+ configSigningState.err = err+ return+ }+ configSigningState.key = key+ })++ return configSigningState.key, configSigningState.err+}++func isConfigSignatureRequired() bool {+ return utils.ParseBool(utils.GetenvTrim("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED"))+}+// handleGetConfig returns the server-side config for an agent to apply.func (h *HostAgentHandlers) handleGetConfig(w http.ResponseWriter, r *http.Request, hostID string) {- if !h.ensureHostTokenMatch(w, r, hostID) {+ record := getAPITokenRecordFromRequest(r)+ if !h.canReadConfig(record) {+ respondMissingScope(w, config.ScopeHostConfigRead)+ LogAuditEvent("host_agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false,+ fmt.Sprintf("host_id=%s token_id=%s", hostID, tokenID(record)))return}+ host, ok := h.resolveConfigHost(hostID, record)+ if !ok {+ writeErrorResponse(w, http.StatusNotFound, "host_not_found", "Host has not registered with Pulse yet", nil)+ LogAuditEvent("host_agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false,+ fmt.Sprintf("host_id=%s token_id=%s", hostID, tokenID(record)))+ return+ }++ hostID = host.ID+config := h.monitor.GetHostAgentConfig(hostID)+ signedConfig, err := h.signHostConfig(hostID, config)+ if err != nil {+ log.Error().Err(err).Msg("Failed to sign host config payload")+ writeErrorResponse(w, http.StatusInternalServerError, "config_signing_failed", "Failed to sign host config", nil)+ LogAuditEvent("host_agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false,+ fmt.Sprintf("host_id=%s token_id=%s", hostID, tokenID(record)))+ return+ }resp := map[string]any{"success": true,"hostId": hostID,- "config": config,+ "config": signedConfig,}if err := utils.WriteJSONResponse(w, resp); err != nil {log.Error().Err(err).Msg("Failed to serialize host config response")+ LogAuditEvent("host_agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false,+ fmt.Sprintf("host_id=%s token_id=%s", hostID, tokenID(record)))+ return+ }++ LogAuditEvent("host_agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, true,+ fmt.Sprintf("host_id=%s token_id=%s", hostID, tokenID(record)))+}++func tokenID(record *config.APITokenRecord) string {+ if record == nil {+ return ""}+ return record.ID}func (h *HostAgentHandlers) ensureHostTokenMatch(w http.ResponseWriter, r *http.Request, hostID string) bool {diff --git a/internal/api/host_agents_test.go b/internal/api/host_agents_test.goindex 55a0eefc23..9e4b1569e2 100644--- a/internal/api/host_agents_test.go+++ b/internal/api/host_agents_test.go@@ -312,7 +312,7 @@ func TestHandleLookupByHostname(t *testing.T) {}}-func TestHandleConfigForbiddenOnTokenMismatch(t *testing.T) {+func TestHandleConfigMissingConfigScope(t *testing.T) {t.Parallel()hostID := "host-789"@@ -336,6 +336,38 @@ func TestHandleConfigForbiddenOnTokenMismatch(t *testing.T) {}}+func TestHandleConfigUsesTokenBinding(t *testing.T) {+ t.Parallel()++ handler := newHostAgentHandlerForTests(t, models.Host{+ ID: "host-1",+ TokenID: "token-expected",+ })++ req := httptest.NewRequest(http.MethodGet, "/api/agents/host/other-host/config", nil)+ attachAPITokenRecord(req, &config.APITokenRecord{+ ID: "token-expected",+ Scopes: []string{config.ScopeHostConfigRead},+ })++ rec := httptest.NewRecorder()+ handler.HandleConfig(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }++ var resp struct {+ HostID string `json:"hostId"`+ }+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {+ t.Fatalf("failed to decode response: %v", err)+ }+ if resp.HostID != "host-1" {+ t.Fatalf("expected host id %q, got %q", "host-1", resp.HostID)+ }+}+func TestHandleConfigAllowsHostManageScope(t *testing.T) {t.Parallel()diff --git a/internal/api/router.go b/internal/api/router.goindex 563c88ba49..8296286cc0 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -233,13 +233,9 @@ func (r *Router) setupRoutes() {r.mux.HandleFunc("/api/agents/host/", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {// Route /api/agents/host/{id}/config to HandleConfigif strings.HasSuffix(req.URL.Path, "/config") {- // GET is for agents to fetch config (host_report scope)+ // GET is for agents to fetch config (host config scope)// PATCH is for UI to update config (host_manage scope, admin only)- if req.Method == http.MethodGet {- if !ensureScope(w, req, config.ScopeHostReport) {- return- }- } else if req.Method == http.MethodPatch {+ if req.Method == http.MethodPatch {if !ensureScope(w, req, config.ScopeHostManage) {return}@@ -1415,6 +1411,13 @@ func (r *Router) setupRoutes() {}))r.mux.HandleFunc("/api/ai/sessions/", RequireAuth(r.config, r.routeOpenCodeSessions))+ // AI approval endpoints - for command approval workflow+ r.mux.HandleFunc("/api/ai/approvals", RequireAuth(r.config, r.aiSettingsHandler.HandleListApprovals))+ r.mux.HandleFunc("/api/ai/approvals/", RequireAuth(r.config, r.routeApprovals))++ // AI question endpoints - for answering OpenCode questions+ r.mux.HandleFunc("/api/ai/question/", RequireAuth(r.config, r.routeQuestions))+// Agent WebSocket for AI command executionr.mux.HandleFunc("/api/agent/ws", r.handleAgentWebSocket)@@ -1487,6 +1490,65 @@ func (r *Router) routeOpenCodeSessions(w http.ResponseWriter, req *http.Request)}}+// routeApprovals routes approval-specific requests+func (r *Router) routeApprovals(w http.ResponseWriter, req *http.Request) {+ // Extract approval ID and action from path: /api/ai/approvals/{id}[/approve|/deny]+ path := strings.TrimPrefix(req.URL.Path, "/api/ai/approvals/")+ parts := strings.SplitN(path, "/", 2)++ if parts[0] == "" {+ http.Error(w, "Approval ID required", http.StatusBadRequest)+ return+ }++ // Check if there's an action+ if len(parts) > 1 {+ switch parts[1] {+ case "approve":+ r.aiSettingsHandler.HandleApproveCommand(w, req)+ case "deny":+ r.aiSettingsHandler.HandleDenyCommand(w, req)+ default:+ http.Error(w, "Not found", http.StatusNotFound)+ }+ return+ }++ // Handle approval-level operations (GET specific approval)+ switch req.Method {+ case http.MethodGet:+ r.aiSettingsHandler.HandleGetApproval(w, req)+ default:+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ }+}++// routeQuestions routes question-specific requests+func (r *Router) routeQuestions(w http.ResponseWriter, req *http.Request) {+ // Extract question ID and action from path: /api/ai/question/{id}/answer+ path := strings.TrimPrefix(req.URL.Path, "/api/ai/question/")+ parts := strings.SplitN(path, "/", 2)++ if parts[0] == "" {+ http.Error(w, "Question ID required", http.StatusBadRequest)+ return+ }++ questionID := parts[0]++ // Check if there's an action+ if len(parts) > 1 && parts[1] == "answer" {+ if req.Method == http.MethodPost {+ r.aiHandler.HandleAnswerQuestion(w, req, questionID)+ } else {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ }+ return+ }++ http.Error(w, "Not found", http.StatusNotFound)+}+// handleAgentWebSocket handles WebSocket connections from agents for AI command executionfunc (r *Router) handleAgentWebSocket(w http.ResponseWriter, req *http.Request) {if r.agentExecServer == nil {diff --git a/internal/config/api_tokens.go b/internal/config/api_tokens.goindex f0f5c015eb..654bbf0f82 100644--- a/internal/config/api_tokens.go+++ b/internal/config/api_tokens.go@@ -19,6 +19,7 @@ const (ScopeKubernetesReport = "kubernetes:report"ScopeKubernetesManage = "kubernetes:manage"ScopeHostReport = "host-agent:report"+ ScopeHostConfigRead = "host-agent:config:read"ScopeHostManage = "host-agent:manage"ScopeSettingsRead = "settings:read"ScopeSettingsWrite = "settings:write"@@ -33,6 +34,7 @@ var AllKnownScopes = []string{ScopeKubernetesReport,ScopeKubernetesManage,ScopeHostReport,+ ScopeHostConfigRead,ScopeHostManage,ScopeSettingsRead,ScopeSettingsWrite,diff --git a/internal/config/api_tokens_test.go b/internal/config/api_tokens_test.goindex ccb2007037..b8da7695ec 100644--- a/internal/config/api_tokens_test.go+++ b/internal/config/api_tokens_test.go@@ -170,6 +170,7 @@ func TestIsKnownScope(t *testing.T) {{name: "kubernetes:report", scope: ScopeKubernetesReport, expected: true},{name: "kubernetes:manage", scope: ScopeKubernetesManage, expected: true},{name: "host-agent:report", scope: ScopeHostReport, expected: true},+ {name: "host-agent:config:read", scope: ScopeHostConfigRead, expected: true},{name: "host-agent:manage", scope: ScopeHostManage, expected: true},{name: "settings:read", scope: ScopeSettingsRead, expected: true},{name: "settings:write", scope: ScopeSettingsWrite, expected: true},diff --git a/internal/config/persistence.go b/internal/config/persistence.goindex 682726a9db..be4a18bc75 100644--- a/internal/config/persistence.go+++ b/internal/config/persistence.go@@ -2179,6 +2179,14 @@ func (c *ConfigPersistence) LoadAgentProfiles() ([]models.AgentProfile, error) {return []models.AgentProfile{}, nil}+ if c.crypto != nil {+ if decrypted, err := c.crypto.Decrypt(data); err == nil {+ data = decrypted+ } else {+ log.Warn().Err(err).Msg("Failed to decrypt agent profiles - falling back to plaintext")+ }+ }+var profiles []models.AgentProfileif err := json.Unmarshal(data, &profiles); err != nil {return nil, err@@ -2197,6 +2205,14 @@ func (c *ConfigPersistence) SaveAgentProfiles(profiles []models.AgentProfile) erreturn err}+ if c.crypto != nil {+ encrypted, err := c.crypto.Encrypt(data)+ if err != nil {+ return err+ }+ data = encrypted+ }+if err := c.EnsureConfigDir(); err != nil {return err}@@ -2221,6 +2237,14 @@ func (c *ConfigPersistence) LoadAgentProfileAssignments() ([]models.AgentProfilereturn []models.AgentProfileAssignment{}, nil}+ if c.crypto != nil {+ if decrypted, err := c.crypto.Decrypt(data); err == nil {+ data = decrypted+ } else {+ log.Warn().Err(err).Msg("Failed to decrypt agent profile assignments - falling back to plaintext")+ }+ }+var assignments []models.AgentProfileAssignmentif err := json.Unmarshal(data, &assignments); err != nil {return nil, err@@ -2239,6 +2263,14 @@ func (c *ConfigPersistence) SaveAgentProfileAssignments(assignments []models.Agereturn err}+ if c.crypto != nil {+ encrypted, err := c.crypto.Encrypt(data)+ if err != nil {+ return err+ }+ data = encrypted+ }+if err := c.EnsureConfigDir(); err != nil {return err}@@ -2264,6 +2296,14 @@ func (c *ConfigPersistence) LoadAgentProfileVersions() ([]models.AgentProfileVerreturn []models.AgentProfileVersion{}, nil}+ if c.crypto != nil {+ if decrypted, err := c.crypto.Decrypt(data); err == nil {+ data = decrypted+ } else {+ log.Warn().Err(err).Msg("Failed to decrypt agent profile versions - falling back to plaintext")+ }+ }+var versions []models.AgentProfileVersionif err := json.Unmarshal(data, &versions); err != nil {return nil, err@@ -2282,6 +2322,14 @@ func (c *ConfigPersistence) SaveAgentProfileVersions(versions []models.AgentProfreturn err}+ if c.crypto != nil {+ encrypted, err := c.crypto.Encrypt(data)+ if err != nil {+ return err+ }+ data = encrypted+ }+if err := c.EnsureConfigDir(); err != nil {return err}@@ -2308,6 +2356,14 @@ func (c *ConfigPersistence) LoadProfileDeploymentStatus() ([]models.ProfileDeploreturn []models.ProfileDeploymentStatus{}, nil}+ if c.crypto != nil {+ if decrypted, err := c.crypto.Decrypt(data); err == nil {+ data = decrypted+ } else {+ log.Warn().Err(err).Msg("Failed to decrypt profile deployment status - falling back to plaintext")+ }+ }+var status []models.ProfileDeploymentStatusif err := json.Unmarshal(data, &status); err != nil {return nil, err@@ -2326,6 +2382,14 @@ func (c *ConfigPersistence) SaveProfileDeploymentStatus(status []models.ProfileDreturn err}+ if c.crypto != nil {+ encrypted, err := c.crypto.Encrypt(data)+ if err != nil {+ return err+ }+ data = encrypted+ }+if err := c.EnsureConfigDir(); err != nil {return err}diff --git a/internal/config/persistence_profiles_test.go b/internal/config/persistence_profiles_test.gonew file mode 100644index 0000000000..940e781381--- /dev/null+++ b/internal/config/persistence_profiles_test.go@@ -0,0 +1,111 @@+package config++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/crypto"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++func TestLoadProfileDataPlaintextWithCrypto(t *testing.T) {+ tempDir := t.TempDir()+ cp := NewConfigPersistence(tempDir)+ if err := cp.EnsureConfigDir(); err != nil {+ t.Fatalf("EnsureConfigDir: %v", err)+ }++ cm, err := crypto.NewCryptoManagerAt(tempDir)+ if err != nil {+ t.Fatalf("NewCryptoManagerAt: %v", err)+ }+ cp.crypto = cm++ writeJSON := func(name string, payload interface{}) {+ data, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("json.Marshal: %v", err)+ }+ if err := os.WriteFile(filepath.Join(tempDir, name), data, 0600); err != nil {+ t.Fatalf("WriteFile: %v", err)+ }+ }++ t.Run("AgentProfiles", func(t *testing.T) {+ writeJSON("agent_profiles.json", []models.AgentProfile{+ {+ ID: "profile-1",+ Name: "Prod",+ Version: 1,+ Config: models.AgentConfigMap{"interval": "1m"},+ },+ })++ profiles, err := cp.LoadAgentProfiles()+ if err != nil {+ t.Fatalf("LoadAgentProfiles: %v", err)+ }+ if len(profiles) != 1 || profiles[0].ID != "profile-1" {+ t.Fatalf("unexpected profiles: %+v", profiles)+ }+ })++ t.Run("Assignments", func(t *testing.T) {+ writeJSON("agent_profile_assignments.json", []models.AgentProfileAssignment{+ {+ AgentID: "agent-1",+ ProfileID: "profile-1",+ ProfileVersion: 1,+ },+ })++ assignments, err := cp.LoadAgentProfileAssignments()+ if err != nil {+ t.Fatalf("LoadAgentProfileAssignments: %v", err)+ }+ if len(assignments) != 1 || assignments[0].AgentID != "agent-1" {+ t.Fatalf("unexpected assignments: %+v", assignments)+ }+ })++ t.Run("Versions", func(t *testing.T) {+ writeJSON("profile-versions.json", []models.AgentProfileVersion{+ {+ ProfileID: "profile-1",+ Version: 1,+ Name: "Prod",+ Config: models.AgentConfigMap{"interval": "1m"},+ },+ })++ versions, err := cp.LoadAgentProfileVersions()+ if err != nil {+ t.Fatalf("LoadAgentProfileVersions: %v", err)+ }+ if len(versions) != 1 || versions[0].ProfileID != "profile-1" {+ t.Fatalf("unexpected versions: %+v", versions)+ }+ })++ t.Run("DeploymentStatus", func(t *testing.T) {+ writeJSON("profile-deployments.json", []models.ProfileDeploymentStatus{+ {+ AgentID: "agent-1",+ ProfileID: "profile-1",+ AssignedVersion: 1,+ DeployedVersion: 1,+ DeploymentStatus: "pending",+ },+ })++ status, err := cp.LoadProfileDeploymentStatus()+ if err != nil {+ t.Fatalf("LoadProfileDeploymentStatus: %v", err)+ }+ if len(status) != 1 || status[0].AgentID != "agent-1" {+ t.Fatalf("unexpected deployment status: %+v", status)+ }+ })+}diff --git a/internal/dockeragent/agent.go b/internal/dockeragent/agent.goindex bac94cab9a..0fdef7861c 100644--- a/internal/dockeragent/agent.go+++ b/internal/dockeragent/agent.go@@ -12,6 +12,7 @@ import ("os""os/exec""strings"+ "sync""time"systemtypes "github.com/docker/docker/api/types/system"@@ -92,6 +93,7 @@ type Agent struct {stateFilters []stringhostID stringprevContainerCPU map[string]cpuSample+ cpuMu sync.Mutex // protects prevContainerCPU and preCPUStatsFailurespreCPUStatsFailures intreportBuffer *buffer.Queue[agentsdocker.Report]registryChecker *RegistryChecker // For checking container image updatesdiff --git a/internal/dockeragent/collect.go b/internal/dockeragent/collect.goindex 0f306d04b0..fc3757243e 100644--- a/internal/dockeragent/collect.go+++ b/internal/dockeragent/collect.go@@ -220,6 +220,9 @@ func (a *Agent) collectContainers(ctx context.Context) ([]agentsdocker.Container}func (a *Agent) pruneStaleCPUSamples(active map[string]struct{}) {+ a.cpuMu.Lock()+ defer a.cpuMu.Unlock()+if len(a.prevContainerCPU) == 0 {return}@@ -269,7 +272,9 @@ func (a *Agent) collectContainer(ctx context.Context, summary containertypes.SummemUsage, memLimit, memPercent = calculateMemoryUsage(stats)blockIO = summarizeBlockIO(stats)} else {+ a.cpuMu.Lock()delete(a.prevContainerCPU, summary.ID)+ a.cpuMu.Unlock()}createdAt := time.Unix(summary.Created, 0)@@ -590,6 +595,9 @@ func extractPodmanMetadata(labels map[string]string) *agentsdocker.PodmanContain}func (a *Agent) calculateContainerCPUPercent(id string, stats containertypes.StatsResponse) float64 {+ a.cpuMu.Lock()+ defer a.cpuMu.Unlock()+current := cpuSample{totalUsage: stats.CPUStats.CPUUsage.TotalUsage,systemUsage: stats.CPUStats.SystemUsage,diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex abb51fd61e..98ae5a840c 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -1395,6 +1395,9 @@ func (m *Monitor) UnlinkHostAgent(hostID string) error {type HostAgentConfig struct {CommandsEnabled *bool `json:"commandsEnabled,omitempty"` // nil = use agent defaultSettings map[string]interface{} `json:"settings,omitempty"` // Merged profile settings+ IssuedAt *time.Time `json:"issuedAt,omitempty"`+ ExpiresAt *time.Time `json:"expiresAt,omitempty"`+ Signature string `json:"signature,omitempty"`}// GetHostAgentConfig returns the server-side configuration for a host agent.diff --git a/internal/remoteconfig/client.go b/internal/remoteconfig/client.goindex 83ad1e66e7..a5169c6f83 100644--- a/internal/remoteconfig/client.go+++ b/internal/remoteconfig/client.go@@ -9,6 +9,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/utils""github.com/rs/zerolog")@@ -35,6 +36,9 @@ type Response struct {Config struct {CommandsEnabled *bool `json:"commandsEnabled,omitempty"`Settings map[string]interface{} `json:"settings,omitempty"`+ IssuedAt time.Time `json:"issuedAt,omitempty"`+ ExpiresAt time.Time `json:"expiresAt,omitempty"`+ Signature string `json:"signature,omitempty"`} `json:"config"`}@@ -76,6 +80,7 @@ func (c *Client) Fetch(ctx context.Context) (map[string]interface{}, *bool, erroreturn nil, nil, fmt.Errorf("agent ID is required to fetch remote config")}+ signatureRequired := isConfigSignatureRequired()hostID := c.cfg.AgentIDif resolved, err := c.resolveHostID(ctx); err != nil {return nil, nil, err@@ -108,9 +113,41 @@ func (c *Client) Fetch(ctx context.Context) (map[string]interface{}, *bool, erroreturn nil, nil, fmt.Errorf("decode response: %w", err)}+ if configResp.Config.Signature != "" {+ if configResp.Config.IssuedAt.IsZero() || configResp.Config.ExpiresAt.IsZero() {+ return nil, nil, fmt.Errorf("config signature missing timestamp metadata")+ }+ now := time.Now().UTC()+ if now.After(configResp.Config.ExpiresAt.Add(2 * time.Minute)) {+ return nil, nil, fmt.Errorf("config signature expired")+ }+ if configResp.Config.IssuedAt.After(now.Add(2 * time.Minute)) {+ return nil, nil, fmt.Errorf("config signature issued in the future")+ }++ payload := SignedConfigPayload{+ HostID: configResp.HostID,+ IssuedAt: configResp.Config.IssuedAt,+ ExpiresAt: configResp.Config.ExpiresAt,+ CommandsEnabled: configResp.Config.CommandsEnabled,+ Settings: configResp.Config.Settings,+ }+ if err := VerifyConfigPayloadSignature(payload, configResp.Config.Signature); err != nil {+ return nil, nil, fmt.Errorf("config signature verification failed: %w", err)+ }+ } else if signatureRequired {+ return nil, nil, fmt.Errorf("config signature required but missing")+ } else if len(configResp.Config.Settings) > 0 || configResp.Config.CommandsEnabled != nil {+ c.cfg.Logger.Warn().Msg("Remote config response missing signature - skipping verification")+ }+return configResp.Config.Settings, configResp.Config.CommandsEnabled, nil}+func isConfigSignatureRequired() bool {+ return utils.ParseBool(utils.GetenvTrim("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED"))+}+func (c *Client) resolveHostID(ctx context.Context) (string, error) {hostname := strings.TrimSpace(c.cfg.Hostname)if hostname == "" {diff --git a/internal/remoteconfig/client_test.go b/internal/remoteconfig/client_test.goindex 6c55ab081e..665760781d 100644--- a/internal/remoteconfig/client_test.go+++ b/internal/remoteconfig/client_test.go@@ -4,6 +4,7 @@ import ("context""net/http""net/http/httptest"+ "strings""testing")@@ -57,6 +58,38 @@ func TestClient_Fetch(t *testing.T) {}})+ t.Run("signature required without signature", func(t *testing.T) {+ t.Setenv("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED", "true")+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{+ "success": true,+ "hostId": "agent-1",+ "config": {+ "commandsEnabled": true,+ "settings": {+ "interval": "1m"+ }+ }+ }`))+ }))+ defer ts.Close()++ client := New(Config{+ PulseURL: ts.URL,+ APIToken: "token-123",+ AgentID: "agent-1",+ })++ _, _, err := client.Fetch(context.Background())+ if err == nil {+ t.Fatal("Expected error, got nil")+ }+ if !strings.Contains(err.Error(), "signature required") {+ t.Fatalf("Expected signature required error, got %v", err)+ }+ })+t.Run("server error", func(t *testing.T) {ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusInternalServerError)diff --git a/internal/remoteconfig/signature.go b/internal/remoteconfig/signature.gonew file mode 100644index 0000000000..b0c8718d8c--- /dev/null+++ b/internal/remoteconfig/signature.go@@ -0,0 +1,253 @@+package remoteconfig++import (+ "crypto/ed25519"+ "crypto/x509"+ "encoding/base64"+ "encoding/json"+ "encoding/pem"+ "errors"+ "fmt"+ "sort"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/utils"+)++// trustedConfigPublicKeysPEM contains trusted Ed25519 public keys for config verification.+// In production builds, inject keys via ldflags to support rotation.+var trustedConfigPublicKeysPEM = []string{+ `-----BEGIN PUBLIC KEY-----+MCowBQYDK2VwAyEAlbXZQRx8jgMzwpXbbjOGcnA+9TG0lms/auxbPzY+Tdo=+-----END PUBLIC KEY-----`,+}++// SignedConfigPayload is the canonical payload used for config signing.+type SignedConfigPayload struct {+ HostID string+ IssuedAt time.Time+ ExpiresAt time.Time+ CommandsEnabled *bool+ Settings map[string]interface{}+}++// DecodeEd25519PrivateKey decodes a base64-encoded Ed25519 private key or seed.+func DecodeEd25519PrivateKey(encoded string) (ed25519.PrivateKey, error) {+ encoded = strings.TrimSpace(encoded)+ if encoded == "" {+ return nil, errors.New("empty signing key")+ }++ raw, err := base64.StdEncoding.DecodeString(encoded)+ if err != nil {+ return nil, fmt.Errorf("invalid base64 signing key: %w", err)+ }++ switch len(raw) {+ case ed25519.PrivateKeySize:+ return ed25519.PrivateKey(raw), nil+ case ed25519.SeedSize:+ return ed25519.NewKeyFromSeed(raw), nil+ default:+ return nil, fmt.Errorf("invalid signing key length: %d", len(raw))+ }+}++// SignConfigPayload signs the canonical config payload and returns a base64 signature.+func SignConfigPayload(payload SignedConfigPayload, privateKey ed25519.PrivateKey) (string, error) {+ if len(privateKey) == 0 {+ return "", errors.New("missing private key")+ }++ canonical, err := canonicalConfigPayload(payload)+ if err != nil {+ return "", err+ }++ signature := ed25519.Sign(privateKey, canonical)+ return base64.StdEncoding.EncodeToString(signature), nil+}++// VerifyConfigPayloadSignature verifies a base64 signature against the trusted public keys.+func VerifyConfigPayloadSignature(payload SignedConfigPayload, signatureBase64 string) error {+ if signatureBase64 == "" {+ return errors.New("missing signature")+ }++ canonical, err := canonicalConfigPayload(payload)+ if err != nil {+ return err+ }++ signature, err := base64.StdEncoding.DecodeString(signatureBase64)+ if err != nil {+ return fmt.Errorf("invalid base64 signature: %w", err)+ }++ keys, err := trustedConfigPublicKeys()+ if err != nil {+ return err+ }++ for _, key := range keys {+ if ed25519.Verify(key, canonical, signature) {+ return nil+ }+ }++ return errors.New("config signature verification failed against all trusted keys")+}++func canonicalConfigPayload(payload SignedConfigPayload) ([]byte, error) {+ type canonicalPayload struct {+ HostID string `json:"hostId"`+ IssuedAt string `json:"issuedAt"`+ ExpiresAt string `json:"expiresAt"`+ CommandsEnabled *bool `json:"commandsEnabled,omitempty"`+ Settings json.RawMessage `json:"settings,omitempty"`+ }++ var settings json.RawMessage+ if len(payload.Settings) > 0 {+ data, err := marshalSortedMap(payload.Settings)+ if err != nil {+ return nil, err+ }+ settings = data+ }++ canonical := canonicalPayload{+ HostID: payload.HostID,+ IssuedAt: payload.IssuedAt.UTC().Format(time.RFC3339Nano),+ ExpiresAt: payload.ExpiresAt.UTC().Format(time.RFC3339Nano),+ CommandsEnabled: payload.CommandsEnabled,+ Settings: settings,+ }++ return json.Marshal(canonical)+}++func trustedConfigPublicKeys() ([]ed25519.PublicKey, error) {+ raw := utils.GetenvTrim("PULSE_AGENT_CONFIG_PUBLIC_KEYS")+ if raw == "" {+ raw = strings.Join(trustedConfigPublicKeysPEM, "\n")+ }++ var keys []ed25519.PublicKey++ if strings.Contains(raw, "BEGIN PUBLIC KEY") {+ for {+ block, rest := pem.Decode([]byte(raw))+ if block == nil {+ break+ }+ raw = string(rest)+ if block.Type != "PUBLIC KEY" {+ continue+ }+ pub, err := x509.ParsePKIXPublicKey(block.Bytes)+ if err != nil {+ return nil, fmt.Errorf("failed to parse trusted public key: %w", err)+ }+ edPub, ok := pub.(ed25519.PublicKey)+ if !ok {+ return nil, errors.New("trusted key is not an Ed25519 public key")+ }+ keys = append(keys, edPub)+ }+ } else {+ parts := strings.Split(raw, ",")+ for _, part := range parts {+ part = strings.TrimSpace(part)+ if part == "" {+ continue+ }++ decoded, err := base64.StdEncoding.DecodeString(part)+ if err != nil {+ return nil, fmt.Errorf("invalid base64 public key: %w", err)+ }+ if len(decoded) == ed25519.PublicKeySize {+ keys = append(keys, ed25519.PublicKey(decoded))+ continue+ }++ pub, err := x509.ParsePKIXPublicKey(decoded)+ if err != nil {+ return nil, fmt.Errorf("failed to parse trusted public key: %w", err)+ }+ edPub, ok := pub.(ed25519.PublicKey)+ if !ok {+ return nil, errors.New("trusted key is not an Ed25519 public key")+ }+ keys = append(keys, edPub)+ }+ }++ if len(keys) == 0 {+ return nil, errors.New("no trusted config keys available")+ }++ return keys, nil+}++func marshalSortedMap(values map[string]interface{}) ([]byte, error) {+ if len(values) == 0 {+ return nil, nil+ }++ keys := make([]string, 0, len(values))+ for key := range values {+ keys = append(keys, key)+ }+ sort.Strings(keys)++ var builder strings.Builder+ builder.WriteByte('{')++ for i, key := range keys {+ if i > 0 {+ builder.WriteByte(',')+ }+ keyJSON, err := json.Marshal(key)+ if err != nil {+ return nil, err+ }+ valueJSON, err := marshalCanonicalValue(values[key])+ if err != nil {+ return nil, err+ }++ builder.Write(keyJSON)+ builder.WriteByte(':')+ builder.Write(valueJSON)+ }++ builder.WriteByte('}')+ return []byte(builder.String()), nil+}++func marshalCanonicalValue(value interface{}) ([]byte, error) {+ switch typed := value.(type) {+ case map[string]interface{}:+ return marshalSortedMap(typed)+ case []interface{}:+ var builder strings.Builder+ builder.WriteByte('[')+ for i, item := range typed {+ if i > 0 {+ builder.WriteByte(',')+ }+ itemJSON, err := marshalCanonicalValue(item)+ if err != nil {+ return nil, err+ }+ builder.Write(itemJSON)+ }+ builder.WriteByte(']')+ return []byte(builder.String()), nil+ default:+ return json.Marshal(typed)+ }+}diff --git a/internal/remoteconfig/signature_test.go b/internal/remoteconfig/signature_test.gonew file mode 100644index 0000000000..b732be371e--- /dev/null+++ b/internal/remoteconfig/signature_test.go@@ -0,0 +1,36 @@+package remoteconfig++import (+ "crypto/ed25519"+ "encoding/base64"+ "testing"+ "time"+)++func TestVerifyConfigPayloadSignature_WithEnvKey(t *testing.T) {+ pub, priv, err := ed25519.GenerateKey(nil)+ if err != nil {+ t.Fatalf("GenerateKey: %v", err)+ }++ payload := SignedConfigPayload{+ HostID: "host-1",+ IssuedAt: time.Now().UTC(),+ ExpiresAt: time.Now().UTC().Add(time.Minute),+ CommandsEnabled: nil,+ Settings: map[string]interface{}{+ "interval": "1m",+ },+ }++ sig, err := SignConfigPayload(payload, priv)+ if err != nil {+ t.Fatalf("SignConfigPayload: %v", err)+ }++ t.Setenv("PULSE_AGENT_CONFIG_PUBLIC_KEYS", base64.StdEncoding.EncodeToString(pub))++ if err := VerifyConfigPayloadSignature(payload, sig); err != nil {+ t.Fatalf("VerifyConfigPayloadSignature: %v", err)+ }+}diff --git a/scripts/dev-check.sh b/scripts/dev-check.shnew file mode 100755index 0000000000..71e6376668--- /dev/null+++ b/scripts/dev-check.sh@@ -0,0 +1,103 @@+#!/bin/bash+# Quick dev environment health check+# Run this before debugging frontend issues!+#+# Usage:+# ./scripts/dev-check.sh # Check and report+# ./scripts/dev-check.sh --kill # Kill all dev processes++RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+NC='\033[0m'++# Handle --kill flag+if [[ "${1:-}" == "--kill" ]]; then+ echo "Stopping all dev processes..."+ pkill -9 -f "bin/pulse$" 2>/dev/null || true+ pkill -9 -f "^\./pulse$" 2>/dev/null || true+ # Kill all OpenCode processes (pattern matches any opencode serve invocation)+ pkill -f "opencode.*serve" 2>/dev/null || true+ sleep 1+ pkill -9 -f "opencode.*serve" 2>/dev/null || true+ pkill -f "node.*vite" 2>/dev/null || true+ sleep 2+ echo -e "${GREEN}✓${NC} All dev processes stopped"+ exit 0+fi++echo "=== Pulse Dev Environment Check ==="+echo ""++# Check for duplicate Pulse processes (CRITICAL!)+# Count both installed binary and dev binary patterns+# Use tr to strip newlines for robustness+PULSE_COUNT_BIN=$(pgrep -c -f "bin/pulse$" 2>/dev/null | tr -d '\n' || echo 0)+PULSE_COUNT_DEV=$(pgrep -c -f "^\./pulse$" 2>/dev/null | tr -d '\n' || echo 0)+PULSE_COUNT=$(( ${PULSE_COUNT_BIN:-0} + ${PULSE_COUNT_DEV:-0} ))+echo -n "Pulse processes: "+if [[ $PULSE_COUNT -eq 0 ]]; then+ echo -e "${YELLOW}⚠ None running${NC}"+elif [[ $PULSE_COUNT -eq 1 ]]; then+ PULSE_PID=$(pgrep -f "bin/pulse$" 2>/dev/null || pgrep -f "^\./pulse$" 2>/dev/null || echo "?")+ echo -e "${GREEN}✓ 1 running (PID: $PULSE_PID)${NC}"+else+ echo -e "${RED}✗ MULTIPLE RUNNING ($PULSE_COUNT)! This causes database locks!${NC}"+ pgrep -af "pulse$" | grep -E "(bin/pulse|^\./pulse)" | head -5+ echo -e " ${YELLOW}Fix: ./scripts/dev-check.sh --kill${NC}"+fi++# Check Pulse backend connectivity+echo -n "Pulse backend (port 7655): "+if curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:7655/api/health 2>/dev/null | grep -q "200\|401\|403"; then+ echo -e "${GREEN}✓ Responding${NC}"+elif systemctl is-active --quiet pulse 2>/dev/null; then+ echo -e "${YELLOW}⚠ Service running but not responding${NC}"+else+ echo -e "${RED}✗ NOT RESPONDING${NC}"+fi++# Check Vite frontend+echo -n "Vite frontend (port 5173): "+if curl -s -o /dev/null http://127.0.0.1:5173/ 2>/dev/null; then+ echo -e "${GREEN}✓ Running${NC}"+else+ echo -e "${RED}✗ NOT RUNNING${NC}"+ echo " Fix: cd /opt/pulse/frontend-modern && npm run dev"+fi++# Check OpenCode sidecar+echo -n "OpenCode sidecar: "+# Count unique ports - each OpenCode instance runs as node + binary pair on same port+OPENCODE_PORTS=$(ps aux | grep -o "opencode.*--port [0-9]*" | grep -v grep | grep -o "[0-9]*$" | sort -u)+OPENCODE_COUNT=$(echo "$OPENCODE_PORTS" | grep -c . 2>/dev/null || echo 0)+OPENCODE_PORT=$(echo "$OPENCODE_PORTS" | head -1)+if [[ $OPENCODE_COUNT -eq 0 ]] || [[ -z "$OPENCODE_PORT" ]]; then+ echo -e "${YELLOW}⚠ Not detected (starts with AI features)${NC}"+elif [[ $OPENCODE_COUNT -gt 1 ]]; then+ echo -e "${RED}✗ MULTIPLE INSTANCES ($OPENCODE_COUNT)! This causes context loss!${NC}"+ echo " Ports: $OPENCODE_PORTS"+ echo -e " ${YELLOW}Fix: ./scripts/dev-check.sh --kill${NC}"+elif curl -s -o /dev/null http://127.0.0.1:$OPENCODE_PORT/config 2>/dev/null; then+ echo -e "${GREEN}✓ Running on port $OPENCODE_PORT${NC}"++ # Check MCP connection+ echo -n "MCP tools connection: "+ MCP_STATUS=$(curl -s http://127.0.0.1:$OPENCODE_PORT/mcp 2>/dev/null | grep -o '"status":"[^"]*"' | cut -d'"' -f4)+ if [[ "$MCP_STATUS" == "connected" ]]; then+ echo -e "${GREEN}✓ Connected${NC}"+ else+ echo -e "${RED}✗ Not connected (tools won't work)${NC}"+ echo -e " ${YELLOW}Fix: Restart Pulse to regenerate MCP config${NC}"+ fi+else+ echo -e "${YELLOW}⚠ Running but not responding${NC}"+fi++# Show recent errors+echo ""+echo "=== Recent Pulse Errors (last 5) ==="+journalctl -u pulse-dev --no-pager -n 20 2>/dev/null | grep -i "error\|fatal\|panic" | tail -5 || echo "None found"++echo ""+echo "Done."diff --git a/scripts/hot-dev.sh b/scripts/hot-dev.shindex e30426b9b4..3fd06c1bac 100755--- a/scripts/hot-dev.sh+++ b/scripts/hot-dev.sh@@ -201,14 +201,11 @@ kill_port() {log_info "Cleaning up existing processes..."# OS-Specific Cleanup+# Note: When running under systemd (INVOCATION_ID is set), skip stopping our own serviceOS_NAME=$(uname -s)-if [[ "$OS_NAME" == "Linux" ]]; then- if [[ -z "${INVOCATION_ID:-}" ]]; then- sudo systemctl stop pulse-hot-dev 2>/dev/null || true- fi- sudo systemctl stop pulse-backend 2>/dev/null || true- sudo systemctl stop pulse 2>/dev/null || true- sudo systemctl stop pulse-frontend 2>/dev/null || true+if [[ "$OS_NAME" == "Linux" ]] && [[ -z "${INVOCATION_ID:-}" ]]; then+ # Only stop pulse-dev if we're NOT running under systemd+ sudo systemctl stop pulse-dev 2>/dev/null || truefipkill -f "backend-watch.sh" 2>/dev/null || true@@ -414,6 +411,7 @@ log_info "Starting backend health monitor..."PULSE_DEV=${PULSE_DEV:-true} \PULSE_AUTH_USER=${PULSE_AUTH_USER} \PULSE_AUTH_PASS=${PULSE_AUTH_PASS} \+ ALLOWED_ORIGINS=${ALLOWED_ORIGINS} \./pulse >> /opt/pulse/hotdev.log 2>&1 &NEW_PID=$!sleep 2@@ -455,7 +453,17 @@ log_info "Starting backend file watcher..."# This prevents stale sidecars with lost session contextpkill -f "opencode.*serve" 2>/dev/null || true- FRONTEND_PORT=${PULSE_DEV_API_PORT} PORT=${PULSE_DEV_API_PORT} PULSE_DATA_DIR=${PULSE_DATA_DIR} PULSE_USE_OPENCODE=${PULSE_USE_OPENCODE:-true} ALLOW_ADMIN_BYPASS=${ALLOW_ADMIN_BYPASS:-1} PULSE_DEV=${PULSE_DEV:-true} ./pulse >> /opt/pulse/hotdev.log 2>&1 &+ FRONTEND_PORT=${PULSE_DEV_API_PORT} \+ PORT=${PULSE_DEV_API_PORT} \+ PULSE_DATA_DIR=${PULSE_DATA_DIR} \+ PULSE_ENCRYPTION_KEY=${PULSE_ENCRYPTION_KEY} \+ PULSE_USE_OPENCODE=${PULSE_USE_OPENCODE:-true} \+ ALLOW_ADMIN_BYPASS=${ALLOW_ADMIN_BYPASS:-1} \+ PULSE_DEV=${PULSE_DEV:-true} \+ PULSE_AUTH_USER=${PULSE_AUTH_USER} \+ PULSE_AUTH_PASS=${PULSE_AUTH_PASS} \+ ALLOWED_ORIGINS=${ALLOWED_ORIGINS} \+ ./pulse >> /opt/pulse/hotdev.log 2>&1 &NEW_PID=$!sleep 1