Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

feat(ai): embed OpenCode web UI in Pulse AI panel

rcourtman316c3cbb6fd3
diff --git a/.opencode/config.json b/.opencode/config.json
new file mode 100644
index 0000000000..f40e045693
--- /dev/null
+++ b/.opencode/config.json
@@ -0,0 +1,20 @@
+{
+ "$schema": "https://opencode.ai/config.schema.json",
+ "mcp": {
+ "pulse": {
+ "type": "http",
+ "url": "http://localhost:0",
+ "description": "Pulse infrastructure tools - URL is set dynamically at runtime"
+ }
+ },
+ "agent": {
+ "model": "claude-sonnet-4-20250514",
+ "tools": ["pulse_*"]
+ },
+ "instructions": [
+ "You are Pulse's AI assistant for infrastructure monitoring and management.",
+ "Use pulse_* tools to interact with the monitored infrastructure.",
+ "Be concise and direct in responses.",
+ "Focus on actionable insights and solutions."
+ ]
+}
diff --git a/frontend-modern/src/App.tsx b/frontend-modern/src/App.tsx
index b359c09433..d9f3bb5815 100644
--- a/frontend-modern/src/App.tsx
+++ b/frontend-modern/src/App.tsx
@@ -48,7 +48,7 @@ import { TokenRevealDialog } from './components/TokenRevealDialog';
import { useAlertsActivation } from './stores/alertsActivation';
import { UpdateProgressModal } from './components/UpdateProgressModal';
import type { UpdateStatus } from './api/updates';
-import { AIChat } from './components/AI/Chat';
+import { AIChat } from './components/AI/AIChat';
import { AIStatusIndicator } from './components/AI/AIStatusIndicator';
import { aiChatStore } from './stores/aiChat';
import { useResourcesAsLegacy } from './hooks/useResources';
diff --git a/frontend-modern/src/api/opencode.ts b/frontend-modern/src/api/opencode.ts
new file mode 100644
index 0000000000..6fdd7cb3e0
--- /dev/null
+++ b/frontend-modern/src/api/opencode.ts
@@ -0,0 +1,192 @@
+import { apiFetchJSON, apiFetch } from '@/utils/apiClient';
+import { logger } from '@/utils/logger';
+
+// OpenCode API - Simplified AI interface
+
+export interface ChatSession {
+ id: string;
+ title: string;
+ created_at: string;
+ updated_at: string;
+ message_count: number;
+}
+
+export interface ChatMessage {
+ id: string;
+ role: 'user' | 'assistant';
+ content: string;
+ timestamp: string;
+ model?: string;
+ tool_calls?: ToolCall[];
+}
+
+export interface ToolCall {
+ name: string;
+ input: string;
+ output: string;
+ success: boolean;
+}
+
+export interface StreamEvent {
+ type: 'content' | 'thinking' | 'tool_start' | 'tool_end' | 'tool' | 'done' | 'error';
+ data?: any;
+}
+
+export interface AIStatus {
+ running: boolean;
+ engine: string;
+}
+
+export class OpenCodeAPI {
+ private static baseUrl = '/api/ai';
+
+ // Get AI status
+ static async getStatus(): Promise<AIStatus> {
+ return apiFetchJSON(`${this.baseUrl}/status`) as Promise<AIStatus>;
+ }
+
+ // List all chat sessions
+ static async listSessions(): Promise<ChatSession[]> {
+ return apiFetchJSON(`${this.baseUrl}/sessions`) as Promise<ChatSession[]>;
+ }
+
+ // Create a new session
+ static async createSession(): Promise<ChatSession> {
+ return apiFetchJSON(`${this.baseUrl}/sessions`, {
+ method: 'POST',
+ }) as Promise<ChatSession>;
+ }
+
+ // Delete a session
+ static async deleteSession(sessionId: string): Promise<void> {
+ await apiFetch(`${this.baseUrl}/sessions/${sessionId}`, {
+ method: 'DELETE',
+ });
+ }
+
+ // Get messages for a session
+ static async getMessages(sessionId: string): Promise<ChatMessage[]> {
+ return apiFetchJSON(`${this.baseUrl}/sessions/${sessionId}/messages`) as Promise<ChatMessage[]>;
+ }
+
+ // Abort a session
+ static async abortSession(sessionId: string): Promise<void> {
+ await apiFetch(`${this.baseUrl}/sessions/${sessionId}/abort`, {
+ method: 'POST',
+ });
+ }
+
+ // Stream chat - the main chat interface
+ static async chat(
+ prompt: string,
+ sessionId: string | undefined,
+ model: string | undefined,
+ onEvent: (event: StreamEvent) => void,
+ signal?: AbortSignal
+ ): Promise<void> {
+ logger.debug('[OpenCode] Starting chat stream', { prompt: prompt.substring(0, 50) });
+
+ const response = await apiFetch(`${this.baseUrl}/chat`, {
+ method: 'POST',
+ body: JSON.stringify({
+ prompt,
+ session_id: sessionId,
+ model,
+ }),
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Accept': 'text/event-stream',
+ },
+ signal,
+ });
+
+ if (!response.ok) {
+ const text = await response.text();
+ throw new Error(text || `Request failed with status ${response.status}`);
+ }
+
+ const reader = response.body?.getReader();
+ if (!reader) {
+ throw new Error('No response body');
+ }
+
+ const decoder = new TextDecoder();
+ let buffer = '';
+ let lastEventTime = Date.now();
+ const STREAM_TIMEOUT_MS = 300000; // 5 minutes
+
+ try {
+ for (;;) {
+ if (Date.now() - lastEventTime > STREAM_TIMEOUT_MS) {
+ logger.warn('[OpenCode] Stream timeout');
+ break;
+ }
+
+ const readPromise = reader.read();
+ const timeoutPromise = new Promise<never>((_, reject) => {
+ setTimeout(() => reject(new Error('Read timeout')), STREAM_TIMEOUT_MS);
+ });
+
+ let result: ReadableStreamReadResult<Uint8Array>;
+ try {
+ result = await Promise.race([readPromise, timeoutPromise]);
+ } catch (e) {
+ if ((e as Error).message === 'Read timeout') break;
+ throw e;
+ }
+
+ const { done, value } = result;
+ if (done) break;
+
+ lastEventTime = Date.now();
+ const chunk = decoder.decode(value, { stream: true });
+ buffer += chunk;
+
+ // Process SSE messages
+ const normalizedBuffer = buffer.replace(/\r\n/g, '\n');
+ const messages = normalizedBuffer.split('\n\n');
+ buffer = messages.pop() || '';
+
+ for (const message of messages) {
+ if (!message.trim() || message.trim().startsWith(':')) continue;
+
+ const dataLines = message.split('\n').filter(line => line.startsWith('data: '));
+ for (const line of dataLines) {
+ try {
+ const jsonStr = line.slice(6);
+ if (!jsonStr.trim()) continue;
+
+ const event = JSON.parse(jsonStr) as StreamEvent;
+ logger.debug('[OpenCode] Event', { type: event.type });
+ onEvent(event);
+
+ if (event.type === 'done' || event.type === 'error') {
+ return;
+ }
+ } catch (e) {
+ logger.error('[OpenCode] Failed to parse event', { error: e, line });
+ }
+ }
+ }
+ }
+
+ // Process remaining buffer
+ if (buffer.trim() && buffer.trim().startsWith('data: ')) {
+ try {
+ const jsonStr = buffer.slice(6);
+ if (jsonStr.trim()) {
+ const event = JSON.parse(jsonStr) as StreamEvent;
+ onEvent(event);
+ }
+ } catch {
+ logger.warn('[OpenCode] Could not parse remaining buffer');
+ }
+ }
+
+ // Ensure done event
+ onEvent({ type: 'done' });
+ } finally {
+ reader.releaseLock();
+ }
+ }
+}
diff --git a/frontend-modern/src/components/AI/AIChat.tsx b/frontend-modern/src/components/AI/AIChat.tsx
index d120e264c7..edad0df140 100644
--- a/frontend-modern/src/components/AI/AIChat.tsx
+++ b/frontend-modern/src/components/AI/AIChat.tsx
@@ -1,906 +1,52 @@
-import { Component, Show, createSignal, For, createEffect, createMemo, onMount, Switch, Match } from 'solid-js';
-import { AIAPI } from '@/api/ai';
-import Sparkles from 'lucide-solid/icons/sparkles';
-import ExternalLink from 'lucide-solid/icons/external-link';
-import { getPatrolStatus, type PatrolStatus } from '@/api/patrol';
-import { notificationStore } from '@/stores/notifications';
-import { logger } from '@/utils/logger';
+import { Component, Show, createEffect, onMount, onCleanup } from 'solid-js';
import { aiChatStore } from '@/stores/aiChat';
-import { useWebSocket } from '@/App';
-import { GuestNotes } from './GuestNotes';
-import {
- PROVIDER_DISPLAY_NAMES,
- getGuestName,
- groupModelsByProvider,
- renderMarkdown,
- sanitizeThinking,
-} from './aiChatUtils';
-import type {
- AIToolExecution,
- AIStreamEvent,
- AIStreamToolStartData,
- AIStreamToolEndData,
- AIStreamCompleteData,
- AIStreamApprovalNeededData,
- ModelInfo,
-} from '@/types/ai';
-
-
-// In-progress tool execution (before completion)
-interface PendingTool {
- name: string;
- input: string;
-}
-
-// Command awaiting user approval
-interface PendingApproval {
- command: string;
- toolId: string;
- toolName: string;
- runOnHost: boolean;
- targetHost?: string; // Explicit host for command routing
- isExecuting?: boolean;
-}
-
-
-// Unified event type for chronological display
-interface StreamDisplayEvent {
- type: 'thinking' | 'tool' | 'content';
- thinking?: string;
- tool?: AIToolExecution;
- content?: string; // Text content chunk for chronological display
-}
-
-interface Message {
- id: string;
- role: 'user' | 'assistant';
- content: string;
- thinking?: string; // DeepSeek reasoning/thinking content (accumulated)
- thinkingChunks?: string[]; // Thinking split into sequential blocks for display
- streamEvents?: StreamDisplayEvent[]; // All events in chronological order
- timestamp: Date;
- model?: string;
- tokens?: { input: number; output: number };
- toolCalls?: AIToolExecution[];
- // Streaming state
- isStreaming?: boolean;
- pendingTools?: PendingTool[];
- pendingApprovals?: PendingApproval[];
-}
interface AIChatProps {
onClose: () => void;
}
+/**
+ * AIChat component - Embeds OpenCode's web UI in a slide-out panel.
+ *
+ * OpenCode provides the full chat experience including:
+ * - Message display and streaming
+ * - Tool execution visualization
+ * - Session management
+ * - Model selection
+ *
+ * Pulse provides infrastructure context via MCP tools.
+ */
export const AIChat: Component<AIChatProps> = (props) => {
- // Read all context from store for proper SolidJS reactivity
const isOpen = () => aiChatStore.isOpen;
- const context = () => aiChatStore.context;
- const targetType = () => context().targetType;
- const targetId = () => context().targetId;
- const contextData = () => context().context;
- const initialPrompt = () => context().initialPrompt;
- const findingId = () => context().findingId; // For resolving patrol findings
-
- // Access WebSocket state for listing available resources
- const wsContext = useWebSocket();
-
- // Context picker state
- const [showContextPicker, setShowContextPicker] = createSignal(false);
- const [contextSearch, setContextSearch] = createSignal('');
-
- // Session management state
- const [showSessionPicker, setShowSessionPicker] = createSignal(false);
-
- // Build a list of all available resources for the context picker
- const availableResources = createMemo(() => {
- const resources: Array<{
- id: string;
- type: 'vm' | 'container' | 'node' | 'host' | 'docker';
- name: string;
- status: string;
- node?: string;
- data: Record<string, unknown>;
- }> = [];
-
- // Add VMs
- for (const vm of wsContext.state.vms || []) {
- resources.push({
- id: `${vm.node}-${vm.vmid}`,
- type: 'vm',
- name: vm.name || `VM ${vm.vmid}`,
- status: vm.status,
- node: vm.node,
- data: {
- guest_id: `${vm.node}-${vm.vmid}`,
- guest_name: vm.name,
- guest_vmid: vm.vmid,
- guest_type: 'qemu',
- guest_node: vm.node,
- guest_status: vm.status,
- cpu: vm.cpu,
- mem: vm.memory?.used,
- maxmem: vm.memory?.total,
- disk: vm.disk?.used,
- maxdisk: vm.disk?.total,
- },
- });
- }
-
- // Add containers
- for (const ct of wsContext.state.containers || []) {
- resources.push({
- id: `${ct.node}-${ct.vmid}`,
- type: 'container',
- name: ct.name || `CT ${ct.vmid}`,
- status: ct.status,
- node: ct.node,
- data: {
- guest_id: `${ct.node}-${ct.vmid}`,
- guest_name: ct.name,
- guest_vmid: ct.vmid,
- guest_type: 'lxc',
- guest_node: ct.node,
- guest_status: ct.status,
- cpu: ct.cpu,
- mem: ct.memory?.used,
- maxmem: ct.memory?.total,
- disk: ct.disk?.used,
- maxdisk: ct.disk?.total,
- },
- });
- }
-
- // Add Proxmox nodes
- for (const node of wsContext.state.nodes || []) {
- resources.push({
- id: `node-${node.name}`,
- type: 'node',
- name: node.name,
- status: node.status,
- data: {
- node_name: node.name,
- node_status: node.status,
- cpu: node.cpu,
- mem: node.memory?.used,
- maxmem: node.memory?.total,
- disk: node.disk?.used,
- maxdisk: node.disk?.total,
- },
- });
- }
-
- // Add host agents
- for (const host of wsContext.state.hosts || []) {
- resources.push({
- id: `host-${host.hostname}`,
- type: 'host',
- name: host.hostname,
- status: host.status === 'online' ? 'online' : 'offline',
- data: {
- host_name: host.hostname,
- host_platform: host.platform,
- host_version: host.agentVersion,
- connected: host.status === 'online',
- },
- });
- }
-
- return resources;
- });
-
- // Filtered resources based on search
- const filteredResources = createMemo(() => {
- const search = contextSearch().toLowerCase();
- if (!search) return availableResources();
- return availableResources().filter(
- (r) =>
- r.name.toLowerCase().includes(search) ||
- r.type.toLowerCase().includes(search) ||
- (r.node && r.node.toLowerCase().includes(search))
- );
- });
-
- // Add a resource to context
- const addResourceToContext = (resource: ReturnType<typeof availableResources>[number]) => {
- aiChatStore.addContextItem(resource.type, resource.id, resource.name, resource.data);
- setShowContextPicker(false);
- setContextSearch('');
- };
-
- // Initialize messages from store (for persistence across navigation)
- const [messages, setMessagesLocal] = createSignal<Message[]>(
- aiChatStore.messages as Message[] || []
- );
- const [input, setInput] = createSignal('');
- const [isLoading, setIsLoading] = createSignal(false);
- const [queuedMessage, setQueuedMessage] = createSignal<string | null>(null);
-
- // Model selection
- const [availableModels, setAvailableModels] = createSignal<ModelInfo[]>([]);
- const [selectedModel, setSelectedModel] = createSignal<string>(''); // Empty = use default
- const [showModelSelector, setShowModelSelector] = createSignal(false);
-
- // Autonomous mode toggle
- const [autonomousMode, setAutonomousMode] = createSignal(false);
- const [isTogglingAutonomous, setIsTogglingAutonomous] = createSignal(false);
-
- // AI Patrol upgrade prompt state
- const [patrolStatus, setPatrolStatus] = createSignal<PatrolStatus | null>(null);
- const [upgradePromptDismissed, setUpgradePromptDismissed] = createSignal(false);
-
- // Show upgrade prompt when: user has sent a message, patrol requires license, and user hasn't dismissed
- const showUpgradePrompt = createMemo(() => {
- const status = patrolStatus();
- const hasMessages = messages().some(m => m.role === 'user');
- return hasMessages && status?.license_required === true && !upgradePromptDismissed();
- });
-
- let messagesEndRef: HTMLDivElement | undefined;
- let inputRef: HTMLTextAreaElement | undefined;
- let abortControllerRef: AbortController | null = null;
-
- // Fetch available models, settings, and patrol status on mount
- onMount(async () => {
- try {
- const [modelsResult, settingsResult, patrolStatusResult] = await Promise.all([
- AIAPI.getModels(),
- AIAPI.getSettings(),
- getPatrolStatus().catch(() => null), // Patrol may not be available
- ]);
- if (modelsResult.models && modelsResult.models.length > 0) {
- setAvailableModels(modelsResult.models.map(m => ({
- id: m.id,
- name: m.name || m.id,
- description: m.description,
- })));
- }
- if (settingsResult) {
- setAutonomousMode(settingsResult.autonomous_mode || false);
- }
- if (patrolStatusResult) {
- setPatrolStatus(patrolStatusResult);
- }
- } catch (_e) {
- // Silently fail - models will just not be selectable
- }
- });
+ let iframeRef: HTMLIFrameElement | undefined;
- // Toggle autonomous mode
- const toggleAutonomousMode = async () => {
- const newValue = !autonomousMode();
- setIsTogglingAutonomous(true);
- try {
- await AIAPI.updateSettings({ autonomous_mode: newValue });
- setAutonomousMode(newValue);
- notificationStore.success(newValue ? 'Autonomous mode enabled' : 'Autonomous mode disabled');
- } catch (_e) {
- notificationStore.error('Failed to toggle autonomous mode');
- } finally {
- setIsTogglingAutonomous(false);
- }
- };
-
- // Wrapper to sync messages to global store
- const setMessages = (updater: Message[] | ((prev: Message[]) => Message[])) => {
- setMessagesLocal((prev) => {
- const newMsgs = typeof updater === 'function' ? updater(prev) : updater;
- // Sync to global store for persistence (debounce or defer to avoid too many updates)
- setTimeout(() => aiChatStore.setMessages(newMsgs as any), 0);
- return newMsgs;
- });
- };
-
- // Auto-scroll to bottom when new messages arrive
- createEffect(() => {
- if (messages().length > 0 && messagesEndRef) {
- messagesEndRef.scrollIntoView({ behavior: 'smooth' });
- }
- });
-
- // Focus input when drawer opens and register with store for keyboard shortcuts
- createEffect(() => {
- if (isOpen() && inputRef) {
- setTimeout(() => inputRef?.focus(), 100);
- aiChatStore.registerInput(inputRef);
- } else {
- aiChatStore.registerInput(null);
- }
- });
-
- // Handle initial prompt if provided
+ // Focus iframe when panel opens for keyboard navigation
createEffect(() => {
- if (initialPrompt() && isOpen()) {
- setInput(initialPrompt()!);
+ if (isOpen() && iframeRef) {
+ setTimeout(() => iframeRef?.focus(), 100);
}
});
- // Sync messages from store when session changes (e.g., newConversation, switchSession)
- // Track sessionId to detect when we need to reload messages from store
- createEffect(() => {
- void aiChatStore.sessionId; // Track session changes (creates reactive dependency)
- // When session changes, sync messages from store to local state
- const storeMessages = aiChatStore.messages as Message[] || [];
- setMessagesLocal(storeMessages);
- });
-
- // Auto-send queued message when AI finishes processing
- createEffect(() => {
- const loading = isLoading();
- const queued = queuedMessage();
-
- // When loading finishes and we have a queued message, send it
- if (!loading && queued) {
- logger.info('[AIChat] AI finished, auto-sending queued message', { prompt: queued.substring(0, 50) });
- setQueuedMessage(null);
- // Small delay to let the UI update first
- setTimeout(() => {
- handleSubmit(undefined, queued);
- }, 100);
- }
- });
-
- const generateId = () => Math.random().toString(36).substring(2, 9);
-
- // Stop/cancel the current AI request
- const handleStop = () => {
- if (abortControllerRef) {
- abortControllerRef.abort();
- abortControllerRef = null;
- }
- // Mark any streaming message as stopped
- setMessages((prev) =>
- prev.map((msg) =>
- msg.isStreaming
- ? { ...msg, isStreaming: false, content: msg.content || '(Stopped by user)' }
- : msg
- )
- );
- // Clear queued message when stopping - user likely doesn't want it sent
- setQueuedMessage(null);
- setIsLoading(false);
- };
-
- const handleSubmit = async (e?: Event, forcePrompt?: string) => {
- e?.preventDefault();
- const prompt = forcePrompt || input().trim();
- if (!prompt) return;
-
- // If AI is currently working, queue this message for later
- if (isLoading() && !forcePrompt) {
- setQueuedMessage(prompt);
- setInput('');
- logger.info('[AIChat] Message queued while AI is working', { prompt: prompt.substring(0, 50) });
- return;
- }
-
- // IMPORTANT: Capture the current messages BEFORE adding new ones to avoid race conditions
- // SolidJS batches updates, so messages() may not be updated synchronously
- const previousMessages = messages();
-
- // Build conversation history from previous messages (before we add new ones)
- // Include tool call outputs so the AI remembers what commands were run
- const history = previousMessages
- .filter((m) => !m.isStreaming) // Only include completed messages
- .filter((m) => m.content || (m.toolCalls && m.toolCalls.length > 0)) // Must have content or tool calls
- .map((m) => {
- let content = m.content || '';
-
- // For assistant messages, prepend tool call outputs so AI has full context
- if (m.role === 'assistant' && m.toolCalls && m.toolCalls.length > 0) {
- const toolSummary = m.toolCalls
- .map((tc) => `Command: ${tc.input}\nOutput: ${tc.output}`)
- .join('\n\n');
- content = toolSummary + (content ? '\n\n' + content : '');
- }
-
- return {
- role: m.role,
- content,
- };
- })
- .filter((m) => m.content); // Filter out any empty messages
-
- // Add user message
- const userMessage: Message = {
- id: generateId(),
- role: 'user',
- content: prompt,
- timestamp: new Date(),
- };
- setMessages((prev) => [...prev, userMessage]);
- setInput('');
- setIsLoading(true);
-
- // Create abort controller for this request
- abortControllerRef = new AbortController();
-
- // Create a streaming assistant message
- const assistantId = generateId();
- const streamingMessage: Message = {
- id: assistantId,
- role: 'assistant',
- content: '',
- timestamp: new Date(),
- isStreaming: true,
- pendingTools: [],
- pendingApprovals: [],
- toolCalls: [],
- thinkingChunks: [],
- streamEvents: [],
- };
- setMessages((prev) => [...prev, streamingMessage]);
-
- // Safety timeout - clear streaming state if we don't get any completion event
- // This prevents the UI from getting stuck in a streaming state
- let lastEventTime = Date.now();
- const SAFETY_TIMEOUT_MS = 120000; // 2 minutes
-
- const safetyCheckInterval = setInterval(() => {
- const timeSinceLastEvent = Date.now() - lastEventTime;
- if (timeSinceLastEvent > SAFETY_TIMEOUT_MS) {
- logger.warn('[AIChat] Safety timeout - forcing stream completion', { seconds: SAFETY_TIMEOUT_MS / 1000 });
- clearInterval(safetyCheckInterval);
- setMessages((prev) =>
- prev.map((msg) =>
- msg.id === assistantId && msg.isStreaming
- ? { ...msg, isStreaming: false, content: msg.content || '(Request timed out - no response received)' }
- : msg
- )
- );
- setIsLoading(false);
- if (abortControllerRef) {
- abortControllerRef.abort();
- abortControllerRef = null;
- }
- }
- }, 10000); // Check every 10 seconds
-
- try {
- await AIAPI.executeStream(
- {
- prompt,
- target_type: targetType(),
- target_id: targetId(),
- context: contextData(),
- history: history.length > 0 ? history : undefined,
- finding_id: findingId(), // Pass finding ID so AI can resolve it when fixed
- model: selectedModel() || undefined, // Use selected model or default
- },
- (event: AIStreamEvent) => {
- lastEventTime = Date.now(); // Update last event time
- logger.debug('[AIChat] Received event', { type: event.type, event });
- // Update the streaming message based on event type
- setMessages((prev) =>
- prev.map((msg) => {
- if (msg.id !== assistantId) return msg;
-
- switch (event.type) {
- case 'tool_start': {
- const data = event.data as AIStreamToolStartData;
- return {
- ...msg,
- pendingTools: [...(msg.pendingTools || []), { name: data.name, input: data.input }],
- };
- }
- case 'tool_end': {
- const data = event.data as AIStreamToolEndData;
- // Remove one pending tool with matching name
- const pendingTools = msg.pendingTools || [];
- const matchingIndex = pendingTools.findIndex((t) => t.name === data.name);
- const updatedPending = matchingIndex >= 0
- ? [...pendingTools.slice(0, matchingIndex), ...pendingTools.slice(matchingIndex + 1)]
- : pendingTools;
- // Use input directly from tool_end event (authoritative)
- const newToolCall: AIToolExecution = {
- name: data.name,
- input: data.input,
- output: data.output,
- success: data.success,
- };
- // Add to both toolCalls and streamEvents for chronological display
- const events = msg.streamEvents || [];
-
- // Emit event for metadata refresh if AI set a resource URL
- if (data.name === 'set_resource_url' && data.success) {
- let payload;
- try {
- // Optimistically parse the input to pass relevant data for immediate update
- const parsedInput = JSON.parse(data.input);
- // Handle both new 'resource_id' field and legacy 'id'/'guest_id' fields
- const id = parsedInput.resource_id || parsedInput.guest_id || parsedInput.id;
- if (id && typeof parsedInput.url !== 'undefined') {
- payload = { guestId: id, url: parsedInput.url };
- }
- } catch (e) {
- logger.warn('[AIChat] Failed to parse set_resource_url input for optimistic update', e);
- }
-
- logger.info('[AIChat] Emitting metadata-changed event for set_resource_url', { payload });
- window.dispatchEvent(new CustomEvent('pulse:metadata-changed', {
- detail: { source: 'ai', tool: data.name, payload }
- }));
- }
-
- return {
- ...msg,
- pendingTools: updatedPending,
- toolCalls: [...(msg.toolCalls || []), newToolCall],
- streamEvents: [...events, { type: 'tool' as const, tool: newToolCall }],
- };
- }
- case 'thinking': {
- const chunk = event.data as string;
- if (!chunk.trim()) return msg; // Skip empty chunks
- // Each thinking event is a new chunk - add to both arrays
- const chunks = msg.thinkingChunks || [];
- const events = msg.streamEvents || [];
- return {
- ...msg,
- thinking: (msg.thinking || '') + chunk,
- thinkingChunks: [...chunks, chunk.trim()],
- streamEvents: [...events, { type: 'thinking' as const, thinking: chunk.trim() }],
- };
- }
- case 'content': {
- const content = event.data as string;
- if (!content.trim()) return msg; // Skip empty content
- // Track content in streamEvents for chronological display
- const events = msg.streamEvents || [];
- // Also accumulate in content for backwards compatibility / summary
- const existingContent = msg.content || '';
- const separator = existingContent && !existingContent.endsWith('\n') ? '\n\n' : '';
- return {
- ...msg,
- content: existingContent + separator + content,
- streamEvents: [...events, { type: 'content' as const, content: content.trim() }],
- };
- }
- case 'complete': {
- // Complete event has flat structure (model, input_tokens at top level, not under data)
- const completeEvent = event as unknown as AIStreamCompleteData & { type: string };
- return {
- ...msg,
- isStreaming: false,
- pendingTools: [],
- model: completeEvent.model,
- tokens: {
- input: completeEvent.input_tokens,
- output: completeEvent.output_tokens,
- },
- // Use tool_calls from complete if we missed any
- toolCalls: msg.toolCalls?.length ? msg.toolCalls : completeEvent.tool_calls,
- };
- }
- case 'done': {
- return {
- ...msg,
- isStreaming: false,
- pendingTools: [],
- };
- }
- case 'error': {
- const errorMsg = event.data as string;
- return {
- ...msg,
- isStreaming: false,
- pendingTools: [],
- content: `Error: ${errorMsg}`,
- };
- }
- case 'processing': {
- // Show processing status for multi-iteration calls
- const status = event.data as string;
- logger.debug('[AIChat] Processing', status);
- // Add as a pending tool for visual feedback
- return {
- ...msg,
- pendingTools: [{ name: 'processing', input: status }],
- };
- }
- case 'approval_needed': {
- const data = event.data as AIStreamApprovalNeededData;
- return {
- ...msg,
- pendingApprovals: [...(msg.pendingApprovals || []), {
- command: data.command,
- toolId: data.tool_id,
- toolName: data.tool_name,
- runOnHost: data.run_on_host ?? false, // Default to false if undefined
- targetHost: data.target_host, // Pass through the explicit routing target
- }],
- };
- }
-
- default:
- return msg;
- }
- })
- );
- },
- abortControllerRef?.signal
- );
- } catch (error) {
- // Don't show error for user-initiated abort
- if (error instanceof Error && error.name === 'AbortError') {
- logger.debug('[AIChat] Request aborted by user');
- return;
- }
- logger.error('[AIChat] Execute failed:', error);
- const errorMessage = error instanceof Error ? error.message : 'Failed to get AI response';
- notificationStore.error(errorMessage);
-
- // Update the streaming message to show error
- setMessages((prev) =>
- prev.map((msg) =>
- msg.id === assistantId
- ? { ...msg, isStreaming: false, content: `Error: ${errorMessage}` }
- : msg
- )
- );
- } finally {
- clearInterval(safetyCheckInterval);
- abortControllerRef = null;
- setIsLoading(false);
- }
- };
-
+ // Handle escape key to close panel
const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Enter' && !e.shiftKey) {
- e.preventDefault();
- handleSubmit();
+ if (e.key === 'Escape' && isOpen()) {
+ props.onClose();
}
};
- // Execute an approved command
- const executeApprovedCommand = async (messageId: string, approval: PendingApproval) => {
- // Mark as executing
- setMessages((prev) =>
- prev.map((m) =>
- m.id === messageId
- ? {
- ...m,
- pendingApprovals: m.pendingApprovals?.map((a) =>
- a.toolId === approval.toolId ? { ...a, isExecuting: true } : a
- ),
- }
- : m
- )
- );
-
- try {
- // Extract VMID from context if available
- const vmid = contextData()?.vmid as string | undefined;
-
- const result = await AIAPI.runCommand({
- command: approval.command,
- target_type: targetType() || '',
- target_id: targetId() || '',
- run_on_host: approval.runOnHost,
- vmid,
- target_host: approval.targetHost, // Pass through the explicit routing target
- });
-
-
- // Move from pending approvals to completed tool calls
- const currentMessages = messages();
- const targetMessage = currentMessages.find((m) => m.id === messageId);
- const pendingCount = targetMessage?.pendingApprovals?.length || 0;
- const remainingAfterThis = (targetMessage?.pendingApprovals?.filter((a) => a.toolId !== approval.toolId) || []).length;
-
- logger.info('[AIChat] Approval processed', {
- messageId,
- toolId: approval.toolId,
- pendingCount,
- remainingAfterThis,
- pendingApprovals: targetMessage?.pendingApprovals?.map(a => a.toolId)
- });
-
- setMessages((prev) =>
- prev.map((m) => {
- if (m.id !== messageId) return m;
-
- const newToolCall: AIToolExecution = {
- name: approval.toolName,
- input: approval.command,
- output: result.output || result.error || '',
- success: result.success,
- };
-
- const remainingApprovals = m.pendingApprovals?.filter((a) => a.toolId !== approval.toolId) || [];
- const existingEvents = m.streamEvents || [];
-
- return {
- ...m,
- pendingApprovals: remainingApprovals,
- toolCalls: [...(m.toolCalls || []), newToolCall],
- // Also add to streamEvents so it appears in the chronological view
- streamEvents: [...existingEvents, { type: 'tool' as const, tool: newToolCall }],
- // Clear the stale "I need approval" content after the last approval is processed
- // The tool output will show the result instead
- content: remainingApprovals.length === 0 ? '' : m.content,
- };
- })
- );
-
- // No toast for success - the tool output shows the result inline
- // Only show error toast for failures since they might need attention
- if (!result.success && result.error) {
- notificationStore.error(result.error);
- }
-
- // After the last approval is processed, automatically continue the conversation
- // This lets the AI analyze the command output and provide a summary
- if (remainingAfterThis === 0) {
- logger.info('[AIChat] Last approval processed, triggering auto-continuation');
- // Small delay to let the UI update first
- setTimeout(async () => {
- logger.info('[AIChat] Starting auto-continuation');
- setIsLoading(true);
-
- // Build history including the just-executed command
- const currentMsgs = messages();
- logger.debug('[AIChat] Building history for continuation', { messageCount: currentMsgs.length });
-
- const historyForContinuation = currentMsgs
- .filter((m) => !m.isStreaming)
- .filter((m) => m.content || (m.toolCalls && m.toolCalls.length > 0))
- .map((m) => {
- let content = m.content || '';
- if (m.role === 'assistant' && m.toolCalls && m.toolCalls.length > 0) {
- const toolSummary = m.toolCalls
- .map((tc) => `Command: ${tc.input}\nOutput: ${tc.output}`)
- .join('\n\n');
- content = toolSummary + (content ? '\n\n' + content : '');
- }
- return { role: m.role, content };
- })
- .filter((m) => m.content);
-
- logger.debug('[AIChat] History for continuation built', { historyLength: historyForContinuation.length });
-
- // Add a hidden continuation prompt - the AI will see it but user won't
- const continuationPrompt = 'Continue analyzing the command output above and provide a summary.';
-
- // Create the streaming assistant response message (no visible user message)
- // Show "Analyzing..." as initial content so user sees inline feedback
- const assistantId = generateId();
- const streamingMessage: Message = {
- id: assistantId,
- role: 'assistant',
- content: '*Analyzing results...*',
- timestamp: new Date(),
- isStreaming: true,
- pendingTools: [],
- pendingApprovals: [],
- toolCalls: [],
- };
- setMessages((prev) => [...prev, streamingMessage]);
-
- try {
- logger.info('[AIChat] Calling executeStream for continuation');
- await AIAPI.executeStream(
- {
- prompt: continuationPrompt,
- target_type: targetType() || undefined,
- target_id: targetId() || undefined,
- context: contextData() || undefined,
- history: historyForContinuation.length > 0 ? historyForContinuation : undefined,
- },
- (event: AIStreamEvent) => {
- logger.debug('[AIChat] Continuation event received', { type: event.type });
- setMessages((prev) =>
- prev.map((msg) => {
- if (msg.id !== assistantId) return msg;
- switch (event.type) {
- case 'content': {
- // Append content, but filter out the initial placeholder
- const content = event.data as string;
- const existingContent = msg.content === '*Analyzing results...*' ? '' : (msg.content || '');
- const separator = existingContent && !existingContent.endsWith('\n') ? '\n\n' : '';
- return { ...msg, content: existingContent + separator + content, isStreaming: false };
- }
- case 'done':
- return { ...msg, isStreaming: false };
- case 'error':
- return { ...msg, content: `Error: ${event.data}`, isStreaming: false };
- case 'thinking':
- // Ignore thinking events for now
- return msg;
- case 'processing':
- // Ignore processing events
- return msg;
- case 'tool_start': {
- const data = event.data as { name: string; input: string };
- return {
- ...msg,
- pendingTools: [...(msg.pendingTools || []), { name: data.name, input: data.input }],
- };
- }
- case 'tool_end': {
- const data = event.data as { name: string; input: string; output: string; success: boolean };
- const pendingTools = msg.pendingTools || [];
- const matchingIndex = pendingTools.findIndex((t) => t.name === data.name);
- const updatedPending = matchingIndex >= 0
- ? [...pendingTools.slice(0, matchingIndex), ...pendingTools.slice(matchingIndex + 1)]
- : pendingTools;
- return {
- ...msg,
- pendingTools: updatedPending,
- toolCalls: [...(msg.toolCalls || []), {
- name: data.name,
- input: data.input,
- output: data.output,
- success: data.success,
- }],
- };
- }
- case 'approval_needed': {
- const data = event.data as AIStreamApprovalNeededData;
- logger.info('[AIChat] Approval needed in continuation', { command: data.command });
- return {
- ...msg,
- pendingApprovals: [...(msg.pendingApprovals || []), {
- command: data.command,
- toolId: data.tool_id,
- toolName: data.tool_name,
- runOnHost: data.run_on_host,
- targetHost: data.target_host,
- }],
- isStreaming: false, // Stop streaming when approval is needed
- };
- }
- default:
- logger.debug('[AIChat] Unhandled continuation event', { type: event.type, event });
- return msg;
- }
- })
- );
- }
- );
- logger.info('[AIChat] Continuation executeStream completed');
- } catch (err) {
- logger.error('[AIChat] Failed to continue after approval:', err);
- setMessages((prev) =>
- prev.map((msg) =>
- msg.id === assistantId
- ? { ...msg, content: 'Failed to analyze results.', isStreaming: false }
- : msg
- )
- );
- } finally {
- setIsLoading(false);
- }
- }, 200);
- } else {
- logger.debug('[AIChat] Approvals remaining, not triggering continuation', { remainingAfterThis });
- }
- } catch (error) {
- logger.error('[AIChat] Failed to execute approved command:', error);
- const errorMsg = error instanceof Error ? error.message : 'Failed to execute command';
- notificationStore.error(errorMsg);
+ onMount(() => {
+ document.addEventListener('keydown', handleKeyDown);
+ });
- // Mark as no longer executing
- setMessages((prev) =>
- prev.map((m) =>
- m.id === messageId
- ? {
- ...m,
- pendingApprovals: m.pendingApprovals?.map((a) =>
- a.toolId === approval.toolId ? { ...a, isExecuting: false } : a
- ),
- }
- : m
- )
- );
- }
- };
+ onCleanup(() => {
+ document.removeEventListener('keydown', handleKeyDown);
+ });
- // Panel renders as flex child, width controlled by isOpen state
return (
<div
- class={`flex-shrink-0 h-full bg-white dark:bg-gray-900 border-l border-gray-200 dark:border-gray-700 flex flex-col transition-all duration-300 overflow-hidden ${isOpen() ? 'w-[420px]' : 'w-0 border-l-0'
- }`}
+ class={`flex-shrink-0 h-full bg-white dark:bg-gray-900 border-l border-gray-200 dark:border-gray-700 flex flex-col transition-all duration-300 overflow-hidden ${
+ isOpen() ? 'w-[500px]' : 'w-0 border-l-0'
+ }`}
>
<Show when={isOpen()}>
{/* Header */}
@@ -923,228 +69,37 @@ export const AIChat: Component<AIChatProps> = (props) => {
</div>
<div>
<h2 class="text-sm font-semibold text-gray-900 dark:text-gray-100">
- <Show when={getGuestName(contextData())} fallback="AI Assistant">
- Ask AI about {getGuestName(contextData())}
- </Show>
+ AI Assistant
</h2>
- <Show when={targetType()}>
- <p class="text-xs text-gray-500 dark:text-gray-400">
- {targetType() === 'vm' ? 'Virtual Machine' : targetType() === 'container' ? 'LXC Container' : targetType()}
- </p>
- </Show>
+ <p class="text-xs text-gray-500 dark:text-gray-400">
+ Powered by OpenCode
+ </p>
</div>
</div>
<div class="flex items-center gap-2">
- {/* Model selector dropdown */}
- <Show when={availableModels().length > 0}>
- <div class="relative">
- <button
- onClick={() => setShowModelSelector(!showModelSelector())}
- class="flex items-center gap-1 px-2 py-1 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 rounded border border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 bg-white dark:bg-gray-800"
- title="Select AI model"
- >
- <svg class="w-3 h-3" 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-[80px] truncate">
- {selectedModel() || 'Default'}
- </span>
- <svg class="w-3 h-3" 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-64 max-h-80 overflow-y-auto bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-50 py-1">
- <button
- onClick={() => { setSelectedModel(''); setShowModelSelector(false); }}
- class={`w-full px-3 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 ${!selectedModel() ? 'bg-blue-50 dark:bg-blue-900/30' : ''}`}
- >
- <div class="font-medium text-gray-900 dark:text-gray-100">Default</div>
- <div class="text-xs text-gray-500 dark:text-gray-400">Use configured default model</div>
- </button>
- <For each={Array.from(groupModelsByProvider(availableModels()).entries())}>
- {([provider, models]) => (
- <>
- <div class="px-3 py-1.5 text-xs font-semibold text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-700/50 sticky top-0">
- {PROVIDER_DISPLAY_NAMES[provider] || provider}
- </div>
- <For each={models}>
- {(model) => (
- <button
- onClick={() => { setSelectedModel(model.id); setShowModelSelector(false); }}
- class={`w-full px-3 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 ${selectedModel() === model.id ? 'bg-blue-50 dark:bg-blue-900/30' : ''}`}
- >
- <div class="font-medium text-gray-900 dark:text-gray-100">
- {model.name || model.id.split(':').pop()}
- </div>
- </button>
- )}
- </For>
- </>
- )}
- </For>
- </div>
- </Show>
- </div>
- </Show>
- {/* Autonomous Mode toggle */}
- <button
- onClick={toggleAutonomousMode}
- disabled={isTogglingAutonomous()}
- class={`p-2 rounded-lg transition-colors ${autonomousMode()
- ? 'text-amber-600 dark:text-amber-400 bg-amber-100 dark:bg-amber-900/40 hover:bg-amber-200 dark:hover:bg-amber-900/60'
- : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800'
- } ${isTogglingAutonomous() ? 'opacity-50 cursor-wait' : ''}`}
- title={autonomousMode() ? 'Autonomous Mode: ON (commands run without approval)' : 'Autonomous Mode: OFF (commands need approval)'}
+ {/* Open in new tab */}
+ <a
+ href="/opencode/"
+ target="_blank"
+ rel="noopener noreferrer"
+ class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800"
+ title="Open in new tab"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
- d="M13 10V3L4 14h7v7l9-11h-7z"
+ d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
/>
</svg>
- </button>
- {/* Session management dropdown */}
- <div class="relative">
- <button
- onClick={() => {
- setShowSessionPicker(!showSessionPicker());
- if (!showSessionPicker()) {
- aiChatStore.refreshSessions();
- }
- }}
- class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800"
- title="Chat sessions"
- >
- <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"
- />
- </svg>
- </button>
- <Show when={showSessionPicker()}>
- <div class="absolute right-0 top-full mt-1 w-72 max-h-96 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 z-50 overflow-hidden">
- {/* New conversation button */}
- <button
- onClick={() => {
- aiChatStore.newConversation();
- setShowSessionPicker(false);
- }}
- class="w-full px-3 py-2.5 text-left text-sm flex items-center gap-2 text-purple-600 dark:text-purple-400 hover:bg-purple-50 dark:hover:bg-purple-900/20 border-b border-gray-200 dark:border-gray-700"
- >
- <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
- </svg>
- <span class="font-medium">New conversation</span>
- </button>
-
- {/* Session list */}
- <div class="max-h-64 overflow-y-auto">
- <Show when={aiChatStore.sessions.length > 0} fallback={
- <div class="px-3 py-4 text-center text-xs text-gray-500 dark:text-gray-400">
- No previous conversations
- </div>
- }>
- <For each={aiChatStore.sessions}>
- {(session) => {
- const isCurrentSession = () => session.id === aiChatStore.sessionId;
- const sessionDate = new Date(session.updated_at);
- const isToday = sessionDate.toDateString() === new Date().toDateString();
- const dateStr = isToday
- ? sessionDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
- : sessionDate.toLocaleDateString([], { month: 'short', day: 'numeric' });
-
- return (
- <div
- class={`group relative px-3 py-2 flex items-start gap-2 hover:bg-gray-50 dark:hover:bg-gray-700/50 cursor-pointer ${isCurrentSession() ? 'bg-purple-50 dark:bg-purple-900/20' : ''
- }`}
- onClick={() => {
- if (!isCurrentSession()) {
- aiChatStore.switchSession(session.id);
- }
- setShowSessionPicker(false);
- }}
- >
- <div class="flex-1 min-w-0">
- <div class="flex items-center gap-2">
- <span class={`text-sm font-medium truncate ${isCurrentSession()
- ? 'text-purple-700 dark:text-purple-300'
- : 'text-gray-900 dark:text-gray-100'
- }`}>
- {session.title || 'Untitled conversation'}
- </span>
- <Show when={isCurrentSession()}>
- <span class="flex-shrink-0 w-1.5 h-1.5 rounded-full bg-purple-500" />
- </Show>
- </div>
- <div class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
- <span>{session.message_count} messages</span>
- <span>·</span>
- <span>{dateStr}</span>
- </div>
- </div>
- {/* Delete button - show on hover */}
- <button
- type="button"
- class="flex-shrink-0 p-1 rounded opacity-0 group-hover:opacity-100 hover:bg-red-100 dark:hover:bg-red-900/30 text-gray-400 hover:text-red-500 transition-opacity"
- onClick={(e) => {
- e.stopPropagation();
- if (confirm('Delete this conversation?')) {
- aiChatStore.deleteSession(session.id);
- }
- }}
- title="Delete conversation"
- >
- <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
- </svg>
- </button>
- </div>
- );
- }}
- </For>
- </Show>
- </div>
-
- {/* Sync status */}
- <div class="px-3 py-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
- <div class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
- <span class="flex items-center gap-1.5">
- <Show when={aiChatStore.syncing} fallback={
- <svg class="w-3 h-3 text-green-500" fill="currentColor" viewBox="0 0 20 20">
- <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
- </svg>
- }>
- <svg class="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24">
- <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
- <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
- </svg>
- </Show>
- {aiChatStore.syncing ? 'Syncing...' : 'Synced'}
- </span>
- <button
- type="button"
- onClick={() => setShowSessionPicker(false)}
- class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
- >
- Close
- </button>
- </div>
- </div>
- </div>
- </Show>
- </div>
+ </a>
+ {/* Collapse panel */}
<button
onClick={props.onClose}
class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800"
- title="Collapse panel"
+ title="Collapse panel (Esc)"
>
- {/* Double chevron right - collapse */}
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
stroke-linecap="round"
@@ -1157,530 +112,15 @@ export const AIChat: Component<AIChatProps> = (props) => {
</div>
</div>
- {/* Messages Area */}
- <div class="flex-1 overflow-y-auto p-4 space-y-4">
- {/* AI Patrol upgrade prompt - shows after first message for free users */}
- <Show when={showUpgradePrompt()}>
- <div class="mb-4 relative overflow-hidden group">
- <div class="absolute inset-0 bg-gradient-to-r from-purple-500/10 to-indigo-500/10 opacity-50 group-hover:opacity-100 transition-opacity"></div>
- <div class="relative flex items-start gap-4 p-4 bg-white dark:bg-gray-800/50 border border-purple-200 dark:border-purple-900/50 rounded-2xl shadow-lg backdrop-blur-sm">
- <div class="p-2.5 bg-gradient-to-br from-purple-500 to-indigo-600 rounded-xl shadow-md transform group-hover:scale-110 transition-transform duration-500">
- <Sparkles class="w-4 h-4 text-white" />
- </div>
- <div class="flex-1 min-w-0">
- <div class="flex items-center gap-2">
- <p class="text-sm font-bold text-gray-900 dark:text-white">Autopilot your Ops</p>
- <span class="px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wider bg-purple-100 dark:bg-purple-900/50 text-purple-600 dark:text-purple-400 rounded">Pro</span>
- </div>
- <p class="text-xs text-gray-600 dark:text-gray-400 mt-1 leading-relaxed">
- AI Patrol monitors your infrastructure 24/7 and surfaces issues before they become outages.
- </p>
- <a
- href={patrolStatus()?.upgrade_url || 'https://pulserelay.pro/'}
- target="_blank"
- rel="noopener noreferrer"
- class="inline-flex items-center gap-1.5 mt-2.5 text-xs font-bold text-purple-600 dark:text-purple-400 hover:text-purple-700 dark:hover:text-purple-300 transition-colors group/link"
- >
- Enable AI Patrol
- <ExternalLink class="w-3 h-3 transform group-hover/link:translate-x-0.5 group-hover/link:-translate-y-0.5 transition-transform" />
- </a>
- </div>
- <button
- type="button"
- onClick={() => setUpgradePromptDismissed(true)}
- class="flex-shrink-0 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-all"
- title="Dismiss"
- >
- <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
- </svg>
- </button>
- </div>
- </div>
- </Show>
-
- <Show when={messages().length === 0}>
- <div class="text-center py-12 text-gray-500 dark:text-gray-400">
- <svg
- class="w-12 h-12 mx-auto mb-4 text-purple-200 dark:text-purple-800"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="1.5"
- d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"
- />
- </svg>
- <Show when={getGuestName(contextData())} fallback={
- <>
- <p class="text-sm font-medium mb-2">Start a conversation</p>
- <p class="text-xs max-w-xs mx-auto">
- Ask about your infrastructure, diagnose issues, or get remediation suggestions.
- </p>
- </>
- }>
- <p class="text-sm font-medium mb-2">Ask about {getGuestName(contextData())}</p>
- <p class="text-xs max-w-xs mx-auto mb-4">
- AI has access to this guest's current metrics and state. Try asking:
- </p>
- <div class="text-xs space-y-2 text-left max-w-xs mx-auto">
- <button
- type="button"
- class="w-full text-left px-3 py-2 rounded-lg bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 hover:bg-purple-100 dark:hover:bg-purple-900/50 transition-colors"
- onClick={() => setInput('What is the current status of this guest?')}
- >
- "What is the current status of this guest?"
- </button>
- <button
- type="button"
- class="w-full text-left px-3 py-2 rounded-lg bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 hover:bg-purple-100 dark:hover:bg-purple-900/50 transition-colors"
- onClick={() => setInput('Are there any performance concerns?')}
- >
- "Are there any performance concerns?"
- </button>
- <button
- type="button"
- class="w-full text-left px-3 py-2 rounded-lg bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 hover:bg-purple-100 dark:hover:bg-purple-900/50 transition-colors"
- onClick={() => setInput('How can I optimize resource usage?')}
- >
- "How can I optimize resource usage?"
- </button>
- </div>
- </Show>
- </div>
- </Show>
-
- <For each={messages()}>
- {(message) => (
- <div
- class={`flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}
- >
- <div
- class={`max-w-[85%] rounded-lg px-4 py-2 overflow-hidden break-words ${message.role === 'user'
- ? 'bg-purple-600 text-white'
- : 'bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-gray-100'
- }`}
- >
- {/* Render all events in chronological order - thinking, tools, and content interleaved */}
- <Show when={message.role === 'assistant' && message.streamEvents && message.streamEvents.length > 0}>
- <div class="space-y-2">
- <For each={message.streamEvents}>
- {(evt) => (
- <Switch>
- <Match when={evt.type === 'tool' && evt.tool}>
- {/* Tool call */}
- <div class="rounded border border-gray-300 dark:border-gray-600 overflow-hidden">
- <div class={`px-2 py-1 text-xs font-medium flex items-center gap-2 ${evt.tool!.success
- ? 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-200'
- : 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-200'
- }`}>
- <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
- </svg>
- <code class="font-mono">{evt.tool!.input}</code>
- </div>
- <Show when={evt.tool!.output}>
- <pre class="px-2 py-1 text-xs font-mono bg-gray-50 dark:bg-gray-900 text-gray-700 dark:text-gray-300 overflow-x-auto max-h-32 overflow-y-auto whitespace-pre-wrap break-words">
- {evt.tool!.output.length > 500 ? evt.tool!.output.substring(0, 500) + '...' : evt.tool!.output}
- </pre>
- </Show>
- </div>
- </Match>
- <Match when={evt.type === 'thinking' && evt.thinking}>
- {/* Thinking chunk */}
- <div class="px-2 py-1.5 text-xs bg-blue-50 dark:bg-blue-900/20 text-gray-700 dark:text-gray-300 rounded border-l-2 border-blue-400 whitespace-pre-wrap">
- {sanitizeThinking(evt.thinking!.length > 500 ? evt.thinking!.substring(0, 500) + '...' : evt.thinking!)}
- </div>
- </Match>
- <Match when={evt.type === 'content' && evt.content}>
- {/* Content chunk - rendered as markdown */}
- {/* DOMPurify sanitizes LLM output in renderMarkdown before HTML rendering. */}
- <div
- class="text-sm prose prose-sm dark:prose-invert max-w-none prose-pre:bg-gray-800 prose-pre:text-gray-100 prose-code:text-purple-600 dark:prose-code:text-purple-400 prose-code:before:content-none prose-code:after:content-none"
- // eslint-disable-next-line solid/no-innerhtml -- HTML is sanitized via DOMPurify in renderMarkdown
- innerHTML={renderMarkdown(evt.content!)}
- />
- </Match>
- </Switch>
- )}
- </For>
- </div>
- </Show>
-
- {/* Show in-progress tool executions - at the bottom */}
- <Show when={message.role === 'assistant' && message.pendingTools && message.pendingTools.length > 0}>
- <div class="mb-3 space-y-2">
- <For each={message.pendingTools}>
- {(tool) => (
- <div class="rounded border border-purple-400 dark:border-purple-600 overflow-hidden">
- <div class="px-2 py-1 text-xs font-medium flex items-center gap-2 bg-purple-100 dark:bg-purple-900/30 text-purple-800 dark:text-purple-200">
- <svg class="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24">
- <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
- <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>
- <code class="font-mono">{tool.input}</code>
- <span class="text-[10px] text-purple-600 dark:text-purple-400">Running...</span>
- </div>
- </div>
- )}
- </For>
- </div>
- </Show>
-
- {/* Show AI's response text - only if no streamEvents (fallback for old messages or messages without streaming) */}
- <Show when={message.content && (!message.streamEvents || message.streamEvents.length === 0)}>
- <div
- class="text-sm prose prose-sm dark:prose-invert max-w-none prose-pre:bg-gray-800 prose-pre:text-gray-100 prose-code:text-purple-600 dark:prose-code:text-purple-400 prose-code:before:content-none prose-code:after:content-none"
- // eslint-disable-next-line solid/no-innerhtml -- HTML is sanitized via DOMPurify in renderMarkdown
- innerHTML={renderMarkdown(message.content)}
- />
- </Show>
-
- {/* Show commands awaiting approval */}
- <Show when={message.role === 'assistant' && message.pendingApprovals && message.pendingApprovals.length > 0}>
- <div class="mt-3 space-y-2">
- <For each={message.pendingApprovals}>
- {(approval) => (
- <div class="rounded border border-amber-400 dark:border-amber-600 overflow-hidden">
- <div class="px-2 py-1.5 text-xs font-medium flex items-center gap-2 bg-amber-100 dark:bg-amber-900/30 text-amber-800 dark:text-amber-200">
- <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="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
- </svg>
- <span>Approval Required</span>
- <Show when={approval.runOnHost}>
- <span class="px-1 py-0.5 bg-amber-200 dark:bg-amber-800 rounded text-[10px]">HOST</span>
- </Show>
- </div>
- <div class="px-2 py-2 bg-amber-50 dark:bg-amber-900/20">
- <code class="text-xs font-mono text-gray-800 dark:text-gray-200 block mb-2">{approval.command}</code>
- <div class="flex gap-2">
- <button
- type="button"
- class={`flex-1 px-2 py-1 text-xs font-medium rounded transition-colors ${approval.isExecuting
- ? 'bg-green-400 text-white cursor-wait'
- : 'bg-green-600 hover:bg-green-700 text-white'
- }`}
- onClick={() => executeApprovedCommand(message.id, approval)}
- disabled={approval.isExecuting}
- >
- {approval.isExecuting ? (
- <span class="flex items-center justify-center gap-1">
- <svg class="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24">
- <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
- <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>
- Running...
- </span>
- ) : 'Run'}
- </button>
- <button
- type="button"
- class="flex-1 px-2 py-1 text-xs font-medium bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 rounded transition-colors disabled:opacity-50"
- onClick={() => {
- // Remove from pending approvals
- setMessages((prev) =>
- prev.map((m) =>
- m.id === message.id
- ? { ...m, pendingApprovals: m.pendingApprovals?.filter((a) => a.toolId !== approval.toolId) }
- : m
- )
- );
- }}
- disabled={approval.isExecuting}
- >
- Skip
- </button>
- </div>
- </div>
- </div>
- )}
- </For>
- </div>
- </Show>
- {/* Minimal footer - no model/token info shown */}
- </div>
- </div>
- )}
- </For>
-
- <div ref={messagesEndRef} />
- </div>
-
- {/* Processing indicator - sticky above input */}
- <Show when={isLoading()}>
- <div class="px-4 py-2 bg-purple-50 dark:bg-purple-900/20 border-t border-purple-200 dark:border-purple-800 flex items-center gap-2 text-sm text-purple-700 dark:text-purple-300">
- <svg class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
- <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
- <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>
- <span>Analyzing...</span>
- </div>
- </Show>
-
- {/* Input Area */}
- <div class="border-t border-gray-200 dark:border-gray-700 p-4">
- {/* Context section - always show with Add button */}
- <div class="mb-3 px-3 py-2 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700">
- <div class="flex items-center justify-between mb-2">
- <div class="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400">
- <svg class="w-3.5 h-3.5 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
- </svg>
- <span class="font-medium">
- Context {aiChatStore.contextItems.length > 0 ? `(${aiChatStore.contextItems.length})` : ''}
- </span>
- </div>
- <div class="flex items-center gap-2">
- <Show when={aiChatStore.contextItems.length > 0}>
- <button
- type="button"
- onClick={() => aiChatStore.clearAllContext()}
- class="text-[10px] text-gray-400 hover:text-red-500 transition-colors"
- title="Clear all context"
- >
- Clear all
- </button>
- </Show>
- </div>
- </div>
-
- {/* Context items */}
- <div class="flex flex-wrap gap-1.5">
- <For each={aiChatStore.contextItems}>
- {(item) => (
- <span class="inline-flex items-center gap-1 px-2 py-1 text-[11px] rounded-md bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-200">
- <span class="text-[9px] uppercase text-purple-500 dark:text-purple-400">{item.type}</span>
- <span class="font-medium">{item.name}</span>
- <button
- type="button"
- onClick={() => aiChatStore.removeContextItem(item.id)}
- class="ml-0.5 p-0.5 rounded hover:bg-purple-200 dark:hover:bg-purple-800 transition-colors"
- title="Remove from context"
- >
- <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
- </svg>
- </button>
- </span>
- )}
- </For>
-
- {/* Add context button */}
- <div class="relative">
- <button
- type="button"
- onClick={() => setShowContextPicker(!showContextPicker())}
- class="inline-flex items-center gap-1 px-2 py-1 text-[11px] rounded-md border border-dashed border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:border-purple-400 hover:text-purple-600 dark:hover:border-purple-500 dark:hover:text-purple-400 transition-colors"
- >
- <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
- </svg>
- <span>Add</span>
- </button>
-
- {/* Context picker dropdown */}
- <Show when={showContextPicker()}>
- <div class="absolute bottom-full left-0 mb-1 w-72 max-h-80 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 overflow-hidden z-50">
- {/* Search input */}
- <div class="p-2 border-b border-gray-200 dark:border-gray-700">
- <input
- type="text"
- value={contextSearch()}
- onInput={(e) => setContextSearch(e.currentTarget.value)}
- placeholder="Search VMs, containers, hosts..."
- class="w-full px-2 py-1.5 text-xs rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 placeholder-gray-400 focus:outline-none focus:ring-1 focus:ring-purple-500"
- autofocus
- />
- </div>
-
- {/* Resource list */}
- <div class="max-h-56 overflow-y-auto">
- <Show when={filteredResources().length > 0} fallback={
- <div class="p-4 text-center text-xs text-gray-500 dark:text-gray-400">
- No resources found
- </div>
- }>
- <For each={filteredResources()}>
- {(resource) => {
- const isAlreadyAdded = () => aiChatStore.hasContextItem(resource.id);
- return (
- <button
- type="button"
- onClick={() => !isAlreadyAdded() && addResourceToContext(resource)}
- disabled={isAlreadyAdded()}
- class={`w-full px-3 py-2 text-left flex items-center gap-2 text-xs transition-colors ${isAlreadyAdded()
- ? 'bg-purple-50 dark:bg-purple-900/20 text-gray-400 dark:text-gray-500 cursor-default'
- : 'hover:bg-gray-50 dark:hover:bg-gray-700/50 text-gray-700 dark:text-gray-300'
- }`}
- >
- {/* Type icon */}
- <span class={`flex-shrink-0 w-5 h-5 rounded flex items-center justify-center text-[9px] font-bold uppercase ${resource.type === 'vm' ? 'bg-blue-100 text-blue-600 dark:bg-blue-900/40 dark:text-blue-400' :
- resource.type === 'container' ? 'bg-green-100 text-green-600 dark:bg-green-900/40 dark:text-green-400' :
- resource.type === 'node' ? 'bg-orange-100 text-orange-600 dark:bg-orange-900/40 dark:text-orange-400' :
- resource.type === 'host' ? 'bg-purple-100 text-purple-600 dark:bg-purple-900/40 dark:text-purple-400' :
- 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400'
- }`}>
- {resource.type === 'vm' ? 'VM' :
- resource.type === 'container' ? 'CT' :
- resource.type === 'node' ? 'N' :
- resource.type === 'host' ? 'H' : '?'}
- </span>
-
- {/* Name and details */}
- <div class="flex-1 min-w-0">
- <div class="font-medium truncate">{resource.name}</div>
- <Show when={resource.node}>
- <div class="text-[10px] text-gray-400">{resource.node}</div>
- </Show>
- </div>
-
- {/* Status indicator */}
- <span class={`flex-shrink-0 w-2 h-2 rounded-full ${resource.status === 'running' || resource.status === 'online' ? 'bg-green-500' :
- resource.status === 'stopped' || resource.status === 'offline' ? 'bg-gray-400' :
- 'bg-yellow-500'
- }`} />
-
- {/* Check if already added */}
- <Show when={isAlreadyAdded()}>
- <svg class="w-3.5 h-3.5 text-purple-500" fill="currentColor" viewBox="0 0 20 20">
- <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
- </svg>
- </Show>
- </button>
- );
- }}
- </For>
- </Show>
- </div>
-
- {/* Close button */}
- <div class="p-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
- <button
- type="button"
- onClick={() => { setShowContextPicker(false); setContextSearch(''); }}
- class="w-full px-2 py-1 text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
- >
- Close
- </button>
- </div>
- </div>
- </Show>
- </div>
- </div>
-
- {/* Empty state hint */}
- <Show when={aiChatStore.contextItems.length === 0}>
- <p class="mt-2 text-[10px] text-gray-400 dark:text-gray-500">
- Add VMs, containers, or hosts to provide context for your questions
- </p>
- </Show>
-
- {/* Guest Notes - show for first context item */}
- <Show when={aiChatStore.contextItems.length > 0}>
- <GuestNotes
- guestId={`${aiChatStore.contextItems[0].type}-${aiChatStore.contextItems[0].id}`}
- guestName={aiChatStore.contextItems[0].name}
- guestType={aiChatStore.contextItems[0].type}
- />
- </Show>
- </div>
- {/* Queued message indicator */}
- <Show when={queuedMessage()}>
- <div class="flex items-center gap-2 px-3 py-2 mb-2 text-xs rounded-lg bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-700 text-amber-700 dark:text-amber-300">
- <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
- </svg>
- <span class="flex-1 truncate">
- <span class="font-medium">Queued:</span> "{queuedMessage()!.substring(0, 50)}{queuedMessage()!.length > 50 ? '...' : ''}"
- </span>
- <button
- type="button"
- onClick={() => setQueuedMessage(null)}
- class="p-0.5 rounded hover:bg-amber-200 dark:hover:bg-amber-800 transition-colors"
- title="Cancel queued message"
- >
- <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="M6 18L18 6M6 6l12 12" />
- </svg>
- </button>
- </div>
- </Show>
- <form onSubmit={handleSubmit} class="flex gap-2">
- <textarea
- ref={inputRef}
- value={input()}
- onInput={(e) => setInput(e.currentTarget.value)}
- onKeyDown={handleKeyDown}
- placeholder={
- isLoading()
- ? queuedMessage()
- ? "Type another message to replace queued..."
- : "Type to queue your next message..."
- : aiChatStore.contextItems.length > 0
- ? `Ask about ${aiChatStore.contextItems.length} item${aiChatStore.contextItems.length > 1 ? 's' : ''} in context...`
- : "Ask about your infrastructure..."
- }
- rows={2}
- class={`flex-1 px-3 py-2 text-sm rounded-lg border bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:border-transparent resize-none transition-colors ${isLoading()
- ? 'border-amber-300 dark:border-amber-600 focus:ring-amber-500'
- : 'border-gray-300 dark:border-gray-600 focus:ring-purple-500'
- }`}
- />
- <Show
- when={isLoading()}
- fallback={
- <button
- type="submit"
- disabled={!input().trim()}
- class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors self-end"
- title="Send message"
- >
- <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
- />
- </svg>
- </button>
- }
- >
- <div class="flex flex-col gap-1 self-end">
- {/* Queue button when AI is working */}
- <button
- type="submit"
- disabled={!input().trim()}
- class="px-4 py-2 bg-amber-500 text-white rounded-lg hover:bg-amber-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
- title={queuedMessage() ? "Replace queued message" : "Queue message for when AI finishes"}
- >
- <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
- </svg>
- </button>
- {/* Stop button */}
- <button
- type="button"
- onClick={handleStop}
- class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
- title="Stop generating"
- >
- <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
- <rect x="6" y="6" width="12" height="12" rx="1" />
- </svg>
- </button>
- </div>
- </Show>
- </form>
- <p class="text-xs text-gray-400 dark:text-gray-500 mt-2">
- {isLoading()
- ? "Type and press Enter to queue your next message"
- : "Press Enter to send, Shift+Enter for new line"
- }
- </p>
+ {/* OpenCode iframe */}
+ <div class="flex-1 relative">
+ <iframe
+ ref={iframeRef}
+ src="/opencode/"
+ class="absolute inset-0 w-full h-full border-0"
+ title="AI Assistant"
+ allow="clipboard-read; clipboard-write"
+ />
</div>
</Show>
</div>
diff --git a/frontend-modern/src/components/AI/Chat/ApprovalCard.tsx b/frontend-modern/src/components/AI/Chat/ApprovalCard.tsx
new file mode 100644
index 0000000000..1410eb19ac
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/ApprovalCard.tsx
@@ -0,0 +1,90 @@
+import { Component, Show } from 'solid-js';
+import type { PendingApproval } from './types';
+
+interface ApprovalCardProps {
+ approval: PendingApproval;
+ onApprove: () => void;
+ onSkip: () => void;
+}
+
+export const ApprovalCard: Component<ApprovalCardProps> = (props) => {
+ return (
+ <div class="rounded-lg border border-amber-300 dark:border-amber-700 overflow-hidden shadow-md">
+ {/* Header */}
+ <div class="px-3 py-2 text-xs font-medium flex items-center gap-2 bg-gradient-to-r from-amber-50 to-orange-50 dark:from-amber-900/30 dark:to-orange-900/30 text-amber-800 dark:text-amber-200 border-b border-amber-200 dark:border-amber-800">
+ <div class="p-1 rounded bg-amber-100 dark:bg-amber-800/50">
+ <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="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
+ </svg>
+ </div>
+ <span class="font-semibold">Approval Required</span>
+ <Show when={props.approval.runOnHost}>
+ <span class="px-1.5 py-0.5 bg-amber-200 dark:bg-amber-800 rounded text-[10px] font-bold uppercase tracking-wider">
+ Host
+ </span>
+ </Show>
+ <Show when={props.approval.targetHost}>
+ <span class="text-[10px] text-amber-600 dark:text-amber-400">
+ → {props.approval.targetHost}
+ </span>
+ </Show>
+ </div>
+
+ {/* Command */}
+ <div class="px-3 py-3 bg-amber-50/50 dark:bg-amber-900/10">
+ <div class="mb-3 p-2 bg-white dark:bg-gray-800 rounded border border-amber-200 dark:border-amber-700/50">
+ <code class="text-xs font-mono text-gray-800 dark:text-gray-200 break-all">
+ {props.approval.command}
+ </code>
+ </div>
+
+ {/* Actions */}
+ <div class="flex gap-2">
+ <button
+ type="button"
+ onClick={props.onApprove}
+ disabled={props.approval.isExecuting}
+ class={`flex-1 px-3 py-2 text-xs font-semibold rounded-lg transition-all ${
+ props.approval.isExecuting
+ ? 'bg-green-400 text-white cursor-wait'
+ : 'bg-gradient-to-r from-green-500 to-emerald-500 hover:from-green-600 hover:to-emerald-600 text-white shadow-sm hover:shadow-md'
+ }`}
+ >
+ <Show
+ when={!props.approval.isExecuting}
+ fallback={
+ <span class="flex items-center justify-center gap-1.5">
+ <svg class="w-3.5 h-3.5 animate-spin" fill="none" viewBox="0 0 24 24">
+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
+ <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>
+ Running...
+ </span>
+ }
+ >
+ <span class="flex items-center justify-center gap-1.5">
+ <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="M5 13l4 4L19 7" />
+ </svg>
+ Run Command
+ </span>
+ </Show>
+ </button>
+ <button
+ type="button"
+ onClick={props.onSkip}
+ disabled={props.approval.isExecuting}
+ class="flex-1 px-3 py-2 text-xs font-semibold bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 rounded-lg transition-colors disabled:opacity-50"
+ >
+ <span class="flex items-center justify-center gap-1.5">
+ <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="M6 18L18 6M6 6l12 12" />
+ </svg>
+ Skip
+ </span>
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend-modern/src/components/AI/Chat/ChatHeader.tsx b/frontend-modern/src/components/AI/Chat/ChatHeader.tsx
new file mode 100644
index 0000000000..d10a3838c1
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/ChatHeader.tsx
@@ -0,0 +1,266 @@
+import { Component, Show, For, createSignal } from 'solid-js';
+import { aiChatStore } from '@/stores/aiChat';
+import {
+ PROVIDER_DISPLAY_NAMES,
+ groupModelsByProvider,
+} from '../aiChatUtils';
+import type { ModelInfo } from './types';
+
+interface ChatHeaderProps {
+ title: string;
+ subtitle?: string;
+ onClose: () => void;
+ // Model selection
+ models: ModelInfo[];
+ selectedModel: string;
+ onModelChange: (model: string) => void;
+ // Autonomous mode
+ autonomousMode: boolean;
+ onToggleAutonomous: () => void;
+ isTogglingAutonomous: boolean;
+}
+
+export const ChatHeader: Component<ChatHeaderProps> = (props) => {
+ const [showModelSelector, setShowModelSelector] = createSignal(false);
+ const [showSessionPicker, setShowSessionPicker] = createSignal(false);
+
+ return (
+ <div class="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-purple-50 to-violet-50 dark:from-purple-900/20 dark:to-violet-900/20">
+ {/* Left side - title */}
+ <div class="flex items-center gap-3">
+ <div class="p-2 bg-gradient-to-br from-purple-500 to-violet-500 rounded-xl shadow-lg">
+ <svg
+ class="w-5 h-5 text-white"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="1.8"
+ d="M9.75 3.104v5.714a2.25 2.25 0 01-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 014.5 0m0 0v5.714c0 .597.237 1.17.659 1.591L19.8 15.3M14.25 3.104c.251.023.501.05.75.082M19.8 15.3l-1.57.393A9.065 9.065 0 0112 15a9.065 9.065 0 00-6.23.693L5 14.5m14.8.8l1.402 1.402c1.232 1.232.65 3.318-1.067 3.611l-2.576.43a18.003 18.003 0 01-5.118 0l-2.576-.43c-1.717-.293-2.299-2.379-1.067-3.611L5 14.5"
+ />
+ </svg>
+ </div>
+ <div>
+ <h2 class="text-sm font-semibold text-gray-900 dark:text-gray-100">
+ {props.title}
+ </h2>
+ <Show when={props.subtitle}>
+ <p class="text-xs text-gray-500 dark:text-gray-400">{props.subtitle}</p>
+ </Show>
+ </div>
+ </div>
+
+ {/* Right side - controls */}
+ <div class="flex items-center gap-2">
+ {/* Model selector */}
+ <Show when={props.models.length > 0}>
+ <div class="relative">
+ <button
+ onClick={() => setShowModelSelector(!showModelSelector())}
+ class="flex items-center gap-1.5 px-2.5 py-1.5 text-xs text-gray-600 dark:text-gray-300 hover:text-gray-800 dark:hover:text-gray-100 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 bg-white dark:bg-gray-800 transition-colors"
+ >
+ <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-[80px] truncate font-medium">
+ {props.selectedModel || 'Default'}
+ </span>
+ <svg class="w-3 h-3 text-gray-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-64 max-h-80 overflow-y-auto bg-white dark:bg-gray-800 rounded-xl shadow-xl border border-gray-200 dark:border-gray-700 z-50 py-1">
+ <button
+ onClick={() => { props.onModelChange(''); setShowModelSelector(false); }}
+ class={`w-full px-3 py-2 text-left text-sm hover:bg-gray-50 dark:hover:bg-gray-700 ${!props.selectedModel ? 'bg-purple-50 dark:bg-purple-900/30' : ''}`}
+ >
+ <div class="font-medium text-gray-900 dark:text-gray-100">Default</div>
+ <div class="text-xs text-gray-500 dark:text-gray-400">Use configured default model</div>
+ </button>
+ <For each={Array.from(groupModelsByProvider(props.models).entries())}>
+ {([provider, models]) => (
+ <>
+ <div class="px-3 py-1.5 text-xs font-semibold text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-700/50 sticky top-0">
+ {PROVIDER_DISPLAY_NAMES[provider] || provider}
+ </div>
+ <For each={models}>
+ {(model) => (
+ <button
+ onClick={() => { props.onModelChange(model.id); setShowModelSelector(false); }}
+ class={`w-full px-3 py-2 text-left text-sm hover:bg-gray-50 dark:hover:bg-gray-700 ${props.selectedModel === model.id ? 'bg-purple-50 dark:bg-purple-900/30' : ''}`}
+ >
+ <div class="font-medium text-gray-900 dark:text-gray-100">
+ {model.name || model.id.split(':').pop()}
+ </div>
+ </button>
+ )}
+ </For>
+ </>
+ )}
+ </For>
+ </div>
+ </Show>
+ </div>
+ </Show>
+
+ {/* Autonomous mode toggle */}
+ <button
+ onClick={props.onToggleAutonomous}
+ disabled={props.isTogglingAutonomous}
+ class={`p-2 rounded-lg transition-all ${
+ props.autonomousMode
+ ? 'text-amber-600 dark:text-amber-400 bg-amber-100 dark:bg-amber-900/40 hover:bg-amber-200 dark:hover:bg-amber-900/60 shadow-sm'
+ : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800'
+ } ${props.isTogglingAutonomous ? 'opacity-50 cursor-wait' : ''}`}
+ title={props.autonomousMode ? 'Autonomous Mode: ON (commands run without approval)' : 'Autonomous Mode: OFF (commands need approval)'}
+ >
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
+ </svg>
+ </button>
+
+ {/* Session management */}
+ <div class="relative">
+ <button
+ onClick={() => {
+ setShowSessionPicker(!showSessionPicker());
+ if (!showSessionPicker()) {
+ aiChatStore.refreshSessions();
+ }
+ }}
+ class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
+ title="Chat sessions"
+ >
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
+ </svg>
+ </button>
+
+ <Show when={showSessionPicker()}>
+ <div class="absolute right-0 top-full mt-1 w-72 max-h-96 bg-white dark:bg-gray-800 rounded-xl shadow-xl border border-gray-200 dark:border-gray-700 z-50 overflow-hidden">
+ {/* New conversation */}
+ <button
+ onClick={() => {
+ aiChatStore.newConversation();
+ setShowSessionPicker(false);
+ }}
+ class="w-full px-3 py-2.5 text-left text-sm flex items-center gap-2 text-purple-600 dark:text-purple-400 hover:bg-purple-50 dark:hover:bg-purple-900/20 border-b border-gray-200 dark:border-gray-700"
+ >
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
+ </svg>
+ <span class="font-medium">New conversation</span>
+ </button>
+
+ {/* Session list */}
+ <div class="max-h-64 overflow-y-auto">
+ <Show when={aiChatStore.sessions.length > 0} fallback={
+ <div class="px-3 py-6 text-center text-xs text-gray-500 dark:text-gray-400">
+ No previous conversations
+ </div>
+ }>
+ <For each={aiChatStore.sessions}>
+ {(session) => {
+ const isCurrentSession = () => session.id === aiChatStore.sessionId;
+ const sessionDate = new Date(session.updated_at);
+ const isToday = sessionDate.toDateString() === new Date().toDateString();
+ const dateStr = isToday
+ ? sessionDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
+ : sessionDate.toLocaleDateString([], { month: 'short', day: 'numeric' });
+
+ return (
+ <div
+ class={`group relative px-3 py-2.5 flex items-start gap-2 hover:bg-gray-50 dark:hover:bg-gray-700/50 cursor-pointer ${isCurrentSession() ? 'bg-purple-50 dark:bg-purple-900/20' : ''}`}
+ onClick={() => {
+ if (!isCurrentSession()) {
+ aiChatStore.switchSession(session.id);
+ }
+ setShowSessionPicker(false);
+ }}
+ >
+ <div class="flex-1 min-w-0">
+ <div class="flex items-center gap-2">
+ <span class={`text-sm font-medium truncate ${isCurrentSession() ? 'text-purple-700 dark:text-purple-300' : 'text-gray-900 dark:text-gray-100'}`}>
+ {session.title || 'Untitled conversation'}
+ </span>
+ <Show when={isCurrentSession()}>
+ <span class="flex-shrink-0 w-1.5 h-1.5 rounded-full bg-purple-500" />
+ </Show>
+ </div>
+ <div class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
+ <span>{session.message_count} messages</span>
+ <span>·</span>
+ <span>{dateStr}</span>
+ </div>
+ </div>
+ {/* Delete button */}
+ <button
+ type="button"
+ class="flex-shrink-0 p-1 rounded opacity-0 group-hover:opacity-100 hover:bg-red-100 dark:hover:bg-red-900/30 text-gray-400 hover:text-red-500 transition-opacity"
+ onClick={(e) => {
+ e.stopPropagation();
+ if (confirm('Delete this conversation?')) {
+ aiChatStore.deleteSession(session.id);
+ }
+ }}
+ title="Delete conversation"
+ >
+ <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
+ </svg>
+ </button>
+ </div>
+ );
+ }}
+ </For>
+ </Show>
+ </div>
+
+ {/* Sync status */}
+ <div class="px-3 py-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
+ <div class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
+ <span class="flex items-center gap-1.5">
+ <Show when={aiChatStore.syncing} fallback={
+ <svg class="w-3 h-3 text-green-500" fill="currentColor" viewBox="0 0 20 20">
+ <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
+ </svg>
+ }>
+ <svg class="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24">
+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
+ <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
+ </svg>
+ </Show>
+ {aiChatStore.syncing ? 'Syncing...' : 'Synced'}
+ </span>
+ <button
+ type="button"
+ onClick={() => setShowSessionPicker(false)}
+ class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
+ >
+ Close
+ </button>
+ </div>
+ </div>
+ </div>
+ </Show>
+ </div>
+
+ {/* Close button */}
+ <button
+ onClick={props.onClose}
+ class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
+ title="Collapse panel"
+ >
+ <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 5l7 7-7 7M6 5l7 7-7 7" />
+ </svg>
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend-modern/src/components/AI/Chat/ChatInput.tsx b/frontend-modern/src/components/AI/Chat/ChatInput.tsx
new file mode 100644
index 0000000000..ce7b70af2a
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/ChatInput.tsx
@@ -0,0 +1,193 @@
+import { Component, Show, For } from 'solid-js';
+import type { ChatContextItem } from './types';
+
+interface ChatInputProps {
+ value: string;
+ onChange: (value: string) => void;
+ onSubmit: () => void;
+ onStop: () => void;
+ isLoading: boolean;
+ queuedMessage: string | null;
+ onClearQueue: () => void;
+ placeholder?: string;
+ contextItems: ChatContextItem[];
+ onAddContext: () => void;
+ onRemoveContext: (id: string) => void;
+ onClearAllContext: () => void;
+ disabled?: boolean;
+}
+
+export const ChatInput: Component<ChatInputProps> = (props) => {
+ let inputRef: HTMLTextAreaElement | undefined;
+
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ props.onSubmit();
+ }
+ };
+
+ const placeholder = () => {
+ if (props.isLoading) {
+ return props.queuedMessage
+ ? 'Type another message to replace queued...'
+ : 'Type to queue your next message...';
+ }
+ return props.placeholder || 'Ask about your infrastructure...';
+ };
+
+ return (
+ <div class="border-t border-gray-200 dark:border-gray-700 p-4 bg-white dark:bg-gray-900">
+ {/* Context section */}
+ <div class="mb-3 px-3 py-2.5 bg-gray-50 dark:bg-gray-800/50 rounded-xl border border-gray-200 dark:border-gray-700">
+ <div class="flex items-center justify-between mb-2">
+ <div class="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400">
+ <svg class="w-3.5 h-3.5 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
+ </svg>
+ <span class="font-medium">
+ Context {props.contextItems.length > 0 ? `(${props.contextItems.length})` : ''}
+ </span>
+ </div>
+ <Show when={props.contextItems.length > 0}>
+ <button
+ type="button"
+ onClick={props.onClearAllContext}
+ class="text-[10px] text-gray-400 hover:text-red-500 transition-colors"
+ >
+ Clear all
+ </button>
+ </Show>
+ </div>
+
+ {/* Context items */}
+ <div class="flex flex-wrap gap-1.5">
+ <For each={props.contextItems}>
+ {(item) => (
+ <span class="inline-flex items-center gap-1 px-2 py-1 text-[11px] rounded-lg bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-200">
+ <span class="text-[9px] uppercase text-purple-500 dark:text-purple-400 font-semibold">
+ {item.type}
+ </span>
+ <span class="font-medium">{item.name}</span>
+ <button
+ type="button"
+ onClick={() => props.onRemoveContext(item.id)}
+ class="ml-0.5 p-0.5 rounded hover:bg-purple-200 dark:hover:bg-purple-800 transition-colors"
+ >
+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
+ </svg>
+ </button>
+ </span>
+ )}
+ </For>
+
+ {/* Add context button */}
+ <button
+ type="button"
+ onClick={props.onAddContext}
+ class="inline-flex items-center gap-1 px-2 py-1 text-[11px] rounded-lg border border-dashed border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:border-purple-400 hover:text-purple-600 dark:hover:border-purple-500 dark:hover:text-purple-400 transition-colors"
+ >
+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
+ </svg>
+ <span>Add</span>
+ </button>
+ </div>
+
+ <Show when={props.contextItems.length === 0}>
+ <p class="mt-2 text-[10px] text-gray-400 dark:text-gray-500">
+ Add VMs, containers, or hosts to provide context for your questions
+ </p>
+ </Show>
+ </div>
+
+ {/* Queued message indicator */}
+ <Show when={props.queuedMessage}>
+ <div class="flex items-center gap-2 px-3 py-2 mb-2 text-xs rounded-lg bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-700 text-amber-700 dark:text-amber-300">
+ <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
+ </svg>
+ <span class="flex-1 truncate">
+ <span class="font-medium">Queued:</span> "{props.queuedMessage!.substring(0, 50)}
+ {props.queuedMessage!.length > 50 ? '...' : ''}"
+ </span>
+ <button
+ type="button"
+ onClick={props.onClearQueue}
+ class="p-0.5 rounded hover:bg-amber-200 dark:hover:bg-amber-800 transition-colors"
+ >
+ <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="M6 18L18 6M6 6l12 12" />
+ </svg>
+ </button>
+ </div>
+ </Show>
+
+ {/* Input form */}
+ <form onSubmit={(e) => { e.preventDefault(); props.onSubmit(); }} class="flex gap-2">
+ <textarea
+ ref={inputRef}
+ value={props.value}
+ onInput={(e) => props.onChange(e.currentTarget.value)}
+ onKeyDown={handleKeyDown}
+ placeholder={placeholder()}
+ rows={2}
+ disabled={props.disabled}
+ class={`flex-1 px-4 py-3 text-sm rounded-xl border bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:border-transparent resize-none transition-all ${
+ props.isLoading
+ ? 'border-amber-300 dark:border-amber-600 focus:ring-amber-500'
+ : 'border-gray-200 dark:border-gray-700 focus:ring-purple-500'
+ } ${props.disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
+ />
+
+ <div class="flex flex-col gap-1.5 self-end">
+ <Show
+ when={props.isLoading}
+ fallback={
+ <button
+ type="submit"
+ disabled={!props.value.trim() || props.disabled}
+ class="px-4 py-3 bg-gradient-to-r from-purple-600 to-violet-600 hover:from-purple-700 hover:to-violet-700 text-white rounded-xl disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-lg hover:shadow-xl disabled:shadow-none"
+ >
+ <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
+ </svg>
+ </button>
+ }
+ >
+ {/* Queue button when loading */}
+ <button
+ type="submit"
+ disabled={!props.value.trim()}
+ class="px-4 py-2.5 bg-amber-500 hover:bg-amber-600 text-white rounded-xl disabled:opacity-50 disabled:cursor-not-allowed transition-colors shadow-sm"
+ title={props.queuedMessage ? 'Replace queued message' : 'Queue message'}
+ >
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
+ </svg>
+ </button>
+ {/* Stop button */}
+ <button
+ type="button"
+ onClick={props.onStop}
+ class="px-4 py-2.5 bg-red-500 hover:bg-red-600 text-white rounded-xl transition-colors shadow-sm"
+ title="Stop generating"
+ >
+ <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
+ <rect x="6" y="6" width="12" height="12" rx="1" />
+ </svg>
+ </button>
+ </Show>
+ </div>
+ </form>
+
+ {/* Help text */}
+ <p class="text-xs text-gray-400 dark:text-gray-500 mt-2 text-center">
+ {props.isLoading
+ ? 'Type and press Enter to queue your next message'
+ : 'Press Enter to send, Shift+Enter for new line'}
+ </p>
+ </div>
+ );
+};
diff --git a/frontend-modern/src/components/AI/Chat/ChatMessages.tsx b/frontend-modern/src/components/AI/Chat/ChatMessages.tsx
new file mode 100644
index 0000000000..38130d252e
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/ChatMessages.tsx
@@ -0,0 +1,90 @@
+import { Component, Show, For, createEffect } from 'solid-js';
+import { MessageItem } from './MessageItem';
+import type { ChatMessage, PendingApproval } from './types';
+
+interface ChatMessagesProps {
+ messages: ChatMessage[];
+ onApprove: (messageId: string, approval: PendingApproval) => void;
+ onSkip: (messageId: string, toolId: string) => void;
+ emptyState?: {
+ title: string;
+ subtitle: string;
+ suggestions?: string[];
+ onSuggestionClick?: (suggestion: string) => void;
+ };
+}
+
+export const ChatMessages: Component<ChatMessagesProps> = (props) => {
+ let messagesEndRef: HTMLDivElement | undefined;
+
+ // Auto-scroll to bottom
+ createEffect(() => {
+ if (props.messages.length > 0 && messagesEndRef) {
+ messagesEndRef.scrollIntoView({ behavior: 'smooth' });
+ }
+ });
+
+ return (
+ <div class="flex-1 overflow-y-auto p-4 space-y-4">
+ {/* Empty state */}
+ <Show when={props.messages.length === 0 && props.emptyState}>
+ <div class="flex flex-col items-center justify-center h-full text-center py-12">
+ {/* AI Icon */}
+ <div class="w-16 h-16 mb-4 rounded-2xl bg-gradient-to-br from-purple-100 to-violet-100 dark:from-purple-900/30 dark:to-violet-900/30 flex items-center justify-center">
+ <svg
+ class="w-8 h-8 text-purple-500 dark:text-purple-400"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="1.5"
+ d="M9.75 3.104v5.714a2.25 2.25 0 01-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 014.5 0m0 0v5.714c0 .597.237 1.17.659 1.591L19.8 15.3M14.25 3.104c.251.023.501.05.75.082M19.8 15.3l-1.57.393A9.065 9.065 0 0112 15a9.065 9.065 0 00-6.23.693L5 14.5m14.8.8l1.402 1.402c1.232 1.232.65 3.318-1.067 3.611l-2.576.43a18.003 18.003 0 01-5.118 0l-2.576-.43c-1.717-.293-2.299-2.379-1.067-3.611L5 14.5"
+ />
+ </svg>
+ </div>
+
+ <h3 class="text-base font-semibold text-gray-900 dark:text-gray-100 mb-1">
+ {props.emptyState!.title}
+ </h3>
+ <p class="text-sm text-gray-500 dark:text-gray-400 max-w-xs mb-6">
+ {props.emptyState!.subtitle}
+ </p>
+
+ {/* Suggestions */}
+ <Show when={props.emptyState!.suggestions && props.emptyState!.suggestions!.length > 0}>
+ <div class="space-y-2 w-full max-w-xs">
+ <For each={props.emptyState!.suggestions}>
+ {(suggestion) => (
+ <button
+ type="button"
+ onClick={() => props.emptyState!.onSuggestionClick?.(suggestion)}
+ class="w-full text-left px-4 py-2.5 rounded-xl bg-purple-50 dark:bg-purple-900/20 text-purple-700 dark:text-purple-300 text-sm hover:bg-purple-100 dark:hover:bg-purple-900/40 transition-colors border border-purple-100 dark:border-purple-800"
+ >
+ "{suggestion}"
+ </button>
+ )}
+ </For>
+ </div>
+ </Show>
+ </div>
+ </Show>
+
+ {/* Messages */}
+ <For each={props.messages}>
+ {(message) => (
+ <MessageItem
+ message={message}
+ onApprove={(approval) => props.onApprove(message.id, approval)}
+ onSkip={(toolId) => props.onSkip(message.id, toolId)}
+ />
+ )}
+ </For>
+
+ {/* Scroll anchor */}
+ <div ref={messagesEndRef} />
+ </div>
+ );
+};
diff --git a/frontend-modern/src/components/AI/Chat/ContextPicker.tsx b/frontend-modern/src/components/AI/Chat/ContextPicker.tsx
new file mode 100644
index 0000000000..e637b95612
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/ContextPicker.tsx
@@ -0,0 +1,160 @@
+import { Component, Show, For, createSignal, createMemo } from 'solid-js';
+import type { ChatContextItem } from './types';
+
+interface ContextPickerProps {
+ isOpen: boolean;
+ onClose: () => void;
+ resources: ChatContextItem[];
+ selectedIds: string[];
+ onSelect: (resource: ChatContextItem) => void;
+}
+
+export const ContextPicker: Component<ContextPickerProps> = (props) => {
+ const [search, setSearch] = createSignal('');
+
+ const filteredResources = createMemo(() => {
+ const term = search().toLowerCase();
+ if (!term) return props.resources;
+ return props.resources.filter(
+ (r) =>
+ r.name.toLowerCase().includes(term) ||
+ r.type.toLowerCase().includes(term) ||
+ (r.node && r.node.toLowerCase().includes(term))
+ );
+ });
+
+ const isSelected = (id: string) => props.selectedIds.includes(id);
+
+ const getTypeIcon = (type: string) => {
+ switch (type) {
+ case 'vm':
+ return { bg: 'bg-blue-100 dark:bg-blue-900/40', text: 'text-blue-600 dark:text-blue-400', label: 'VM' };
+ case 'container':
+ return { bg: 'bg-green-100 dark:bg-green-900/40', text: 'text-green-600 dark:text-green-400', label: 'CT' };
+ case 'node':
+ return { bg: 'bg-orange-100 dark:bg-orange-900/40', text: 'text-orange-600 dark:text-orange-400', label: 'N' };
+ case 'host':
+ return { bg: 'bg-purple-100 dark:bg-purple-900/40', text: 'text-purple-600 dark:text-purple-400', label: 'H' };
+ default:
+ return { bg: 'bg-gray-100 dark:bg-gray-700', text: 'text-gray-600 dark:text-gray-400', label: '?' };
+ }
+ };
+
+ const getStatusColor = (status: string) => {
+ switch (status) {
+ case 'running':
+ case 'online':
+ return 'bg-green-500';
+ case 'stopped':
+ case 'offline':
+ return 'bg-gray-400';
+ default:
+ return 'bg-yellow-500';
+ }
+ };
+
+ return (
+ <Show when={props.isOpen}>
+ <div class="absolute bottom-full left-0 mb-1 w-72 max-h-80 bg-white dark:bg-gray-800 rounded-xl shadow-xl border border-gray-200 dark:border-gray-700 overflow-hidden z-50">
+ {/* Search input */}
+ <div class="p-2 border-b border-gray-200 dark:border-gray-700">
+ <div class="relative">
+ <svg
+ class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
+ </svg>
+ <input
+ type="text"
+ value={search()}
+ onInput={(e) => setSearch(e.currentTarget.value)}
+ placeholder="Search VMs, containers, hosts..."
+ class="w-full pl-9 pr-3 py-2 text-sm rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
+ autofocus
+ />
+ </div>
+ </div>
+
+ {/* Resource list */}
+ <div class="max-h-56 overflow-y-auto">
+ <Show
+ when={filteredResources().length > 0}
+ fallback={
+ <div class="p-6 text-center text-xs text-gray-500 dark:text-gray-400">
+ No resources found
+ </div>
+ }
+ >
+ <For each={filteredResources()}>
+ {(resource) => {
+ const typeInfo = getTypeIcon(resource.type);
+ const selected = isSelected(resource.id);
+
+ return (
+ <button
+ type="button"
+ onClick={() => !selected && props.onSelect(resource)}
+ disabled={selected}
+ class={`w-full px-3 py-2.5 text-left flex items-center gap-2.5 text-xs transition-colors ${
+ selected
+ ? 'bg-purple-50 dark:bg-purple-900/20 text-gray-400 dark:text-gray-500 cursor-default'
+ : 'hover:bg-gray-50 dark:hover:bg-gray-700/50 text-gray-700 dark:text-gray-300'
+ }`}
+ >
+ {/* Type icon */}
+ <span
+ class={`flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center text-[9px] font-bold uppercase ${typeInfo.bg} ${typeInfo.text}`}
+ >
+ {typeInfo.label}
+ </span>
+
+ {/* Name and details */}
+ <div class="flex-1 min-w-0">
+ <div class="font-medium truncate">{resource.name}</div>
+ <Show when={resource.node}>
+ <div class="text-[10px] text-gray-400">{resource.node}</div>
+ </Show>
+ </div>
+
+ {/* Status indicator */}
+ <span
+ class={`flex-shrink-0 w-2 h-2 rounded-full ${getStatusColor(resource.status)}`}
+ />
+
+ {/* Selected checkmark */}
+ <Show when={selected}>
+ <svg class="w-4 h-4 text-purple-500" fill="currentColor" viewBox="0 0 20 20">
+ <path
+ fill-rule="evenodd"
+ d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
+ clip-rule="evenodd"
+ />
+ </svg>
+ </Show>
+ </button>
+ );
+ }}
+ </For>
+ </Show>
+ </div>
+
+ {/* Close button */}
+ <div class="p-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
+ <button
+ type="button"
+ onClick={() => {
+ props.onClose();
+ setSearch('');
+ }}
+ class="w-full px-2 py-1.5 text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors"
+ >
+ Close
+ </button>
+ </div>
+ </div>
+ </Show>
+ );
+};
diff --git a/frontend-modern/src/components/AI/Chat/MessageItem.tsx b/frontend-modern/src/components/AI/Chat/MessageItem.tsx
new file mode 100644
index 0000000000..c14502dc50
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/MessageItem.tsx
@@ -0,0 +1,119 @@
+import { Component, Show, For, Switch, Match } from 'solid-js';
+import { renderMarkdown } from '../aiChatUtils';
+import { ThinkingBlock } from './ThinkingBlock';
+import { ToolExecutionBlock, PendingToolBlock } from './ToolExecutionBlock';
+import { ApprovalCard } from './ApprovalCard';
+import type { ChatMessage, PendingApproval } from './types';
+
+interface MessageItemProps {
+ message: ChatMessage;
+ onApprove: (approval: PendingApproval) => void;
+ onSkip: (toolId: string) => void;
+}
+
+export const MessageItem: Component<MessageItemProps> = (props) => {
+ const isUser = () => props.message.role === 'user';
+ const hasStreamEvents = () =>
+ props.message.streamEvents && props.message.streamEvents.length > 0;
+
+ return (
+ <div class={`flex ${isUser() ? 'justify-end' : 'justify-start'}`}>
+ <div
+ class={`max-w-[90%] rounded-2xl overflow-hidden transition-all ${
+ isUser()
+ ? 'bg-gradient-to-br from-purple-600 to-violet-600 text-white shadow-lg'
+ : 'bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 shadow-md border border-gray-100 dark:border-gray-700'
+ }`}
+ >
+ <div class="px-4 py-3">
+ {/* User messages */}
+ <Show when={isUser()}>
+ <p class="text-sm whitespace-pre-wrap">{props.message.content}</p>
+ </Show>
+
+ {/* Assistant messages with stream events */}
+ <Show when={!isUser()}>
+ {/* Stream events (chronological order) */}
+ <Show when={hasStreamEvents()}>
+ <div class="space-y-3">
+ <For each={props.message.streamEvents}>
+ {(evt) => (
+ <Switch>
+ <Match when={evt.type === 'thinking' && evt.thinking}>
+ <ThinkingBlock content={evt.thinking!} />
+ </Match>
+ <Match when={evt.type === 'tool' && evt.tool}>
+ <ToolExecutionBlock tool={evt.tool!} />
+ </Match>
+ <Match when={evt.type === 'content' && evt.content}>
+ <div
+ class="text-sm prose prose-sm dark:prose-invert max-w-none prose-pre:bg-gray-800 prose-pre:text-gray-100 prose-code:text-purple-600 dark:prose-code:text-purple-400 prose-code:before:content-none prose-code:after:content-none"
+ innerHTML={renderMarkdown(evt.content!)}
+ />
+ </Match>
+ </Switch>
+ )}
+ </For>
+ </div>
+ </Show>
+
+ {/* Pending tools (running) */}
+ <Show when={props.message.pendingTools && props.message.pendingTools.length > 0}>
+ <div class="mt-3 space-y-2">
+ <For each={props.message.pendingTools}>
+ {(tool) => <PendingToolBlock tool={tool} />}
+ </For>
+ </div>
+ </Show>
+
+ {/* Fallback: show content if no stream events */}
+ <Show when={props.message.content && !hasStreamEvents()}>
+ <div
+ class="text-sm prose prose-sm dark:prose-invert max-w-none prose-pre:bg-gray-800 prose-pre:text-gray-100 prose-code:text-purple-600 dark:prose-code:text-purple-400 prose-code:before:content-none prose-code:after:content-none"
+ innerHTML={renderMarkdown(props.message.content)}
+ />
+ </Show>
+
+ {/* Pending approvals */}
+ <Show when={props.message.pendingApprovals && props.message.pendingApprovals.length > 0}>
+ <div class="mt-4 space-y-3">
+ <For each={props.message.pendingApprovals}>
+ {(approval) => (
+ <ApprovalCard
+ approval={approval}
+ onApprove={() => props.onApprove(approval)}
+ onSkip={() => props.onSkip(approval.toolId)}
+ />
+ )}
+ </For>
+ </div>
+ </Show>
+
+ {/* Streaming indicator */}
+ <Show when={props.message.isStreaming && !props.message.pendingTools?.length}>
+ <div class="mt-2 flex items-center gap-2 text-purple-500 dark:text-purple-400">
+ <div class="flex gap-1">
+ <span class="w-1.5 h-1.5 bg-current rounded-full animate-bounce" style="animation-delay: 0ms" />
+ <span class="w-1.5 h-1.5 bg-current rounded-full animate-bounce" style="animation-delay: 150ms" />
+ <span class="w-1.5 h-1.5 bg-current rounded-full animate-bounce" style="animation-delay: 300ms" />
+ </div>
+ </div>
+ </Show>
+ </Show>
+ </div>
+
+ {/* Message metadata footer */}
+ <Show when={!isUser() && props.message.model && !props.message.isStreaming}>
+ <div class="px-4 py-1.5 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-100 dark:border-gray-700 flex items-center justify-between text-[10px] text-gray-400 dark:text-gray-500">
+ <span>{props.message.model}</span>
+ <Show when={props.message.tokens}>
+ <span>
+ {props.message.tokens!.input + props.message.tokens!.output} tokens
+ </span>
+ </Show>
+ </div>
+ </Show>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend-modern/src/components/AI/Chat/ThinkingBlock.tsx b/frontend-modern/src/components/AI/Chat/ThinkingBlock.tsx
new file mode 100644
index 0000000000..8c89748140
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/ThinkingBlock.tsx
@@ -0,0 +1,29 @@
+import { Component } from 'solid-js';
+import { sanitizeThinking } from '../aiChatUtils';
+
+interface ThinkingBlockProps {
+ content: string;
+ maxLength?: number;
+}
+
+export const ThinkingBlock: Component<ThinkingBlockProps> = (props) => {
+ const truncated = () => {
+ const max = props.maxLength ?? 500;
+ const text = props.content;
+ return text.length > max ? text.substring(0, max) + '...' : text;
+ };
+
+ return (
+ <div class="px-3 py-2 text-xs bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 text-gray-700 dark:text-gray-300 rounded-lg border-l-3 border-blue-400 dark:border-blue-500 whitespace-pre-wrap">
+ <div class="flex items-center gap-1.5 mb-1.5 text-blue-600 dark:text-blue-400 font-medium">
+ <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.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
+ </svg>
+ <span class="text-[10px] uppercase tracking-wider">Thinking</span>
+ </div>
+ <div class="text-gray-600 dark:text-gray-400 leading-relaxed">
+ {sanitizeThinking(truncated())}
+ </div>
+ </div>
+ );
+};
diff --git a/frontend-modern/src/components/AI/Chat/ToolExecutionBlock.tsx b/frontend-modern/src/components/AI/Chat/ToolExecutionBlock.tsx
new file mode 100644
index 0000000000..052055b8c9
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/ToolExecutionBlock.tsx
@@ -0,0 +1,92 @@
+import { Component, Show, createSignal } from 'solid-js';
+import type { ToolExecution, PendingTool } from './types';
+
+interface ToolExecutionBlockProps {
+ tool: ToolExecution;
+ maxOutputLength?: number;
+}
+
+export const ToolExecutionBlock: Component<ToolExecutionBlockProps> = (props) => {
+ const [expanded, setExpanded] = createSignal(false);
+
+ const truncatedOutput = () => {
+ const max = props.maxOutputLength ?? 500;
+ const output = props.tool.output;
+ if (!output) return '';
+ return output.length > max && !expanded() ? output.substring(0, max) + '...' : output;
+ };
+
+ const needsTruncation = () => {
+ const max = props.maxOutputLength ?? 500;
+ return props.tool.output && props.tool.output.length > max;
+ };
+
+ return (
+ <div class="rounded-lg border overflow-hidden shadow-sm transition-all hover:shadow-md">
+ {/* Header */}
+ <div
+ class={`px-3 py-2 text-xs font-medium flex items-center gap-2 ${
+ props.tool.success
+ ? 'bg-gradient-to-r from-green-50 to-emerald-50 dark:from-green-900/30 dark:to-emerald-900/30 text-green-800 dark:text-green-200 border-b border-green-200 dark:border-green-800'
+ : 'bg-gradient-to-r from-red-50 to-rose-50 dark:from-red-900/30 dark:to-rose-900/30 text-red-800 dark:text-red-200 border-b border-red-200 dark:border-red-800'
+ }`}
+ >
+ <div class={`p-1 rounded ${props.tool.success ? 'bg-green-100 dark:bg-green-800/50' : 'bg-red-100 dark:bg-red-800/50'}`}>
+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
+ </svg>
+ </div>
+ <code class="font-mono flex-1 truncate">{props.tool.input}</code>
+ <Show when={props.tool.success}>
+ <svg class="w-4 h-4 text-green-500" fill="currentColor" viewBox="0 0 20 20">
+ <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
+ </svg>
+ </Show>
+ <Show when={!props.tool.success}>
+ <svg class="w-4 h-4 text-red-500" fill="currentColor" viewBox="0 0 20 20">
+ <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
+ </svg>
+ </Show>
+ </div>
+
+ {/* Output */}
+ <Show when={props.tool.output}>
+ <div class="relative">
+ <pre class="px-3 py-2 text-xs font-mono bg-gray-50 dark:bg-gray-900/80 text-gray-700 dark:text-gray-300 overflow-x-auto max-h-48 overflow-y-auto whitespace-pre-wrap break-words">
+ {truncatedOutput()}
+ </pre>
+ <Show when={needsTruncation()}>
+ <button
+ onClick={() => setExpanded(!expanded())}
+ class="absolute bottom-2 right-2 px-2 py-1 text-[10px] font-medium bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-600 dark:text-gray-300 rounded transition-colors"
+ >
+ {expanded() ? 'Show less' : 'Show more'}
+ </button>
+ </Show>
+ </div>
+ </Show>
+ </div>
+ );
+};
+
+// Pending tool (still running)
+interface PendingToolBlockProps {
+ tool: PendingTool;
+}
+
+export const PendingToolBlock: Component<PendingToolBlockProps> = (props) => {
+ return (
+ <div class="rounded-lg border border-purple-300 dark:border-purple-700 overflow-hidden animate-pulse">
+ <div class="px-3 py-2 text-xs font-medium flex items-center gap-2 bg-gradient-to-r from-purple-50 to-violet-50 dark:from-purple-900/30 dark:to-violet-900/30 text-purple-800 dark:text-purple-200">
+ <div class="p-1 rounded bg-purple-100 dark:bg-purple-800/50">
+ <svg class="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24">
+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
+ <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>
+ </div>
+ <code class="font-mono flex-1 truncate">{props.tool.input}</code>
+ <span class="text-[10px] text-purple-600 dark:text-purple-400 font-semibold uppercase tracking-wider">Running</span>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend-modern/src/components/AI/Chat/hooks/index.ts b/frontend-modern/src/components/AI/Chat/hooks/index.ts
new file mode 100644
index 0000000000..7cf02b47df
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/hooks/index.ts
@@ -0,0 +1,2 @@
+export { useChat } from './useChat';
+export type { UseChatOptions } from './useChat';
diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
new file mode 100644
index 0000000000..1339a92691
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
@@ -0,0 +1,268 @@
+import { createSignal, onCleanup } from 'solid-js';
+import { OpenCodeAPI, type StreamEvent } from '@/api/opencode';
+import { notificationStore } from '@/stores/notifications';
+import { logger } from '@/utils/logger';
+import type {
+ ChatMessage,
+ ToolExecution,
+ StreamDisplayEvent,
+} from '../types';
+
+const generateId = () => Math.random().toString(36).substring(2, 9);
+
+export interface UseChatOptions {
+ sessionId?: string;
+ model?: string;
+}
+
+export function useChat(options: UseChatOptions = {}) {
+ // Core state
+ const [messages, setMessages] = createSignal<ChatMessage[]>([]);
+ const [isLoading, setIsLoading] = createSignal(false);
+ const [sessionId, setSessionId] = createSignal(options.sessionId || '');
+ const [model, setModel] = createSignal(options.model || '');
+
+ // Abort controller for canceling requests
+ let abortControllerRef: AbortController | null = null;
+
+ // Cleanup on unmount
+ onCleanup(() => {
+ if (abortControllerRef) abortControllerRef.abort();
+ });
+
+ // Stop/cancel current request
+ const stop = () => {
+ if (abortControllerRef) {
+ abortControllerRef.abort();
+ abortControllerRef = null;
+ }
+ setMessages((prev) =>
+ prev.map((msg) =>
+ msg.isStreaming
+ ? { ...msg, isStreaming: false, content: msg.content || '(Stopped)' }
+ : msg
+ )
+ );
+ setIsLoading(false);
+ };
+
+ // Helper to add stream event for chronological display
+ const addStreamEvent = (msg: ChatMessage, event: StreamDisplayEvent): ChatMessage => {
+ const events = msg.streamEvents || [];
+ // For content events, merge consecutive content into one
+ if (event.type === 'content' && events.length > 0) {
+ const last = events[events.length - 1];
+ if (last.type === 'content') {
+ return {
+ ...msg,
+ streamEvents: [
+ ...events.slice(0, -1),
+ { ...last, content: (last.content || '') + (event.content || '') },
+ ],
+ };
+ }
+ }
+ return {
+ ...msg,
+ streamEvents: [...events, event],
+ };
+ };
+
+ // Process stream events
+ const processEvent = (
+ assistantId: string,
+ event: StreamEvent
+ ) => {
+ setMessages((prev) =>
+ prev.map((msg) => {
+ if (msg.id !== assistantId) return msg;
+
+ switch (event.type) {
+ case 'content': {
+ const content = event.data as string;
+ if (!content) return msg;
+ const existing = msg.content || '';
+ // Add to streamEvents for chronological display
+ const updated = addStreamEvent(msg, { type: 'content', content });
+ return {
+ ...updated,
+ content: existing + content,
+ };
+ }
+
+ case 'thinking': {
+ const thinking = event.data as string;
+ if (!thinking) return msg;
+ // Add thinking to streamEvents
+ const updated = addStreamEvent(msg, { type: 'thinking', thinking });
+ return {
+ ...updated,
+ thinking: (msg.thinking || '') + thinking,
+ };
+ }
+
+ case 'tool_start': {
+ const data = event.data as { name: string; input: string };
+ return {
+ ...msg,
+ pendingTools: [...(msg.pendingTools || []), { name: data.name, input: data.input }],
+ };
+ }
+
+ case 'tool_end': {
+ const data = event.data as { name: string; input: string; output: string; success: boolean };
+ const pendingTools = msg.pendingTools || [];
+ const matchingIndex = pendingTools.findIndex((t) => t.name === data.name);
+ const updatedPending = matchingIndex >= 0
+ ? [...pendingTools.slice(0, matchingIndex), ...pendingTools.slice(matchingIndex + 1)]
+ : pendingTools;
+
+ const newToolCall: ToolExecution = {
+ name: data.name,
+ input: data.input,
+ output: data.output,
+ success: data.success,
+ };
+
+ // Add tool to streamEvents for chronological display
+ const updated = addStreamEvent(msg, { type: 'tool', tool: newToolCall });
+ return {
+ ...updated,
+ pendingTools: updatedPending,
+ toolCalls: [...(msg.toolCalls || []), newToolCall],
+ };
+ }
+
+ case 'done': {
+ return { ...msg, isStreaming: false, pendingTools: [] };
+ }
+
+ case 'error': {
+ const errorMsg = event.data as string;
+ return {
+ ...msg,
+ isStreaming: false,
+ pendingTools: [],
+ content: `Error: ${errorMsg}`,
+ };
+ }
+
+ default:
+ return msg;
+ }
+ })
+ );
+ };
+
+ // Send a message
+ const sendMessage = async (prompt: string) => {
+ if (!prompt.trim() || isLoading()) return;
+
+ // Add user message
+ const userMessage: ChatMessage = {
+ id: generateId(),
+ role: 'user',
+ content: prompt,
+ timestamp: new Date(),
+ };
+ setMessages((prev) => [...prev, userMessage]);
+ setIsLoading(true);
+
+ abortControllerRef = new AbortController();
+
+ // Create streaming assistant message
+ const assistantId = generateId();
+ const streamingMessage: ChatMessage = {
+ id: assistantId,
+ role: 'assistant',
+ content: '',
+ timestamp: new Date(),
+ isStreaming: true,
+ pendingTools: [],
+ toolCalls: [],
+ streamEvents: [],
+ };
+ setMessages((prev) => [...prev, streamingMessage]);
+
+ try {
+ await OpenCodeAPI.chat(
+ prompt,
+ sessionId() || undefined,
+ model() || undefined,
+ (event: StreamEvent) => {
+ processEvent(assistantId, event);
+ },
+ abortControllerRef?.signal
+ );
+ } catch (error) {
+ if (error instanceof Error && error.name === 'AbortError') {
+ logger.debug('[useChat] Request aborted');
+ return;
+ }
+ logger.error('[useChat] Chat failed:', error);
+ const errorMessage = error instanceof Error ? error.message : 'Failed to get AI response';
+ notificationStore.error(errorMessage);
+
+ setMessages((prev) =>
+ prev.map((msg) =>
+ msg.id === assistantId
+ ? { ...msg, isStreaming: false, content: `Error: ${errorMessage}` }
+ : msg
+ )
+ );
+ } finally {
+ abortControllerRef = null;
+ setIsLoading(false);
+ }
+ };
+
+ // Clear messages
+ const clearMessages = () => {
+ setMessages([]);
+ };
+
+ // Load session messages
+ const loadSession = async (id: string) => {
+ try {
+ const msgs = await OpenCodeAPI.getMessages(id);
+ setMessages(msgs.map(m => ({
+ id: m.id,
+ role: m.role,
+ content: m.content,
+ timestamp: new Date(m.timestamp),
+ toolCalls: m.tool_calls,
+ })));
+ setSessionId(id);
+ } catch (error) {
+ logger.error('[useChat] Failed to load session:', error);
+ notificationStore.error('Failed to load session');
+ }
+ };
+
+ // Create new session
+ const newSession = async () => {
+ try {
+ const session = await OpenCodeAPI.createSession();
+ setSessionId(session.id);
+ setMessages([]);
+ return session;
+ } catch (error) {
+ logger.error('[useChat] Failed to create session:', error);
+ notificationStore.error('Failed to create session');
+ return null;
+ }
+ };
+
+ return {
+ messages,
+ isLoading,
+ sessionId,
+ model,
+ setModel,
+ sendMessage,
+ stop,
+ clearMessages,
+ loadSession,
+ newSession,
+ };
+}
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
new file mode 100644
index 0000000000..34d68d0b6b
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -0,0 +1,259 @@
+import { Component, Show, createSignal, onMount, For } from 'solid-js';
+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';
+
+interface AIChatProps {
+ onClose: () => void;
+}
+
+export const AIChat: Component<AIChatProps> = (props) => {
+ // UI state
+ const [isOpen] = createSignal(true);
+ const [input, setInput] = createSignal('');
+ const [sessions, setSessions] = createSignal<ChatSession[]>([]);
+ const [showSessions, setShowSessions] = createSignal(false);
+
+ // Chat hook
+ const chat = useChat();
+
+ // Load sessions on mount
+ onMount(async () => {
+ try {
+ const status = await OpenCodeAPI.getStatus();
+ if (!status.running) {
+ notificationStore.warning('AI is not running');
+ return;
+ }
+ const sessionList = await OpenCodeAPI.listSessions();
+ setSessions(sessionList);
+ } catch (error) {
+ logger.error('[AIChat] Failed to initialize:', error);
+ }
+ });
+
+ // Handle submit
+ const handleSubmit = () => {
+ const prompt = input().trim();
+ if (!prompt) return;
+ chat.sendMessage(prompt);
+ setInput('');
+ };
+
+ // Handle key down
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ handleSubmit();
+ }
+ };
+
+ // New conversation
+ const handleNewConversation = async () => {
+ await chat.newSession();
+ setShowSessions(false);
+ };
+
+ // Load session
+ const handleLoadSession = async (sessionId: string) => {
+ await chat.loadSession(sessionId);
+ setShowSessions(false);
+ };
+
+ // Delete session
+ const handleDeleteSession = async (sessionId: string, e: Event) => {
+ e.stopPropagation();
+ if (!confirm('Delete this conversation?')) return;
+ try {
+ await OpenCodeAPI.deleteSession(sessionId);
+ setSessions(prev => prev.filter(s => s.id !== sessionId));
+ if (chat.sessionId() === sessionId) {
+ chat.clearMessages();
+ }
+ } catch (error) {
+ notificationStore.error('Failed to delete session');
+ }
+ };
+
+ // Empty state for approval (not used with OpenCode but keeping interface)
+ const handleApprove = (_messageId: string, _approval: PendingApproval) => {};
+ const handleSkip = (_messageId: string, _toolId: string) => {};
+
+ return (
+ <div
+ class={`flex-shrink-0 h-full bg-white dark:bg-gray-900 border-l border-gray-200 dark:border-gray-700 flex flex-col transition-all duration-300 overflow-hidden ${
+ isOpen() ? 'w-[420px]' : 'w-0 border-l-0'
+ }`}
+ >
+ <Show when={isOpen()}>
+ {/* Header */}
+ <div class="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-purple-50 to-violet-50 dark:from-purple-900/20 dark:to-violet-900/20">
+ <div class="flex items-center gap-3">
+ <div class="p-2 bg-gradient-to-br from-purple-500 to-violet-500 rounded-xl shadow-lg">
+ <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M9.75 3.104v5.714a2.25 2.25 0 01-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 014.5 0m0 0v5.714c0 .597.237 1.17.659 1.591L19.8 15.3M14.25 3.104c.251.023.501.05.75.082M19.8 15.3l-1.57.393A9.065 9.065 0 0112 15a9.065 9.065 0 00-6.23.693L5 14.5m14.8.8l1.402 1.402c1.232 1.232.65 3.318-1.067 3.611l-2.576.43a18.003 18.003 0 01-5.118 0l-2.576-.43c-1.717-.293-2.299-2.379-1.067-3.611L5 14.5" />
+ </svg>
+ </div>
+ <div>
+ <h2 class="text-sm font-semibold text-gray-900 dark:text-gray-100">AI Assistant</h2>
+ <p class="text-xs text-gray-500 dark:text-gray-400">
+ Powered by OpenCode
+ </p>
+ </div>
+ </div>
+
+ <div class="flex items-center gap-2">
+ {/* Session picker */}
+ <div class="relative">
+ <button
+ onClick={() => setShowSessions(!showSessions())}
+ class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
+ title="Chat sessions"
+ >
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
+ </svg>
+ </button>
+
+ <Show when={showSessions()}>
+ <div class="absolute right-0 top-full mt-1 w-72 max-h-96 bg-white dark:bg-gray-800 rounded-xl shadow-xl border border-gray-200 dark:border-gray-700 z-50 overflow-hidden">
+ <button
+ onClick={handleNewConversation}
+ class="w-full px-3 py-2.5 text-left text-sm flex items-center gap-2 text-purple-600 dark:text-purple-400 hover:bg-purple-50 dark:hover:bg-purple-900/20 border-b border-gray-200 dark:border-gray-700"
+ >
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
+ </svg>
+ <span class="font-medium">New conversation</span>
+ </button>
+
+ <div class="max-h-64 overflow-y-auto">
+ <Show when={sessions().length > 0} fallback={
+ <div class="px-3 py-6 text-center text-xs text-gray-500 dark:text-gray-400">
+ No previous conversations
+ </div>
+ }>
+ <For each={sessions()}>
+ {(session) => (
+ <div
+ class={`group relative px-3 py-2.5 flex items-start gap-2 hover:bg-gray-50 dark:hover:bg-gray-700/50 cursor-pointer ${chat.sessionId() === session.id ? 'bg-purple-50 dark:bg-purple-900/20' : ''}`}
+ onClick={() => handleLoadSession(session.id)}
+ >
+ <div class="flex-1 min-w-0">
+ <div class="text-sm font-medium truncate text-gray-900 dark:text-gray-100">
+ {session.title || 'Untitled'}
+ </div>
+ <div class="text-xs text-gray-500 dark:text-gray-400">
+ {session.message_count} messages
+ </div>
+ </div>
+ <button
+ type="button"
+ class="flex-shrink-0 p-1 rounded opacity-0 group-hover:opacity-100 hover:bg-red-100 dark:hover:bg-red-900/30 text-gray-400 hover:text-red-500 transition-opacity"
+ onClick={(e) => handleDeleteSession(session.id, e)}
+ >
+ <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
+ </svg>
+ </button>
+ </div>
+ )}
+ </For>
+ </Show>
+ </div>
+ </div>
+ </Show>
+ </div>
+
+ {/* Close button */}
+ <button
+ onClick={props.onClose}
+ class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
+ >
+ <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 5l7 7-7 7M6 5l7 7-7 7" />
+ </svg>
+ </button>
+ </div>
+ </div>
+
+ {/* Messages */}
+ <ChatMessages
+ messages={chat.messages()}
+ onApprove={handleApprove}
+ onSkip={handleSkip}
+ emptyState={{
+ title: 'Start a conversation',
+ subtitle: 'Ask about your infrastructure, diagnose issues, or get help.',
+ suggestions: [
+ 'What VMs are running?',
+ 'Show me resource usage',
+ 'Any issues to investigate?',
+ ],
+ onSuggestionClick: (s) => setInput(s),
+ }}
+ />
+
+ {/* Loading indicator */}
+ <Show when={chat.isLoading()}>
+ <div class="px-4 py-2 bg-purple-50 dark:bg-purple-900/20 border-t border-purple-200 dark:border-purple-800 flex items-center gap-2 text-sm text-purple-700 dark:text-purple-300">
+ <svg class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
+ <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>
+ <span>Thinking...</span>
+ </div>
+ </Show>
+
+ {/* Input */}
+ <div class="border-t border-gray-200 dark:border-gray-700 p-4 bg-white dark:bg-gray-900">
+ <form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="flex gap-2">
+ <textarea
+ value={input()}
+ onInput={(e) => setInput(e.currentTarget.value)}
+ onKeyDown={handleKeyDown}
+ placeholder="Ask about your infrastructure..."
+ rows={2}
+ class="flex-1 px-4 py-3 text-sm rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent resize-none"
+ />
+ <div class="flex flex-col gap-1.5 self-end">
+ <Show
+ when={chat.isLoading()}
+ fallback={
+ <button
+ type="submit"
+ disabled={!input().trim()}
+ class="px-4 py-3 bg-gradient-to-r from-purple-600 to-violet-600 hover:from-purple-700 hover:to-violet-700 text-white rounded-xl disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-lg hover:shadow-xl"
+ >
+ <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
+ </svg>
+ </button>
+ }
+ >
+ <button
+ type="button"
+ onClick={chat.stop}
+ class="px-4 py-3 bg-red-500 hover:bg-red-600 text-white rounded-xl transition-colors shadow-sm"
+ title="Stop"
+ >
+ <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
+ <rect x="6" y="6" width="12" height="12" rx="1" />
+ </svg>
+ </button>
+ </Show>
+ </div>
+ </form>
+ <p class="text-xs text-gray-400 dark:text-gray-500 mt-2 text-center">
+ Press Enter to send, Shift+Enter for new line
+ </p>
+ </div>
+ </Show>
+ </div>
+ );
+};
+
+export default AIChat;
diff --git a/frontend-modern/src/components/AI/Chat/types.ts b/frontend-modern/src/components/AI/Chat/types.ts
new file mode 100644
index 0000000000..6fef7635fd
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/types.ts
@@ -0,0 +1,102 @@
+// Chat component types
+
+export interface ToolExecution {
+ name: string;
+ input: string;
+ output: string;
+ success: boolean;
+}
+
+export interface PendingTool {
+ name: string;
+ input: string;
+}
+
+export interface PendingApproval {
+ command: string;
+ toolId: string;
+ toolName: string;
+ runOnHost: boolean;
+ targetHost?: string;
+ isExecuting?: boolean;
+}
+
+// Unified event for chronological display
+export type StreamEventType = 'thinking' | 'tool' | 'content';
+
+export interface StreamDisplayEvent {
+ type: StreamEventType;
+ thinking?: string;
+ tool?: ToolExecution;
+ content?: string;
+}
+
+export interface ChatMessage {
+ id: string;
+ role: 'user' | 'assistant';
+ content: string;
+ thinking?: string;
+ thinkingChunks?: string[];
+ streamEvents?: StreamDisplayEvent[];
+ timestamp: Date;
+ model?: string;
+ tokens?: { input: number; output: number };
+ toolCalls?: ToolExecution[];
+ isStreaming?: boolean;
+ pendingTools?: PendingTool[];
+ pendingApprovals?: PendingApproval[];
+}
+
+export interface ModelInfo {
+ id: string;
+ name: string;
+ description?: string;
+}
+
+export interface ChatContextItem {
+ id: string;
+ type: string;
+ name: string;
+ status: string;
+ node?: string;
+ data: Record<string, unknown>;
+}
+
+// Stream event types from backend
+export type StreamEventKind =
+ | 'content'
+ | 'thinking'
+ | 'tool_start'
+ | 'tool_end'
+ | 'approval_needed'
+ | 'processing'
+ | 'complete'
+ | 'done'
+ | 'error';
+
+export interface StreamToolStartData {
+ name: string;
+ input: string;
+}
+
+export interface StreamToolEndData {
+ name: string;
+ input: string;
+ output: string;
+ success: boolean;
+}
+
+export interface StreamApprovalNeededData {
+ command: string;
+ tool_id: string;
+ tool_name: string;
+ run_on_host: boolean;
+ target_host?: string;
+}
+
+export interface StreamCompleteData {
+ model: string;
+ input_tokens: number;
+ output_tokens: number;
+ tool_calls?: ToolExecution[];
+}
diff --git a/frontend-modern/vite.config.ts b/frontend-modern/vite.config.ts
index 8e52b67485..473d71f915 100644
--- a/frontend-modern/vite.config.ts
+++ b/frontend-modern/vite.config.ts
@@ -224,6 +224,13 @@ export default defineConfig({
target: backendUrl,
changeOrigin: true,
},
+ // OpenCode Web UI proxy - serves OpenCode's built-in interface
+ '/opencode': {
+ target: backendUrl,
+ changeOrigin: true,
+ // WebSocket support for OpenCode's real-time features
+ ws: true,
+ },
},
},
build: {
diff --git a/internal/ai/findings_mcp_adapter.go b/internal/ai/findings_mcp_adapter.go
new file mode 100644
index 0000000000..7ec7e3e5d8
--- /dev/null
+++ b/internal/ai/findings_mcp_adapter.go
@@ -0,0 +1,79 @@
+package ai
+
+import (
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/mcp"
+)
+
+// FindingsMCPAdapter adapts FindingsStore to MCP FindingsProvider interface
+type FindingsMCPAdapter struct {
+ store *FindingsStore
+}
+
+// NewFindingsMCPAdapter creates a new adapter for findings store
+func NewFindingsMCPAdapter(store *FindingsStore) *FindingsMCPAdapter {
+ if store == nil {
+ return nil
+ }
+ return &FindingsMCPAdapter{store: store}
+}
+
+// GetActiveFindings implements mcp.FindingsProvider
+func (a *FindingsMCPAdapter) GetActiveFindings() []mcp.Finding {
+ if a.store == nil {
+ return nil
+ }
+
+ // Get all active findings (empty severity means all)
+ internal := a.store.GetActive("")
+ result := make([]mcp.Finding, 0, len(internal))
+
+ for _, f := range internal {
+ result = append(result, mcp.Finding{
+ ID: f.ID,
+ Key: f.Key,
+ Severity: string(f.Severity),
+ Category: string(f.Category),
+ ResourceID: f.ResourceID,
+ ResourceName: f.ResourceName,
+ ResourceType: f.ResourceType,
+ Title: f.Title,
+ Description: f.Description,
+ Recommendation: f.Recommendation,
+ Evidence: f.Evidence,
+ DetectedAt: f.DetectedAt,
+ LastSeenAt: f.LastSeenAt,
+ })
+ }
+
+ return result
+}
+
+// GetDismissedFindings implements mcp.FindingsProvider
+func (a *FindingsMCPAdapter) GetDismissedFindings() []mcp.Finding {
+ if a.store == nil {
+ return nil
+ }
+
+ internal := a.store.GetDismissedFindings()
+ result := make([]mcp.Finding, 0, len(internal))
+
+ for _, f := range internal {
+ result = append(result, mcp.Finding{
+ ID: f.ID,
+ Key: f.Key,
+ Severity: string(f.Severity),
+ Category: string(f.Category),
+ ResourceID: f.ResourceID,
+ ResourceName: f.ResourceName,
+ ResourceType: f.ResourceType,
+ Title: f.Title,
+ Description: f.Description,
+ Recommendation: f.Recommendation,
+ Evidence: f.Evidence,
+ DetectedAt: f.DetectedAt,
+ LastSeenAt: f.LastSeenAt,
+ })
+ }
+
+ return result
+}
diff --git a/internal/ai/mcp/adapters.go b/internal/ai/mcp/adapters.go
new file mode 100644
index 0000000000..91e7dd6d8e
--- /dev/null
+++ b/internal/ai/mcp/adapters.go
@@ -0,0 +1,49 @@
+package mcp
+
+import (
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+)
+
+// AlertManagerMCPAdapter adapts alerts.Manager to MCP AlertProvider interface
+type AlertManagerMCPAdapter struct {
+ manager AlertManager
+}
+
+// AlertManager interface matches what alerts.Manager provides
+type AlertManager interface {
+ GetActiveAlerts() []alerts.Alert
+}
+
+// NewAlertManagerMCPAdapter creates a new adapter for alert manager
+func NewAlertManagerMCPAdapter(manager AlertManager) *AlertManagerMCPAdapter {
+ if manager == nil {
+ return nil
+ }
+ return &AlertManagerMCPAdapter{manager: manager}
+}
+
+// GetActiveAlerts implements mcp.AlertProvider
+func (a *AlertManagerMCPAdapter) GetActiveAlerts() []ActiveAlert {
+ if a.manager == nil {
+ return nil
+ }
+
+ activeAlerts := a.manager.GetActiveAlerts()
+ result := make([]ActiveAlert, 0, len(activeAlerts))
+
+ for _, alert := range activeAlerts {
+ result = append(result, ActiveAlert{
+ ID: alert.ID,
+ ResourceID: alert.ResourceID,
+ ResourceName: alert.ResourceName,
+ Type: alert.Type,
+ Severity: string(alert.Level),
+ Value: alert.Value,
+ Threshold: alert.Threshold,
+ StartTime: alert.StartTime,
+ Message: alert.Message,
+ })
+ }
+
+ return result
+}
diff --git a/internal/ai/mcp/protocol.go b/internal/ai/mcp/protocol.go
new file mode 100644
index 0000000000..bcfc7c43ff
--- /dev/null
+++ b/internal/ai/mcp/protocol.go
@@ -0,0 +1,233 @@
+package mcp
+
+import (
+ "encoding/json"
+)
+
+// JSON-RPC 2.0 types for MCP protocol
+
+// Request represents a JSON-RPC request
+type Request struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID interface{} `json:"id,omitempty"`
+ Method string `json:"method"`
+ Params json.RawMessage `json:"params,omitempty"`
+}
+
+// Response represents a JSON-RPC response
+type Response struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID interface{} `json:"id,omitempty"`
+ Result json.RawMessage `json:"result,omitempty"`
+ Error *Error `json:"error,omitempty"`
+}
+
+// Error represents a JSON-RPC error
+type Error struct {
+ Code int `json:"code"`
+ Message string `json:"message"`
+ Data interface{} `json:"data,omitempty"`
+}
+
+// Standard JSON-RPC error codes
+const (
+ ErrParse = -32700
+ ErrInvalidRequest = -32600
+ ErrMethodNotFound = -32601
+ ErrInvalidParams = -32602
+ ErrInternal = -32603
+)
+
+// MCP-specific types
+
+// ServerInfo describes the MCP server
+type ServerInfo struct {
+ Name string `json:"name"`
+ Version string `json:"version"`
+ Capabilities Capabilities `json:"capabilities,omitempty"`
+}
+
+// Capabilities describes what the server supports
+type Capabilities struct {
+ Tools *ToolsCapability `json:"tools,omitempty"`
+ Resources *ResourcesCapability `json:"resources,omitempty"`
+ Prompts *PromptsCapability `json:"prompts,omitempty"`
+}
+
+// ToolsCapability describes tool support
+type ToolsCapability struct {
+ ListChanged bool `json:"listChanged,omitempty"`
+}
+
+// ResourcesCapability describes resource support
+type ResourcesCapability struct {
+ Subscribe bool `json:"subscribe,omitempty"`
+ ListChanged bool `json:"listChanged,omitempty"`
+}
+
+// PromptsCapability describes prompt support
+type PromptsCapability struct {
+ ListChanged bool `json:"listChanged,omitempty"`
+}
+
+// InitializeParams are the params for the initialize method
+type InitializeParams struct {
+ ProtocolVersion string `json:"protocolVersion"`
+ Capabilities Capabilities `json:"capabilities"`
+ ClientInfo ClientInfo `json:"clientInfo"`
+}
+
+// ClientInfo describes the client
+type ClientInfo struct {
+ Name string `json:"name"`
+ Version string `json:"version"`
+}
+
+// InitializeResult is the result of the initialize method
+type InitializeResult struct {
+ ProtocolVersion string `json:"protocolVersion"`
+ Capabilities Capabilities `json:"capabilities"`
+ ServerInfo ServerInfo `json:"serverInfo"`
+}
+
+// Tool describes an available tool
+type Tool struct {
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ InputSchema InputSchema `json:"inputSchema"`
+}
+
+// InputSchema describes the expected input for a tool
+type InputSchema struct {
+ Type string `json:"type"` // Always "object"
+ Properties map[string]PropertySchema `json:"properties,omitempty"`
+ Required []string `json:"required,omitempty"`
+}
+
+// PropertySchema describes a property in the input schema
+type PropertySchema struct {
+ Type string `json:"type"`
+ Description string `json:"description,omitempty"`
+ Enum []string `json:"enum,omitempty"`
+ Default interface{} `json:"default,omitempty"`
+}
+
+// ListToolsResult is the result of tools/list
+type ListToolsResult struct {
+ Tools []Tool `json:"tools"`
+}
+
+// CallToolParams are the params for tools/call
+type CallToolParams struct {
+ Name string `json:"name"`
+ Arguments map[string]interface{} `json:"arguments,omitempty"`
+}
+
+// CallToolResult is the result of tools/call
+type CallToolResult struct {
+ Content []Content `json:"content"`
+ IsError bool `json:"isError,omitempty"`
+}
+
+// Content represents content in a tool result
+type Content struct {
+ Type string `json:"type"` // "text", "image", "resource"
+ Text string `json:"text,omitempty"`
+ MimeType string `json:"mimeType,omitempty"`
+ Data string `json:"data,omitempty"` // base64 for images
+ URI string `json:"uri,omitempty"` // for resources
+}
+
+// Resource describes an available resource
+type Resource struct {
+ URI string `json:"uri"`
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ MimeType string `json:"mimeType,omitempty"`
+}
+
+// ListResourcesResult is the result of resources/list
+type ListResourcesResult struct {
+ Resources []Resource `json:"resources"`
+}
+
+// ReadResourceParams are the params for resources/read
+type ReadResourceParams struct {
+ URI string `json:"uri"`
+}
+
+// ReadResourceResult is the result of resources/read
+type ReadResourceResult struct {
+ Contents []ResourceContent `json:"contents"`
+}
+
+// ResourceContent is the content of a resource
+type ResourceContent struct {
+ URI string `json:"uri"`
+ MimeType string `json:"mimeType,omitempty"`
+ Text string `json:"text,omitempty"`
+ Blob string `json:"blob,omitempty"` // base64
+}
+
+// Prompt describes an available prompt template
+type Prompt struct {
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ Arguments []PromptArgument `json:"arguments,omitempty"`
+}
+
+// PromptArgument describes an argument for a prompt
+type PromptArgument struct {
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ Required bool `json:"required,omitempty"`
+}
+
+// ListPromptsResult is the result of prompts/list
+type ListPromptsResult struct {
+ Prompts []Prompt `json:"prompts"`
+}
+
+// GetPromptParams are the params for prompts/get
+type GetPromptParams struct {
+ Name string `json:"name"`
+ Arguments map[string]string `json:"arguments,omitempty"`
+}
+
+// GetPromptResult is the result of prompts/get
+type GetPromptResult struct {
+ Description string `json:"description,omitempty"`
+ Messages []PromptMessage `json:"messages"`
+}
+
+// PromptMessage is a message in a prompt
+type PromptMessage struct {
+ Role string `json:"role"` // "user" or "assistant"
+ Content Content `json:"content"`
+}
+
+// Helper functions
+
+// NewTextContent creates a text content object
+func NewTextContent(text string) Content {
+ return Content{
+ Type: "text",
+ Text: text,
+ }
+}
+
+// NewErrorResult creates an error tool result
+func NewErrorResult(err error) CallToolResult {
+ return CallToolResult{
+ Content: []Content{NewTextContent(err.Error())},
+ IsError: true,
+ }
+}
+
+// NewTextResult creates a successful text tool result
+func NewTextResult(text string) CallToolResult {
+ return CallToolResult{
+ Content: []Content{NewTextContent(text)},
+ IsError: false,
+ }
+}
diff --git a/internal/ai/mcp/server.go b/internal/ai/mcp/server.go
new file mode 100644
index 0000000000..b240037cbf
--- /dev/null
+++ b/internal/ai/mcp/server.go
@@ -0,0 +1,364 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "sync"
+
+ "github.com/rs/zerolog/log"
+)
+
+const (
+ ProtocolVersion = "2024-11-05"
+ ServerName = "pulse-mcp"
+ ServerVersion = "1.0.0"
+)
+
+// ToolExecutor executes tools on behalf of the MCP server
+type ToolExecutor interface {
+ ExecuteTool(ctx context.Context, name string, args map[string]interface{}) (CallToolResult, error)
+ ListTools() []Tool
+}
+
+// Server implements an MCP server over HTTP
+type Server struct {
+ mu sync.RWMutex
+ executor ToolExecutor
+ addr string
+ server *http.Server
+}
+
+// NewServer creates a new MCP server
+func NewServer(addr string, executor ToolExecutor) *Server {
+ return &Server{
+ addr: addr,
+ executor: executor,
+ }
+}
+
+// Start starts the MCP server
+func (s *Server) Start() error {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/", s.handleRequest)
+ mux.HandleFunc("/health", s.handleHealth)
+
+ s.server = &http.Server{
+ Addr: s.addr,
+ Handler: mux,
+ }
+
+ log.Info().Str("addr", s.addr).Msg("Starting MCP server")
+ return s.server.ListenAndServe()
+}
+
+// Stop stops the MCP server
+func (s *Server) Stop(ctx context.Context) error {
+ if s.server != nil {
+ return s.server.Shutdown(ctx)
+ }
+ return nil
+}
+
+// Addr returns the server address
+func (s *Server) Addr() string {
+ return s.addr
+}
+
+func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ w.Write([]byte(`{"status": "ok"}`))
+}
+
+func (s *Server) handleRequest(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ s.writeError(w, nil, ErrParse, "Failed to read request body")
+ return
+ }
+ defer r.Body.Close()
+
+ var req Request
+ if err := json.Unmarshal(body, &req); err != nil {
+ s.writeError(w, nil, ErrParse, "Failed to parse JSON-RPC request")
+ return
+ }
+
+ if req.JSONRPC != "2.0" {
+ s.writeError(w, req.ID, ErrInvalidRequest, "Invalid JSON-RPC version")
+ return
+ }
+
+ log.Debug().
+ Str("method", req.Method).
+ Interface("id", req.ID).
+ Msg("MCP request received")
+
+ result, mcpErr := s.handleMethod(r.Context(), req)
+ if mcpErr != nil {
+ s.writeErrorResponse(w, req.ID, mcpErr)
+ return
+ }
+
+ s.writeResult(w, req.ID, result)
+}
+
+func (s *Server) handleMethod(ctx context.Context, req Request) (interface{}, *Error) {
+ switch req.Method {
+ case "initialize":
+ return s.handleInitialize(req.Params)
+ case "initialized":
+ // Client notification that initialization is complete
+ return nil, nil
+ case "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)
+ case "prompts/list":
+ return s.handleListPrompts()
+ case "prompts/get":
+ return s.handleGetPrompt(req.Params)
+ case "ping":
+ return map[string]interface{}{}, nil
+ default:
+ return nil, &Error{
+ Code: ErrMethodNotFound,
+ Message: fmt.Sprintf("Method not found: %s", req.Method),
+ }
+ }
+}
+
+func (s *Server) handleInitialize(params json.RawMessage) (*InitializeResult, *Error) {
+ var initParams InitializeParams
+ if params != nil {
+ if err := json.Unmarshal(params, &initParams); err != nil {
+ return nil, &Error{
+ Code: ErrInvalidParams,
+ Message: "Failed to parse initialize params",
+ }
+ }
+ }
+
+ log.Info().
+ Str("client", initParams.ClientInfo.Name).
+ Str("clientVersion", initParams.ClientInfo.Version).
+ Str("protocolVersion", initParams.ProtocolVersion).
+ Msg("MCP client connected")
+
+ return &InitializeResult{
+ ProtocolVersion: ProtocolVersion,
+ Capabilities: Capabilities{
+ Tools: &ToolsCapability{
+ ListChanged: false,
+ },
+ Resources: &ResourcesCapability{
+ Subscribe: false,
+ ListChanged: false,
+ },
+ },
+ ServerInfo: ServerInfo{
+ Name: ServerName,
+ Version: ServerVersion,
+ },
+ }, nil
+}
+
+func (s *Server) handleListTools() (*ListToolsResult, *Error) {
+ s.mu.RLock()
+ executor := s.executor
+ s.mu.RUnlock()
+
+ if executor == nil {
+ return &ListToolsResult{Tools: []Tool{}}, nil
+ }
+
+ tools := executor.ListTools()
+ return &ListToolsResult{Tools: tools}, nil
+}
+
+func (s *Server) handleCallTool(ctx context.Context, params json.RawMessage) (*CallToolResult, *Error) {
+ var callParams CallToolParams
+ if err := json.Unmarshal(params, &callParams); err != nil {
+ return nil, &Error{
+ Code: ErrInvalidParams,
+ Message: "Failed to parse tool call params",
+ }
+ }
+
+ s.mu.RLock()
+ executor := s.executor
+ s.mu.RUnlock()
+
+ if executor == nil {
+ return nil, &Error{
+ Code: ErrInternal,
+ Message: "No tool executor configured",
+ }
+ }
+
+ log.Debug().
+ Str("tool", callParams.Name).
+ Interface("args", callParams.Arguments).
+ Msg("Executing tool")
+
+ result, err := executor.ExecuteTool(ctx, callParams.Name, callParams.Arguments)
+ if err != nil {
+ log.Error().Err(err).Str("tool", callParams.Name).Msg("Tool execution failed")
+ return &CallToolResult{
+ Content: []Content{NewTextContent(err.Error())},
+ IsError: true,
+ }, nil
+ }
+
+ return &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 {
+ s.writeError(w, id, ErrInternal, "Failed to marshal result")
+ return
+ }
+
+ resp := Response{
+ JSONRPC: "2.0",
+ ID: id,
+ Result: resultJSON,
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(resp)
+}
+
+func (s *Server) writeError(w http.ResponseWriter, id interface{}, code int, message string) {
+ s.writeErrorResponse(w, id, &Error{Code: code, Message: message})
+}
+
+func (s *Server) writeErrorResponse(w http.ResponseWriter, id interface{}, err *Error) {
+ resp := Response{
+ JSONRPC: "2.0",
+ ID: id,
+ Error: err,
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(resp)
+}
+
+// SetExecutor updates the tool executor
+func (s *Server) SetExecutor(executor ToolExecutor) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.executor = executor
+}
diff --git a/internal/ai/mcp/tools.go b/internal/ai/mcp/tools.go
new file mode 100644
index 0000000000..f9390011fe
--- /dev/null
+++ b/internal/ai/mcp/tools.go
@@ -0,0 +1,1425 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "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
+}
+
+// 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
+
+ // 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
+}
+
+// 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 {
+ return []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_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{},
+ },
+ },
+ }
+}
+
+// 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 "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)
+ 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
+ }
+
+ // 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 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) 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)
+}
+
+// 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
+}
diff --git a/internal/ai/opencode/bridge.go b/internal/ai/opencode/bridge.go
new file mode 100644
index 0000000000..d60722901f
--- /dev/null
+++ b/internal/ai/opencode/bridge.go
@@ -0,0 +1,299 @@
+package opencode
+
+import (
+ "encoding/json"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai"
+)
+
+// Bridge transforms OpenCode events to Pulse StreamEvent format
+type Bridge struct{}
+
+// NewBridge creates a new event bridge
+func NewBridge() *Bridge {
+ return &Bridge{}
+}
+
+// TransformEvent converts an OpenCode StreamEvent to a Pulse StreamEvent
+func (b *Bridge) TransformEvent(ocEvent StreamEvent) (ai.StreamEvent, error) {
+ switch ocEvent.Type {
+ case "tool_use", "tool_call":
+ return b.transformToolUse(ocEvent)
+ case "tool_result":
+ return b.transformToolResult(ocEvent)
+ case "content", "text":
+ return b.transformContent(ocEvent)
+ case "thinking":
+ return b.transformThinking(ocEvent)
+ case "complete", "done":
+ return b.transformComplete(ocEvent)
+ case "error":
+ return b.transformError(ocEvent)
+ default:
+ // Pass through unknown events as content
+ return ai.StreamEvent{
+ Type: "content",
+ Data: string(ocEvent.Data),
+ }, nil
+ }
+}
+
+func (b *Bridge) transformToolUse(ocEvent StreamEvent) (ai.StreamEvent, error) {
+ var toolUse ToolUseEvent
+ if err := json.Unmarshal(ocEvent.Data, &toolUse); err != nil {
+ return ai.StreamEvent{}, err
+ }
+
+ // Format input for display
+ inputStr := formatToolInput(toolUse.Name, toolUse.Input)
+
+ return ai.StreamEvent{
+ Type: "tool_start",
+ Data: ai.ToolStartData{
+ Name: mapToolName(toolUse.Name),
+ Input: inputStr,
+ },
+ }, nil
+}
+
+func (b *Bridge) transformToolResult(ocEvent StreamEvent) (ai.StreamEvent, error) {
+ var toolResult ToolResultEvent
+ if err := json.Unmarshal(ocEvent.Data, &toolResult); err != nil {
+ return ai.StreamEvent{}, err
+ }
+
+ // Check if this is an approval_needed response
+ if isApprovalNeeded(toolResult.Output) {
+ return b.handleApprovalNeeded(toolResult)
+ }
+
+ return ai.StreamEvent{
+ Type: "tool_end",
+ Data: ai.ToolEndData{
+ Name: mapToolName(toolResult.Name),
+ Input: "", // We don't have input in the result, frontend should track it
+ Output: toolResult.Output,
+ Success: toolResult.Success,
+ },
+ }, nil
+}
+
+func (b *Bridge) transformContent(ocEvent StreamEvent) (ai.StreamEvent, error) {
+ var content ContentEvent
+ if err := json.Unmarshal(ocEvent.Data, &content); err != nil {
+ // If it's not a structured event, treat it as raw content
+ return ai.StreamEvent{
+ Type: "content",
+ Data: string(ocEvent.Data),
+ }, nil
+ }
+
+ // Use delta if available, otherwise use full content
+ text := content.Delta
+ if text == "" {
+ text = content.Content
+ }
+
+ return ai.StreamEvent{
+ Type: "content",
+ Data: text,
+ }, nil
+}
+
+func (b *Bridge) transformThinking(ocEvent StreamEvent) (ai.StreamEvent, error) {
+ var content ContentEvent
+ if err := json.Unmarshal(ocEvent.Data, &content); err != nil {
+ return ai.StreamEvent{
+ Type: "thinking",
+ Data: string(ocEvent.Data),
+ }, nil
+ }
+
+ return ai.StreamEvent{
+ Type: "thinking",
+ Data: content.Content,
+ }, nil
+}
+
+func (b *Bridge) transformComplete(ocEvent StreamEvent) (ai.StreamEvent, error) {
+ var complete CompleteEvent
+ if err := json.Unmarshal(ocEvent.Data, &complete); err != nil {
+ // Return basic done event
+ return ai.StreamEvent{
+ Type: "done",
+ Data: map[string]interface{}{},
+ }, nil
+ }
+
+ return ai.StreamEvent{
+ Type: "done",
+ Data: map[string]interface{}{
+ "session_id": complete.SessionID,
+ "input_tokens": complete.Usage.InputTokens,
+ "output_tokens": complete.Usage.OutputTokens,
+ "model": complete.Model.ID,
+ "provider": complete.Model.Provider,
+ },
+ }, nil
+}
+
+func (b *Bridge) transformError(ocEvent StreamEvent) (ai.StreamEvent, error) {
+ var errorEvent ErrorEvent
+ if err := json.Unmarshal(ocEvent.Data, &errorEvent); err != nil {
+ return ai.StreamEvent{
+ Type: "error",
+ Data: string(ocEvent.Data),
+ }, nil
+ }
+
+ msg := errorEvent.Message
+ if msg == "" {
+ msg = errorEvent.Error
+ }
+
+ return ai.StreamEvent{
+ Type: "error",
+ Data: msg,
+ }, nil
+}
+
+func (b *Bridge) handleApprovalNeeded(toolResult ToolResultEvent) (ai.StreamEvent, error) {
+ // Parse the approval needed data from tool output
+ // Format: APPROVAL_REQUIRED: {"command": "...", "tool_id": "...", ...}
+ approvalData := parseApprovalFromOutput(toolResult.Output)
+
+ return ai.StreamEvent{
+ Type: "approval_needed",
+ Data: ai.ApprovalNeededData{
+ Command: approvalData.Command,
+ ToolID: toolResult.ID,
+ ToolName: mapToolName(toolResult.Name),
+ RunOnHost: approvalData.RunOnHost,
+ TargetHost: approvalData.TargetHost,
+ },
+ }, nil
+}
+
+// mapToolName maps OpenCode/MCP tool names to Pulse tool names
+func mapToolName(name string) string {
+ // Map pulse_ prefixed MCP tools back to original names
+ switch name {
+ case "pulse_run_command":
+ return "run_command"
+ case "pulse_fetch_url":
+ return "fetch_url"
+ case "pulse_set_resource_url":
+ return "set_resource_url"
+ case "pulse_resolve_finding":
+ return "resolve_finding"
+ case "pulse_dismiss_finding":
+ return "dismiss_finding"
+ case "pulse_get_infrastructure_state":
+ return "get_infrastructure_state"
+ default:
+ return name
+ }
+}
+
+// formatToolInput formats tool input for display
+func formatToolInput(name string, input map[string]interface{}) string {
+ switch name {
+ case "pulse_run_command", "run_command":
+ if cmd, ok := input["command"].(string); ok {
+ return cmd
+ }
+ case "pulse_fetch_url", "fetch_url":
+ if url, ok := input["url"].(string); ok {
+ return url
+ }
+ }
+
+ // Default: return JSON
+ b, _ := json.Marshal(input)
+ return string(b)
+}
+
+// isApprovalNeeded checks if a tool result indicates approval is required
+func isApprovalNeeded(output string) bool {
+ return len(output) > 18 && output[:18] == "APPROVAL_REQUIRED:"
+}
+
+// approvalInfo holds parsed approval data
+type approvalInfo struct {
+ Command string
+ RunOnHost bool
+ TargetHost string
+}
+
+// parseApprovalFromOutput parses approval data from tool output
+func parseApprovalFromOutput(output string) approvalInfo {
+ if !isApprovalNeeded(output) {
+ return approvalInfo{}
+ }
+
+ // Try to parse JSON after the prefix
+ jsonStr := output[18:]
+ var data struct {
+ Command string `json:"command"`
+ RunOnHost bool `json:"run_on_host"`
+ TargetHost string `json:"target_host"`
+ }
+
+ if err := json.Unmarshal([]byte(jsonStr), &data); err != nil {
+ // Fallback: treat the rest as the command
+ return approvalInfo{Command: jsonStr}
+ }
+
+ return approvalInfo{
+ Command: data.Command,
+ RunOnHost: data.RunOnHost,
+ TargetHost: data.TargetHost,
+ }
+}
+
+// StreamEvents takes an OpenCode event channel and transforms to Pulse events
+func (b *Bridge) StreamEvents(
+ ocEvents <-chan StreamEvent,
+ ocErrors <-chan error,
+) (<-chan ai.StreamEvent, <-chan error) {
+ pulseEvents := make(chan ai.StreamEvent, 100)
+ pulseErrors := make(chan error, 1)
+
+ go func() {
+ defer close(pulseEvents)
+ defer close(pulseErrors)
+
+ for {
+ select {
+ case event, ok := <-ocEvents:
+ if !ok {
+ return
+ }
+
+ pulseEvent, err := b.TransformEvent(event)
+ if err != nil {
+ pulseErrors <- err
+ return
+ }
+
+ pulseEvents <- pulseEvent
+
+ // Check if this is the final event
+ if pulseEvent.Type == "done" || pulseEvent.Type == "error" {
+ return
+ }
+
+ case err, ok := <-ocErrors:
+ if !ok {
+ return
+ }
+ if err != nil {
+ pulseErrors <- err
+ return
+ }
+ }
+ }
+ }()
+
+ return pulseEvents, pulseErrors
+}
diff --git a/internal/ai/opencode/client.go b/internal/ai/opencode/client.go
new file mode 100644
index 0000000000..00c1765d18
--- /dev/null
+++ b/internal/ai/opencode/client.go
@@ -0,0 +1,655 @@
+package opencode
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/rs/zerolog/log"
+)
+
+// Client communicates with the OpenCode server
+type Client struct {
+ baseURL string
+ httpClient *http.Client
+}
+
+// NewClient creates a new OpenCode client
+func NewClient(baseURL string) *Client {
+ return &Client{
+ baseURL: strings.TrimSuffix(baseURL, "/"),
+ httpClient: newHTTPClient(5 * time.Minute),
+ }
+}
+
+func newHTTPClient(timeout time.Duration) *http.Client {
+ return &http.Client{
+ Timeout: timeout,
+ }
+}
+
+// Session represents an OpenCode chat session
+type Session struct {
+ ID string `json:"id"`
+ CreatedAt time.Time `json:"createdAt"`
+ UpdatedAt time.Time `json:"updatedAt"`
+}
+
+// Message represents a message in a session
+type Message struct {
+ ID string `json:"id"`
+ Role string `json:"role"` // "user" or "assistant"
+ Content string `json:"content"`
+ ToolCalls []ToolCall `json:"toolCalls,omitempty"`
+ Metadata map[string]interface{} `json:"metadata,omitempty"`
+}
+
+// ToolCall represents a tool invocation
+type ToolCall struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Input map[string]interface{} `json:"input"`
+ Output string `json:"output,omitempty"`
+}
+
+// PromptRequest is the request body for sending a prompt
+type PromptRequest struct {
+ Prompt string `json:"prompt"`
+ SessionID string `json:"sessionId,omitempty"`
+ Model string `json:"model,omitempty"`
+ SystemPrompt string `json:"systemPrompt,omitempty"`
+ Tools []string `json:"tools,omitempty"`
+ Context map[string]interface{} `json:"context,omitempty"`
+}
+
+// PromptResponse is the response from a prompt request
+type PromptResponse struct {
+ SessionID string `json:"sessionId"`
+ Message Message `json:"message"`
+ Usage Usage `json:"usage"`
+ Model ModelInfo `json:"model"`
+}
+
+// Usage contains token usage information
+type Usage struct {
+ InputTokens int `json:"inputTokens"`
+ OutputTokens int `json:"outputTokens"`
+}
+
+// ModelInfo contains model information
+type ModelInfo struct {
+ ID string `json:"id"`
+ Provider string `json:"provider"`
+}
+
+// StreamEvent represents an event from the SSE stream
+type StreamEvent struct {
+ Type string `json:"type"`
+ Data json.RawMessage `json:"data"`
+}
+
+// ContentEvent is emitted when content is generated
+type ContentEvent struct {
+ Content string `json:"content"`
+ Delta string `json:"delta,omitempty"`
+}
+
+// ToolUseEvent is emitted when a tool is invoked
+type ToolUseEvent struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Input map[string]interface{} `json:"input"`
+}
+
+// ToolResultEvent is emitted when a tool completes
+type ToolResultEvent struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Output string `json:"output"`
+ Success bool `json:"success"`
+}
+
+// CompleteEvent is emitted when the response is complete
+type CompleteEvent struct {
+ SessionID string `json:"sessionId"`
+ Message Message `json:"message"`
+ Usage Usage `json:"usage"`
+ Model ModelInfo `json:"model"`
+}
+
+// ErrorEvent is emitted when an error occurs
+type ErrorEvent struct {
+ Error string `json:"error"`
+ Code string `json:"code,omitempty"`
+ Message string `json:"message,omitempty"`
+}
+
+// Health checks the OpenCode server health
+func (c *Client) Health(ctx context.Context) error {
+ req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/global/health", nil)
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("health check failed: status %d", resp.StatusCode)
+ }
+
+ return nil
+}
+
+// ListSessions returns all sessions
+func (c *Client) ListSessions(ctx context.Context) ([]Session, error) {
+ req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/session", nil)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("list sessions failed: status %d", resp.StatusCode)
+ }
+
+ var sessions []Session
+ if err := json.NewDecoder(resp.Body).Decode(&sessions); err != nil {
+ return nil, err
+ }
+
+ return sessions, nil
+}
+
+// CreateSession creates a new session
+func (c *Client) CreateSession(ctx context.Context) (*Session, error) {
+ // OpenCode requires a JSON body, even if empty
+ req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/session", strings.NewReader("{}"))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
+ return nil, fmt.Errorf("create session failed: status %d", resp.StatusCode)
+ }
+
+ var session Session
+ if err := json.NewDecoder(resp.Body).Decode(&session); err != nil {
+ return nil, err
+ }
+
+ return &session, nil
+}
+
+// DeleteSession deletes a session
+func (c *Client) DeleteSession(ctx context.Context, sessionID string) error {
+ req, err := http.NewRequestWithContext(ctx, "DELETE", c.baseURL+"/session/"+sessionID, nil)
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
+ return fmt.Errorf("delete session failed: status %d", resp.StatusCode)
+ }
+
+ return nil
+}
+
+// Prompt sends a prompt and returns the response (non-streaming)
+func (c *Client) Prompt(ctx context.Context, req PromptRequest) (*PromptResponse, error) {
+ // Ensure we have a session
+ sessionID := req.SessionID
+ if sessionID == "" {
+ session, err := c.CreateSession(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create session: %w", err)
+ }
+ sessionID = session.ID
+ }
+
+ // OpenCode API uses /session/{id}/message with parts array format
+ messageReq := map[string]interface{}{
+ "parts": []map[string]interface{}{
+ {"type": "text", "text": req.Prompt},
+ },
+ }
+ if req.Model != "" {
+ messageReq["model"] = req.Model
+ }
+
+ body, err := json.Marshal(messageReq)
+ if err != nil {
+ return nil, err
+ }
+
+ httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/session/"+sessionID+"/message", bytes.NewReader(body))
+ if err != nil {
+ return nil, err
+ }
+ httpReq.Header.Set("Content-Type", "application/json")
+
+ resp, err := c.httpClient.Do(httpReq)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ bodyBytes, _ := io.ReadAll(resp.Body)
+ return nil, fmt.Errorf("prompt failed: status %d, body: %s", resp.StatusCode, string(bodyBytes))
+ }
+
+ var result PromptResponse
+ result.SessionID = sessionID
+ if err := json.NewDecoder(resp.Body).Decode(&result.Message); err != nil {
+ return nil, err
+ }
+
+ return &result, nil
+}
+
+// PromptStream sends a prompt and streams the response via SSE
+func (c *Client) PromptStream(ctx context.Context, req PromptRequest) (<-chan StreamEvent, <-chan error) {
+ events := make(chan StreamEvent, 100)
+ errs := make(chan error, 1)
+
+ go func() {
+ defer close(events)
+ defer close(errs)
+
+ // Ensure we have a valid OpenCode session
+ // OpenCode requires session IDs to start with "ses" - if the user passed
+ // their own session ID (e.g., from the frontend), we need to create a new
+ // OpenCode session anyway
+ sessionID := req.SessionID
+ if sessionID == "" || !strings.HasPrefix(sessionID, "ses") {
+ session, err := c.CreateSession(ctx)
+ if err != nil {
+ errs <- fmt.Errorf("failed to create session: %w", err)
+ return
+ }
+ sessionID = session.ID
+ }
+
+ // OpenCode uses /session/{id}/prompt_async for async/streaming with parts array format
+ messageReq := map[string]interface{}{
+ "parts": []map[string]interface{}{
+ {"type": "text", "text": req.Prompt},
+ },
+ }
+ if req.Model != "" {
+ messageReq["model"] = req.Model
+ }
+
+ body, err := json.Marshal(messageReq)
+ if err != nil {
+ errs <- err
+ return
+ }
+
+ // IMPORTANT: Subscribe to event stream FIRST, before sending prompt
+ // This prevents a race condition where fast responses (like from Gemini)
+ // complete before we've established the event subscription
+ eventReq, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/global/event", nil)
+ if err != nil {
+ errs <- err
+ return
+ }
+ eventReq.Header.Set("Accept", "text/event-stream")
+
+ // Use a client without timeout for streaming
+ streamClient := &http.Client{}
+ eventResp, err := streamClient.Do(eventReq)
+ if err != nil {
+ errs <- err
+ return
+ }
+ defer eventResp.Body.Close()
+
+ if eventResp.StatusCode != http.StatusOK {
+ bodyBytes, _ := io.ReadAll(eventResp.Body)
+ errs <- fmt.Errorf("event stream failed: status %d, body: %s", eventResp.StatusCode, string(bodyBytes))
+ return
+ }
+
+ // NOW send the async prompt request (after event stream is established)
+ httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/session/"+sessionID+"/prompt_async", bytes.NewReader(body))
+ if err != nil {
+ errs <- err
+ return
+ }
+ httpReq.Header.Set("Content-Type", "application/json")
+
+ resp, err := c.httpClient.Do(httpReq)
+ if err != nil {
+ errs <- err
+ return
+ }
+ resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusNoContent {
+ errs <- fmt.Errorf("prompt_async failed: status %d", resp.StatusCode)
+ return
+ }
+
+ // Parse SSE stream - OpenCode sends events in format:
+ // data: {"directory":"...","payload":{"type":"event.type","properties":{...}}}
+ // Events contain sessionID in properties - we must filter to only process our session
+ scanner := bufio.NewScanner(eventResp.Body)
+ // SSE lines can be very long (>64KB for some events), increase buffer
+ scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
+ var contentBuffer strings.Builder
+ var receivedContent bool // Track if we've received actual content from our prompt
+
+ log.Debug().Str("sessionID", sessionID).Msg("OpenCode: Starting to read event stream")
+
+ // Start a parallel poll goroutine as safety net for fast models
+ // If SSE doesn't receive content within 5 seconds, poll messages directly
+ pollDone := make(chan struct{})
+ go func() {
+ defer close(pollDone)
+ time.Sleep(5 * time.Second)
+
+ // Check if we've already received content from SSE
+ if receivedContent {
+ return
+ }
+
+ log.Debug().Msg("OpenCode: SSE timeout, falling back to message polling")
+
+ // Poll up to 10 times with 1 second intervals
+ for i := 0; i < 10; i++ {
+ if receivedContent {
+ return // SSE finally delivered
+ }
+
+ messages, err := c.GetMessages(ctx, sessionID)
+ if err != nil {
+ log.Warn().Err(err).Msg("OpenCode: Poll fallback failed")
+ time.Sleep(1 * time.Second)
+ continue
+ }
+
+ // Look for assistant message
+ for _, msg := range messages {
+ if msg.Role == "assistant" && msg.Content != "" {
+ // Found response! Send as content event
+ log.Info().Str("content", msg.Content[:min(50, len(msg.Content))]).Msg("OpenCode: Got response via polling")
+ contentData, _ := json.Marshal(msg.Content)
+ events <- StreamEvent{Type: "content", Data: contentData}
+ events <- StreamEvent{Type: "done", Data: nil}
+ receivedContent = true
+ return
+ }
+ }
+
+ time.Sleep(1 * time.Second)
+ }
+
+ // Timeout - send error
+ log.Warn().Msg("OpenCode: Polling timeout")
+ events <- StreamEvent{Type: "done", Data: nil}
+ }()
+
+ for scanner.Scan() {
+ select {
+ case <-ctx.Done():
+ errs <- ctx.Err()
+ return
+ default:
+ }
+
+ line := scanner.Text()
+ if line == "" || !strings.HasPrefix(line, "data:") {
+ continue
+ }
+
+ data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
+ if data == "" {
+ continue
+ }
+
+ // Parse the OpenCode event envelope
+ var envelope struct {
+ Payload struct {
+ Type string `json:"type"`
+ Properties json.RawMessage `json:"properties"`
+ } `json:"payload"`
+ }
+ if err := json.Unmarshal([]byte(data), &envelope); err != nil {
+ continue
+ }
+
+ eventType := envelope.Payload.Type
+
+ // Extract session ID from properties to filter events
+ var baseProps struct {
+ SessionID string `json:"sessionID"`
+ Part struct {
+ SessionID string `json:"sessionID"`
+ } `json:"part"`
+ }
+ json.Unmarshal(envelope.Payload.Properties, &baseProps)
+ eventSessionID := baseProps.SessionID
+ if eventSessionID == "" {
+ eventSessionID = baseProps.Part.SessionID
+ }
+
+ log.Debug().
+ Str("eventType", eventType).
+ Str("eventSessionID", eventSessionID).
+ Str("ourSessionID", sessionID).
+ Msg("OpenCode: Received event")
+
+ // Skip events from other sessions
+ if eventSessionID != "" && eventSessionID != sessionID {
+ log.Debug().Msg("OpenCode: Skipping event from other session")
+ continue
+ }
+
+ switch eventType {
+ case "message.part.updated":
+ // Content streaming - extract delta or text
+ var props struct {
+ Part struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+ Reason string `json:"reason"` // For step-finish: "stop" or "tool-calls"
+ Tool string `json:"tool"` // For tool parts
+ State struct {
+ Status string `json:"status"`
+ Output string `json:"output"`
+ } `json:"state"`
+ Time struct {
+ End int64 `json:"end"`
+ } `json:"time"`
+ } `json:"part"`
+ Delta string `json:"delta"`
+ }
+ if err := json.Unmarshal(envelope.Payload.Properties, &props); err != nil {
+ continue
+ }
+ log.Debug().Str("partType", props.Part.Type).Str("delta", props.Delta).Str("reason", props.Part.Reason).Msg("OpenCode: Processing message part")
+ if props.Part.Type == "text" || props.Part.Type == "reasoning" {
+ // Stream both text and reasoning content
+ if props.Delta != "" {
+ contentBuffer.WriteString(props.Delta)
+ receivedContent = true // Mark that we've received actual content
+ // Frontend expects just the delta string as data
+ deltaData, _ := json.Marshal(props.Delta)
+ log.Debug().Str("type", props.Part.Type).Str("delta", props.Delta).Msg("OpenCode: Sending content event")
+ events <- StreamEvent{Type: "content", Data: deltaData}
+ }
+ } else if props.Part.Type == "tool" {
+ // Tool execution - translate to frontend format
+ status := props.Part.State.Status
+ log.Debug().Str("tool", props.Part.Tool).Str("status", status).Msg("OpenCode: Tool execution")
+
+ if status == "pending" || status == "running" {
+ // Tool starting - send tool_start event
+ toolInfo := map[string]interface{}{
+ "name": props.Part.Tool,
+ "input": props.Part.Tool, // Use tool name as input display
+ }
+ toolData, _ := json.Marshal(toolInfo)
+ events <- StreamEvent{Type: "tool_start", Data: toolData}
+ } else if status == "completed" {
+ // Tool completed - send tool_end event
+ toolInfo := map[string]interface{}{
+ "name": props.Part.Tool,
+ "input": props.Part.Tool,
+ "output": props.Part.State.Output,
+ "success": true,
+ }
+ toolData, _ := json.Marshal(toolInfo)
+ events <- StreamEvent{Type: "tool_end", Data: toolData}
+ }
+ } else if props.Part.Type == "step-finish" {
+ // Step completed - only terminate if reason is "stop" (not "tool-calls")
+ log.Debug().Str("reason", props.Part.Reason).Msg("OpenCode: Step finished")
+ if props.Part.Reason == "stop" || props.Part.Reason == "" {
+ // Final response complete
+ events <- StreamEvent{Type: "done", Data: nil}
+ return
+ }
+ // If reason is "tool-calls", continue waiting for tool results and next response
+ }
+
+ case "session.idle":
+ // Session done processing - but only if we've received content
+ // Otherwise this is a stale event from before our prompt was processed
+ if receivedContent {
+ events <- StreamEvent{Type: "done", Data: nil}
+ return
+ }
+ log.Debug().Msg("OpenCode: Ignoring session.idle (no content received yet)")
+
+ case "session.status":
+ // Check if status is idle - but only finish if we've received content
+ var props struct {
+ Status struct {
+ Type string `json:"type"`
+ } `json:"status"`
+ }
+ if err := json.Unmarshal(envelope.Payload.Properties, &props); err == nil {
+ if props.Status.Type == "idle" && receivedContent {
+ events <- StreamEvent{Type: "done", Data: nil}
+ return
+ }
+ }
+ }
+ }
+
+ if err := scanner.Err(); err != nil {
+ errs <- err
+ }
+ }()
+
+ return events, errs
+}
+
+// GetMessages returns all messages in a session
+func (c *Client) GetMessages(ctx context.Context, sessionID string) ([]Message, error) {
+ req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/session/"+sessionID+"/message", nil)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("get messages failed: status %d", resp.StatusCode)
+ }
+
+ var messages []Message
+ if err := json.NewDecoder(resp.Body).Decode(&messages); err != nil {
+ return nil, err
+ }
+
+ return messages, nil
+}
+
+// AbortSession aborts the current operation in a session
+func (c *Client) AbortSession(ctx context.Context, sessionID string) error {
+ req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/session/"+sessionID+"/abort", nil)
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
+ return fmt.Errorf("abort session failed: status %d", resp.StatusCode)
+ }
+
+ return nil
+}
+
+// ListModels returns available models
+func (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error) {
+ req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/config/providers", nil)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("list models failed: status %d", resp.StatusCode)
+ }
+
+ var providers map[string]interface{}
+ if err := json.NewDecoder(resp.Body).Decode(&providers); err != nil {
+ return nil, err
+ }
+
+ // Transform provider response to model list
+ var models []ModelInfo
+ for provider := range providers {
+ // OpenCode returns provider configs, we'll need to map to actual models
+ models = append(models, ModelInfo{
+ Provider: provider,
+ })
+ }
+
+ return models, nil
+}
diff --git a/internal/ai/opencode/patrol.go b/internal/ai/opencode/patrol.go
new file mode 100644
index 0000000000..efe9e6148a
--- /dev/null
+++ b/internal/ai/opencode/patrol.go
@@ -0,0 +1,446 @@
+package opencode
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "regexp"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/rs/zerolog/log"
+)
+
+// PatrolFinding represents a finding from AI patrol analysis
+type PatrolFinding 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"`
+ Source string `json:"source"`
+ DetectedAt time.Time `json:"detected_at"`
+ LastSeenAt time.Time `json:"last_seen_at"`
+}
+
+// FindingsStore interface for storing patrol findings
+type FindingsStore interface {
+ Add(finding *PatrolFinding) bool // Returns true if finding is new
+ GetActive() []*PatrolFinding
+ GetDismissed() []*PatrolFinding
+}
+
+// PatrolStreamCallback is called for patrol streaming updates
+type PatrolStreamCallback func(event PatrolStreamEvent)
+
+// PatrolStreamEvent represents a streaming update from patrol
+type PatrolStreamEvent struct {
+ Type string `json:"type"` // "start", "content", "thinking", "tool_use", "complete", "error"
+ Content string `json:"content,omitempty"`
+ Phase string `json:"phase,omitempty"`
+}
+
+// PatrolResult contains the results of a patrol run
+type PatrolResult struct {
+ Findings []*PatrolFinding
+ NewFindings int
+ RawResponse string
+ InputTokens int
+ OutputTokens int
+ Duration time.Duration
+ Error error
+}
+
+// PatrolService runs AI patrol analysis using OpenCode
+type PatrolService struct {
+ mu sync.RWMutex
+
+ service *Service // OpenCode service
+ findingsStore FindingsStore // For storing findings
+ sessionID string // Dedicated patrol session
+ running bool // Whether a patrol is currently running
+ lastRun time.Time // Last patrol run time
+ lastResult *PatrolResult // Last patrol result
+
+ // Streaming support
+ streamMu sync.RWMutex
+ subscribers map[chan PatrolStreamEvent]struct{}
+ currentOutput strings.Builder
+}
+
+// NewPatrolService creates a new OpenCode-based patrol service
+func NewPatrolService(service *Service) *PatrolService {
+ return &PatrolService{
+ service: service,
+ subscribers: make(map[chan PatrolStreamEvent]struct{}),
+ }
+}
+
+// SetFindingsStore sets the findings store for persisting patrol results
+func (p *PatrolService) SetFindingsStore(store FindingsStore) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.findingsStore = store
+}
+
+// IsRunning returns whether a patrol is currently executing
+func (p *PatrolService) IsRunning() bool {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.running
+}
+
+// GetLastResult returns the most recent patrol result
+func (p *PatrolService) GetLastResult() *PatrolResult {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.lastResult
+}
+
+// Subscribe returns a channel for receiving patrol stream events
+func (p *PatrolService) Subscribe() chan PatrolStreamEvent {
+ ch := make(chan PatrolStreamEvent, 100)
+ p.streamMu.Lock()
+ p.subscribers[ch] = struct{}{}
+ p.streamMu.Unlock()
+ return ch
+}
+
+// Unsubscribe removes a subscriber channel
+func (p *PatrolService) Unsubscribe(ch chan PatrolStreamEvent) {
+ p.streamMu.Lock()
+ delete(p.subscribers, ch)
+ p.streamMu.Unlock()
+ close(ch)
+}
+
+// broadcast sends an event to all subscribers
+func (p *PatrolService) broadcast(event PatrolStreamEvent) {
+ p.streamMu.RLock()
+ defer p.streamMu.RUnlock()
+
+ for ch := range p.subscribers {
+ select {
+ case ch <- event:
+ default:
+ // Channel full, skip
+ }
+ }
+}
+
+// RunPatrol executes a patrol analysis using OpenCode (implements OpenCodePatrolRunner interface)
+func (p *PatrolService) RunPatrol(ctx context.Context) error {
+ _, err := p.RunPatrolWithResult(ctx)
+ return err
+}
+
+// RunPatrolWithResult executes a patrol analysis and returns detailed results
+func (p *PatrolService) RunPatrolWithResult(ctx context.Context) (*PatrolResult, error) {
+ p.mu.Lock()
+ if p.running {
+ p.mu.Unlock()
+ return nil, fmt.Errorf("patrol already running")
+ }
+ p.running = true
+ p.mu.Unlock()
+
+ defer func() {
+ p.mu.Lock()
+ p.running = false
+ p.mu.Unlock()
+ }()
+
+ start := time.Now()
+ result := &PatrolResult{}
+
+ // Check service is available
+ if p.service == nil || !p.service.IsRunning() {
+ result.Error = fmt.Errorf("OpenCode service not available")
+ return result, result.Error
+ }
+
+ // Build patrol prompt
+ prompt := p.buildPatrolPrompt()
+
+ log.Info().Msg("OpenCode Patrol: Starting infrastructure analysis")
+ p.broadcast(PatrolStreamEvent{Type: "start", Phase: "Starting patrol analysis"})
+
+ // Clear output buffer
+ p.streamMu.Lock()
+ p.currentOutput.Reset()
+ p.streamMu.Unlock()
+
+ // Execute via OpenCode streaming
+ var responseBuffer strings.Builder
+
+ err := p.service.ExecuteStream(ctx, ExecuteRequest{
+ Prompt: prompt,
+ SessionID: p.sessionID, // Use dedicated session for patrol context
+ }, func(event StreamEvent) {
+ switch event.Type {
+ case "content":
+ // Try to unmarshal as ContentEvent first
+ var contentEvent ContentEvent
+ if json.Unmarshal(event.Data, &contentEvent) == nil {
+ text := contentEvent.Delta
+ if text == "" {
+ text = contentEvent.Content
+ }
+ if text != "" {
+ responseBuffer.WriteString(text)
+ p.streamMu.Lock()
+ p.currentOutput.WriteString(text)
+ p.streamMu.Unlock()
+ p.broadcast(PatrolStreamEvent{Type: "content", Content: text})
+ }
+ } else {
+ // Fallback: try as raw string
+ var text string
+ if json.Unmarshal(event.Data, &text) == nil && text != "" {
+ responseBuffer.WriteString(text)
+ p.streamMu.Lock()
+ p.currentOutput.WriteString(text)
+ p.streamMu.Unlock()
+ p.broadcast(PatrolStreamEvent{Type: "content", Content: text})
+ }
+ }
+ case "thinking":
+ var contentEvent ContentEvent
+ if json.Unmarshal(event.Data, &contentEvent) == nil && contentEvent.Content != "" {
+ p.broadcast(PatrolStreamEvent{Type: "thinking", Content: contentEvent.Content})
+ }
+ case "tool_use", "tool_call":
+ p.broadcast(PatrolStreamEvent{Type: "tool_use", Phase: "Using tools to gather context"})
+ }
+ })
+
+ if err != nil {
+ result.Error = err
+ result.Duration = time.Since(start)
+ p.broadcast(PatrolStreamEvent{Type: "error", Content: err.Error()})
+ log.Error().Err(err).Msg("OpenCode Patrol: Analysis failed")
+ return result, err
+ }
+
+ result.RawResponse = responseBuffer.String()
+ result.Duration = time.Since(start)
+
+ // Parse findings from response
+ findings := p.parseFindings(result.RawResponse)
+ result.Findings = findings
+
+ // Store findings
+ p.mu.RLock()
+ store := p.findingsStore
+ p.mu.RUnlock()
+
+ if store != nil {
+ for _, f := range findings {
+ if store.Add(f) {
+ result.NewFindings++
+ }
+ }
+ } else {
+ result.NewFindings = len(findings)
+ }
+
+ // Save result
+ p.mu.Lock()
+ p.lastRun = time.Now()
+ p.lastResult = result
+ p.mu.Unlock()
+
+ p.broadcast(PatrolStreamEvent{Type: "complete", Phase: "Patrol complete"})
+
+ log.Info().
+ Int("findings", len(findings)).
+ Int("new_findings", result.NewFindings).
+ Dur("duration", result.Duration).
+ Msg("OpenCode Patrol: Analysis complete")
+
+ return result, nil
+}
+
+// buildPatrolPrompt creates the prompt for patrol analysis
+func (p *PatrolService) buildPatrolPrompt() string {
+ return `You are performing a scheduled infrastructure patrol for Pulse, a Proxmox monitoring system.
+
+## Your Task
+Analyze the current infrastructure state and identify issues that require human attention. Use the available MCP tools to gather context.
+
+## Available Tools
+Use these tools to gather information:
+- pulse_get_infrastructure_state: Get current state of all monitored infrastructure
+- pulse_get_metrics_history: Get historical metrics for trend analysis (params: resource_id, period)
+- pulse_get_baselines: Get learned baselines for anomaly detection
+- pulse_get_active_alerts: Get currently active alerts
+- pulse_get_findings: Get existing patrol findings (active and dismissed)
+
+## Steps
+1. First call pulse_get_infrastructure_state to see what's being monitored
+2. Check pulse_get_active_alerts for any ongoing issues
+3. Review pulse_get_findings to see previously identified issues
+4. For any resources that look concerning, use pulse_get_metrics_history for trend analysis
+5. Compare against pulse_get_baselines to identify anomalies
+
+## Output Format
+For each issue found, output in this EXACT format:
+
+[FINDING]
+KEY: <stable-issue-key>
+SEVERITY: critical|warning|watch|info
+CATEGORY: performance|reliability|security|capacity|configuration
+RESOURCE: <resource-name>
+RESOURCE_TYPE: node|vm|container|docker_container|storage|host|kubernetes_cluster
+TITLE: <brief title>
+DESCRIPTION: <detailed description>
+RECOMMENDATION: <actionable recommendation>
+EVIDENCE: <supporting data>
+[/FINDING]
+
+## Severity Guidelines (be conservative)
+- CRITICAL: Service down, data loss imminent, disk >95%, node offline
+- WARNING: Disk >85%, memory >90% sustained, backup failed >48h
+- WATCH: Trends approaching thresholds within 7 days
+- INFO: Minor config issues only
+
+## Thresholds - Only Report If Exceeded
+- CPU: >70% sustained (brief spikes are normal)
+- Memory: >80% sustained (caching is normal)
+- Disk/Storage: >75% OR growing >5%/week toward full
+
+## DO NOT Report
+- Stopped VMs/containers (unless they crashed with autostart enabled)
+- Minor fluctuations from baseline
+- Resources simply "busier than usual" but not near limits
+- Issues that were previously dismissed by the user
+
+If everything is healthy, output NO findings. An empty report is the best report.
+
+Begin your patrol now.`
+}
+
+// parseFindings extracts findings from the AI response
+func (p *PatrolService) parseFindings(response string) []*PatrolFinding {
+ var findings []*PatrolFinding
+
+ // Match [FINDING]...[/FINDING] blocks
+ findingRe := regexp.MustCompile(`(?s)\[FINDING\](.*?)\[/FINDING\]`)
+ matches := findingRe.FindAllStringSubmatch(response, -1)
+
+ for _, match := range matches {
+ if len(match) < 2 {
+ continue
+ }
+ block := match[1]
+
+ finding := p.parseFindingBlock(block)
+ if finding != nil {
+ findings = append(findings, finding)
+ }
+ }
+
+ return findings
+}
+
+// parseFindingBlock parses a single finding block
+func (p *PatrolService) parseFindingBlock(block string) *PatrolFinding {
+ // Extract fields using regex
+ extractField := func(name string) string {
+ re := regexp.MustCompile(`(?i)` + name + `:\s*(.+?)(?:\n|$)`)
+ match := re.FindStringSubmatch(block)
+ if len(match) >= 2 {
+ return strings.TrimSpace(match[1])
+ }
+ return ""
+ }
+
+ key := extractField("KEY")
+ severity := strings.ToLower(extractField("SEVERITY"))
+ category := strings.ToLower(extractField("CATEGORY"))
+ resource := extractField("RESOURCE")
+ resourceType := strings.ToLower(extractField("RESOURCE_TYPE"))
+ title := extractField("TITLE")
+ description := extractField("DESCRIPTION")
+ recommendation := extractField("RECOMMENDATION")
+ evidence := extractField("EVIDENCE")
+
+ // Validate required fields
+ if key == "" || title == "" {
+ return nil
+ }
+
+ // Validate severity
+ validSeverities := map[string]bool{"critical": true, "warning": true, "watch": true, "info": true}
+ if !validSeverities[severity] {
+ severity = "info"
+ }
+
+ // Validate category
+ validCategories := map[string]bool{"performance": true, "reliability": true, "security": true, "capacity": true, "configuration": true}
+ if !validCategories[category] {
+ category = "configuration"
+ }
+
+ // Generate stable ID
+ id := generateFindingID(resource, category, key)
+
+ now := time.Now()
+ return &PatrolFinding{
+ ID: id,
+ Key: key,
+ Severity: severity,
+ Category: category,
+ ResourceID: resource,
+ ResourceName: resource,
+ ResourceType: resourceType,
+ Title: title,
+ Description: description,
+ Recommendation: recommendation,
+ Evidence: evidence,
+ Source: "opencode-patrol",
+ DetectedAt: now,
+ LastSeenAt: now,
+ }
+}
+
+// generateFindingID creates a stable ID for a finding
+func generateFindingID(resourceID, category, key string) string {
+ input := fmt.Sprintf("%s:%s:%s", resourceID, category, key)
+ hash := sha256.Sum256([]byte(input))
+ return fmt.Sprintf("%x", hash[:8])
+}
+
+// CreatePatrolSession creates a dedicated session for patrol with context
+func (p *PatrolService) CreatePatrolSession(ctx context.Context) error {
+ if p.service == nil || !p.service.IsRunning() {
+ return fmt.Errorf("OpenCode service not available")
+ }
+
+ session, err := p.service.CreateSession(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to create patrol session: %w", err)
+ }
+
+ p.mu.Lock()
+ p.sessionID = session.ID
+ p.mu.Unlock()
+
+ log.Info().Str("session_id", session.ID).Msg("OpenCode Patrol: Created dedicated session")
+ return nil
+}
+
+// GetSessionID returns the current patrol session ID
+func (p *PatrolService) GetSessionID() string {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.sessionID
+}
diff --git a/internal/ai/opencode/service.go b/internal/ai/opencode/service.go
new file mode 100644
index 0000000000..c845eb306c
--- /dev/null
+++ b/internal/ai/opencode/service.go
@@ -0,0 +1,526 @@
+package opencode
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/mcp"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "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
+}
+
+// MCP provider type aliases for external use
+type (
+ MCPAlertProvider = mcp.AlertProvider
+ MCPFindingsProvider = mcp.FindingsProvider
+ MCPBaselineProvider = mcp.BaselineProvider
+ MCPPatternProvider = mcp.PatternProvider
+ MCPMetricsHistoryProvider = mcp.MetricsHistoryProvider
+ MCPBackupProvider = mcp.BackupProvider
+ MCPStorageProvider = mcp.StorageProvider
+ MCPDiskHealthProvider = mcp.DiskHealthProvider
+)
+
+// 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)
+}
+
+// StreamCallback is called for each streaming event
+type StreamCallback func(event StreamEvent)
+
+// Service manages OpenCode as Pulse's AI engine
+type Service struct {
+ mu sync.RWMutex
+
+ sidecar *Sidecar
+ client *Client
+ mcpServer *mcp.Server
+ executor *mcp.PulseToolExecutor
+
+ cfg *config.AIConfig
+ started bool
+}
+
+// Config holds OpenCode service configuration
+type Config struct {
+ AIConfig *config.AIConfig
+ StateProvider StateProvider
+ Policy CommandPolicy
+ AgentServer AgentServer
+}
+
+// NewService creates a new OpenCode-powered AI service
+func NewService(cfg Config) *Service {
+ // Create tool executor with adapted interfaces
+ var stateProvider mcp.StateProvider
+ var policy mcp.CommandPolicy
+ var agentServer mcp.AgentServer
+
+ if cfg.StateProvider != nil {
+ stateProvider = &stateProviderAdapter{cfg.StateProvider}
+ }
+ if cfg.Policy != nil {
+ policy = &commandPolicyAdapter{cfg.Policy}
+ }
+ if cfg.AgentServer != nil {
+ agentServer = &agentServerAdapter{cfg.AgentServer}
+ }
+
+ executor := mcp.NewPulseToolExecutor(stateProvider, policy, agentServer)
+
+ return &Service{
+ cfg: cfg.AIConfig,
+ executor: executor,
+ }
+}
+
+// Adapter types to convert between interfaces
+
+type stateProviderAdapter struct {
+ sp StateProvider
+}
+
+func (a *stateProviderAdapter) GetState() models.StateSnapshot {
+ return a.sp.GetState()
+}
+
+type commandPolicyAdapter struct {
+ p CommandPolicy
+}
+
+func (a *commandPolicyAdapter) Evaluate(command string) agentexec.PolicyDecision {
+ return a.p.Evaluate(command)
+}
+
+type agentServerAdapter struct {
+ s AgentServer
+}
+
+func (a *agentServerAdapter) GetConnectedAgents() []agentexec.ConnectedAgent {
+ return a.s.GetConnectedAgents()
+}
+
+func (a *agentServerAdapter) ExecuteCommand(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error) {
+ return a.s.ExecuteCommand(ctx, agentID, cmd)
+}
+
+// Start starts the OpenCode service
+func (s *Service) Start(ctx context.Context) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.started {
+ return nil
+ }
+
+ if s.cfg == nil {
+ return fmt.Errorf("AI config is nil")
+ }
+
+ // Determine data directory
+ dataDir := s.cfg.OpenCodeDataDir
+ if dataDir == "" {
+ dataDir = "/tmp/pulse-opencode"
+ }
+
+ // Find a free port for MCP server
+ mcpPort, err := findFreePort()
+ if err != nil {
+ return fmt.Errorf("failed to find MCP port: %w", err)
+ }
+ mcpAddr := fmt.Sprintf("127.0.0.1:%d", mcpPort)
+
+ // Start MCP server first (OpenCode will connect to it)
+ s.mcpServer = mcp.NewServer(mcpAddr, s.executor)
+ go func() {
+ if err := s.mcpServer.Start(); err != nil {
+ log.Error().Err(err).Msg("MCP server error")
+ }
+ }()
+
+ // Wait for MCP server to start
+ time.Sleep(100 * time.Millisecond)
+
+ // Start OpenCode sidecar with API keys from config
+ sidecarCfg := SidecarConfig{
+ DataDir: dataDir,
+ MCPURL: fmt.Sprintf("http://%s", mcpAddr),
+ Port: s.cfg.OpenCodePort,
+ }
+ // s.cfg is *config.AIConfig directly
+ if s.cfg != nil {
+ sidecarCfg.AnthropicAPIKey = s.cfg.AnthropicAPIKey
+ sidecarCfg.OpenAIAPIKey = s.cfg.OpenAIAPIKey
+ sidecarCfg.DeepSeekAPIKey = s.cfg.DeepSeekAPIKey
+ sidecarCfg.GeminiAPIKey = s.cfg.GeminiAPIKey
+
+ // 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)
+ }
+ }
+ s.sidecar = NewSidecar(sidecarCfg)
+
+ if err := s.sidecar.Start(ctx); err != nil {
+ s.mcpServer.Stop(ctx)
+ return fmt.Errorf("failed to start OpenCode: %w", err)
+ }
+
+ // Create client
+ s.client = NewClient(s.sidecar.BaseURL())
+
+ s.started = true
+ log.Info().
+ Str("opencode_url", s.sidecar.BaseURL()).
+ Str("mcp_addr", mcpAddr).
+ Msg("Pulse AI (OpenCode) started")
+
+ return nil
+}
+
+// Stop stops the OpenCode service
+func (s *Service) Stop(ctx context.Context) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if !s.started {
+ return nil
+ }
+
+ var errs []error
+
+ if s.sidecar != nil {
+ if err := s.sidecar.Stop(); err != nil {
+ errs = append(errs, err)
+ }
+ }
+
+ if s.mcpServer != nil {
+ if err := s.mcpServer.Stop(ctx); err != nil {
+ errs = append(errs, err)
+ }
+ }
+
+ s.started = false
+
+ if len(errs) > 0 {
+ return fmt.Errorf("errors stopping OpenCode: %v", errs)
+ }
+
+ log.Info().Msg("Pulse AI (OpenCode) stopped")
+ return nil
+}
+
+// Restart restarts the OpenCode service with updated configuration
+// Call this when settings change (e.g., model selection)
+func (s *Service) Restart(ctx context.Context, newCfg *config.AIConfig) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if !s.started || s.sidecar == nil {
+ return fmt.Errorf("OpenCode not started")
+ }
+
+ // Use the new config if provided, otherwise fall back to existing
+ cfg := newCfg
+ if cfg == nil {
+ cfg = s.cfg
+ }
+
+ if cfg != nil {
+ // Update stored config
+ s.cfg = cfg
+
+ chatModel := cfg.GetChatModel()
+ if chatModel != "" {
+ // Convert from Pulse format (provider:model) to OpenCode format (provider/model)
+ model := strings.Replace(chatModel, ":", "/", 1)
+ s.sidecar.UpdateModel(model)
+ log.Info().Str("model", model).Msg("Updating OpenCode model")
+ }
+ }
+
+ log.Info().Msg("Restarting OpenCode sidecar with new configuration")
+ return s.sidecar.Restart(ctx)
+}
+
+// IsRunning returns whether the service is running
+func (s *Service) IsRunning() bool {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ if !s.started || s.sidecar == nil {
+ return false
+ }
+
+ return s.sidecar.IsHealthy()
+}
+
+// ExecuteRequest represents a chat request
+type ExecuteRequest struct {
+ Prompt string
+ SessionID string
+ Model string
+}
+
+// Execute sends a prompt and returns the response
+func (s *Service) Execute(ctx context.Context, req ExecuteRequest) (*PromptResponse, error) {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return nil, fmt.Errorf("OpenCode not initialized")
+ }
+
+ return client.Prompt(ctx, PromptRequest{
+ Prompt: req.Prompt,
+ SessionID: req.SessionID,
+ Model: req.Model,
+ })
+}
+
+// ExecuteStream sends a prompt and streams the response
+func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callback StreamCallback) error {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return fmt.Errorf("OpenCode not initialized")
+ }
+
+ // Stream from OpenCode
+ events, errors := client.PromptStream(ctx, PromptRequest{
+ Prompt: req.Prompt,
+ SessionID: req.SessionID,
+ Model: req.Model,
+ })
+
+ // Relay events to callback
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case err := <-errors:
+ if err != nil {
+ errData, _ := json.Marshal(err.Error())
+ callback(StreamEvent{Type: "error", Data: errData})
+ return err
+ }
+ case event, ok := <-events:
+ if !ok {
+ return nil
+ }
+ callback(StreamEvent{
+ Type: event.Type,
+ Data: event.Data,
+ })
+ if event.Type == "done" || event.Type == "error" {
+ return nil
+ }
+ }
+ }
+}
+
+// ListSessions returns all chat sessions
+func (s *Service) ListSessions(ctx context.Context) ([]Session, error) {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return nil, fmt.Errorf("OpenCode not initialized")
+ }
+
+ return client.ListSessions(ctx)
+}
+
+// CreateSession creates a new chat session
+func (s *Service) CreateSession(ctx context.Context) (*Session, error) {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return nil, fmt.Errorf("OpenCode not initialized")
+ }
+
+ return client.CreateSession(ctx)
+}
+
+// DeleteSession deletes a chat session
+func (s *Service) DeleteSession(ctx context.Context, sessionID string) error {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return fmt.Errorf("OpenCode not initialized")
+ }
+
+ return client.DeleteSession(ctx, sessionID)
+}
+
+// GetMessages returns messages from a session
+func (s *Service) GetMessages(ctx context.Context, sessionID string) ([]Message, error) {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return nil, fmt.Errorf("OpenCode not initialized")
+ }
+
+ return client.GetMessages(ctx, sessionID)
+}
+
+// AbortSession aborts the current operation
+func (s *Service) AbortSession(ctx context.Context, sessionID string) error {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return fmt.Errorf("OpenCode not initialized")
+ }
+
+ return client.AbortSession(ctx, sessionID)
+}
+
+// GetClient returns the underlying OpenCode client for direct access
+func (s *Service) GetClient() *Client {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.client
+}
+
+// GetBaseURL returns the OpenCode server base URL for proxying
+func (s *Service) GetBaseURL() string {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s.sidecar == nil {
+ return ""
+ }
+ return s.sidecar.BaseURL()
+}
+
+// SetMetadataUpdater sets the metadata updater for resource URL updates
+func (s *Service) SetMetadataUpdater(updater mcp.MetadataUpdater) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.executor != nil {
+ s.executor.SetMetadataUpdater(updater)
+ }
+}
+
+// SetFindingsManager sets the findings manager for patrol integration
+func (s *Service) SetFindingsManager(manager mcp.FindingsManager) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.executor != nil {
+ s.executor.SetFindingsManager(manager)
+ }
+}
+
+// SetAlertProvider sets the alert provider for active alerts access
+func (s *Service) SetAlertProvider(provider mcp.AlertProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.executor != nil {
+ s.executor.SetAlertProvider(provider)
+ }
+}
+
+// SetFindingsProvider sets the findings provider for patrol findings access
+func (s *Service) SetFindingsProvider(provider mcp.FindingsProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.executor != nil {
+ s.executor.SetFindingsProvider(provider)
+ }
+}
+
+// SetBaselineProvider sets the baseline provider for anomaly detection
+func (s *Service) SetBaselineProvider(provider mcp.BaselineProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.executor != nil {
+ s.executor.SetBaselineProvider(provider)
+ }
+}
+
+// SetPatternProvider sets the pattern provider for trend analysis
+func (s *Service) SetPatternProvider(provider mcp.PatternProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.executor != nil {
+ s.executor.SetPatternProvider(provider)
+ }
+}
+
+// SetMetricsHistory sets the metrics history provider for historical data
+func (s *Service) SetMetricsHistory(provider mcp.MetricsHistoryProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.executor != nil {
+ s.executor.SetMetricsHistory(provider)
+ }
+}
+
+// SetBackupProvider sets the backup provider for backup status access
+func (s *Service) SetBackupProvider(provider mcp.BackupProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.executor != nil {
+ s.executor.SetBackupProvider(provider)
+ }
+}
+
+// SetStorageProvider sets the storage provider for storage pool information
+func (s *Service) SetStorageProvider(provider mcp.StorageProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.executor != nil {
+ s.executor.SetStorageProvider(provider)
+ }
+}
+
+// SetDiskHealthProvider sets the disk health provider for SMART/RAID data
+func (s *Service) SetDiskHealthProvider(provider mcp.DiskHealthProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.executor != nil {
+ s.executor.SetDiskHealthProvider(provider)
+ }
+}
diff --git a/internal/ai/opencode/sidecar.go b/internal/ai/opencode/sidecar.go
new file mode 100644
index 0000000000..ac920194ef
--- /dev/null
+++ b/internal/ai/opencode/sidecar.go
@@ -0,0 +1,417 @@
+package opencode
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "os"
+ "os/exec"
+ "sync"
+ "time"
+
+ "github.com/rs/zerolog/log"
+)
+
+// Sidecar manages the OpenCode server process
+type Sidecar struct {
+ mu sync.RWMutex
+
+ cmd *exec.Cmd
+ port int
+ baseURL string
+ dataDir string
+ mcpURL string // URL of Pulse's MCP server for OpenCode to connect to
+ model string // Model to use (format: provider/model-name)
+ cancelCtx context.CancelFunc
+
+ // API keys for AI providers
+ anthropicAPIKey string
+ openAIAPIKey string
+ deepSeekAPIKey string
+ geminiAPIKey string
+
+ started bool
+ healthy bool
+ lastCheck time.Time
+}
+
+// SidecarConfig contains configuration for the OpenCode sidecar
+type SidecarConfig struct {
+ // DataDir is where OpenCode stores its data
+ DataDir string
+ // MCPURL is the URL of Pulse's MCP server
+ MCPURL string
+ // Port to run OpenCode on (0 for auto-assign)
+ Port int
+ // Model to use (format: provider/model-name, e.g. "anthropic/claude-sonnet-4-5")
+ Model string
+ // API keys for AI providers
+ AnthropicAPIKey string
+ OpenAIAPIKey string
+ DeepSeekAPIKey string
+ GeminiAPIKey string
+}
+
+// NewSidecar creates a new OpenCode sidecar manager
+func NewSidecar(cfg SidecarConfig) *Sidecar {
+ return &Sidecar{
+ dataDir: cfg.DataDir,
+ mcpURL: cfg.MCPURL,
+ port: cfg.Port,
+ model: cfg.Model,
+ anthropicAPIKey: cfg.AnthropicAPIKey,
+ openAIAPIKey: cfg.OpenAIAPIKey,
+ deepSeekAPIKey: cfg.DeepSeekAPIKey,
+ geminiAPIKey: cfg.GeminiAPIKey,
+ }
+}
+
+// Start launches the OpenCode server process
+func (s *Sidecar) Start(ctx context.Context) error {
+ // Acquire lock for initial setup
+ s.mu.Lock()
+ if s.started {
+ s.mu.Unlock()
+ return nil
+ }
+
+ // Find a free port if not specified
+ if s.port == 0 {
+ port, err := findFreePort()
+ if err != nil {
+ s.mu.Unlock()
+ return fmt.Errorf("failed to find free port: %w", err)
+ }
+ s.port = port
+ }
+
+ s.baseURL = fmt.Sprintf("http://127.0.0.1:%d", s.port)
+
+ // Ensure data directory exists
+ if s.dataDir != "" {
+ if err := os.MkdirAll(s.dataDir, 0755); err != nil {
+ s.mu.Unlock()
+ return fmt.Errorf("failed to create data directory: %w", err)
+ }
+ }
+
+ // Create OpenCode config with MCP server connection and model
+ if s.dataDir != "" {
+ configPath := s.dataDir + "/opencode.json"
+
+ // Build config with optional model
+ modelLine := ""
+ if s.model != "" {
+ modelLine = fmt.Sprintf(` "model": "%s",
+`, s.model)
+ }
+
+ mcpConfig := ""
+ if s.mcpURL != "" {
+ mcpConfig = fmt.Sprintf(` "mcp": {
+ "pulse": {
+ "type": "remote",
+ "url": "%s",
+ "enabled": true
+ }
+ }`, s.mcpURL)
+ }
+
+ // Note: API keys are passed via environment variables (not in config file)
+ // OpenCode reads them from ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.
+ providerConfig := ""
+
+ config := fmt.Sprintf(`{
+ "$schema": "https://opencode.ai/config.json",
+%s%s%s
+}`, modelLine, providerConfig, mcpConfig)
+
+ if err := os.WriteFile(configPath, []byte(config), 0644); err != nil {
+ log.Warn().Err(err).Msg("Failed to write OpenCode config")
+ } else {
+ log.Info().Str("config", configPath).Str("model", s.model).Str("mcpURL", s.mcpURL).Msg("Created OpenCode config")
+ }
+ }
+
+ // Create a cancellable context for the process
+ processCtx, cancel := context.WithCancel(ctx)
+ s.cancelCtx = cancel
+
+ // Build command - using npx to run opencode
+ s.cmd = exec.CommandContext(processCtx,
+ "npx", "-y", "opencode-ai@latest",
+ "serve",
+ "--port", fmt.Sprintf("%d", s.port),
+ "--hostname", "127.0.0.1",
+ )
+
+ // Set working directory
+ if s.dataDir != "" {
+ s.cmd.Dir = s.dataDir
+ }
+
+ // Configure environment with API keys
+ env := append(os.Environ(),
+ fmt.Sprintf("OPENCODE_PORT=%d", s.port),
+ )
+ if s.anthropicAPIKey != "" {
+ env = append(env, fmt.Sprintf("ANTHROPIC_API_KEY=%s", s.anthropicAPIKey))
+ }
+ if s.openAIAPIKey != "" {
+ env = append(env, fmt.Sprintf("OPENAI_API_KEY=%s", s.openAIAPIKey))
+ }
+ if s.deepSeekAPIKey != "" {
+ env = append(env, fmt.Sprintf("DEEPSEEK_API_KEY=%s", s.deepSeekAPIKey))
+ }
+ if s.geminiAPIKey != "" {
+ env = append(env, fmt.Sprintf("GEMINI_API_KEY=%s", s.geminiAPIKey))
+ // OpenCode also accepts GOOGLE_GENERATIVE_AI_API_KEY - set both to ensure compatibility
+ env = append(env, fmt.Sprintf("GOOGLE_GENERATIVE_AI_API_KEY=%s", s.geminiAPIKey))
+ }
+ s.cmd.Env = env
+
+ // Capture output for debugging
+ s.cmd.Stdout = &logWriter{prefix: "opencode", level: "info"}
+ s.cmd.Stderr = &logWriter{prefix: "opencode", level: "error"}
+
+ // Start the process
+ if err := s.cmd.Start(); err != nil {
+ s.mu.Unlock()
+ return fmt.Errorf("failed to start opencode: %w", err)
+ }
+
+ s.started = true
+
+ // Release lock before waitForReady (which also needs the lock)
+ s.mu.Unlock()
+
+ // Start health check goroutine
+ go s.healthLoop(ctx)
+
+ // Wait for server to be ready
+ if err := s.waitForReady(ctx, 30*time.Second); err != nil {
+ log.Error().Err(err).Msg("waitForReady failed")
+ s.Stop()
+ return fmt.Errorf("opencode failed to become ready: %w", err)
+ }
+
+ log.Info().
+ Int("port", s.port).
+ Str("url", s.baseURL).
+ Msg("OpenCode sidecar started")
+
+ return nil
+}
+
+// Stop shuts down the OpenCode server process
+func (s *Sidecar) Stop() error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if !s.started {
+ return nil
+ }
+
+ if s.cancelCtx != nil {
+ s.cancelCtx()
+ }
+
+ if s.cmd != nil && s.cmd.Process != nil {
+ // Give it a chance to shut down gracefully
+ done := make(chan error, 1)
+ go func() {
+ done <- s.cmd.Wait()
+ }()
+
+ select {
+ case <-done:
+ // Process exited
+ case <-time.After(5 * time.Second):
+ // Force kill
+ _ = s.cmd.Process.Kill()
+ }
+ }
+
+ s.started = false
+ s.healthy = false
+ log.Info().Msg("OpenCode sidecar stopped")
+
+ return nil
+}
+
+// UpdateModel updates the model configuration
+// Call this before Restart to use a new model
+func (s *Sidecar) UpdateModel(model string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.model = model
+}
+
+// writeConfig writes the opencode.json config file
+// This is called during Start and can be called separately for config updates
+func (s *Sidecar) writeConfig() error {
+ if s.dataDir == "" {
+ return nil
+ }
+
+ configPath := s.dataDir + "/opencode.json"
+
+ // Build config with optional model
+ modelLine := ""
+ if s.model != "" {
+ modelLine = fmt.Sprintf(` "model": "%s",
+`, s.model)
+ }
+
+ mcpConfig := ""
+ if s.mcpURL != "" {
+ mcpConfig = fmt.Sprintf(` "mcp": {
+ "pulse": {
+ "type": "remote",
+ "url": "%s",
+ "enabled": true
+ }
+ }`, s.mcpURL)
+ }
+
+ config := fmt.Sprintf(`{
+ "$schema": "https://opencode.ai/config.json",
+%s%s
+}`, modelLine, mcpConfig)
+
+ if err := os.WriteFile(configPath, []byte(config), 0644); err != nil {
+ return fmt.Errorf("failed to write OpenCode config: %w", err)
+ }
+
+ log.Info().Str("config", configPath).Str("model", s.model).Msg("Updated OpenCode config")
+ return nil
+}
+
+// Restart stops and starts the sidecar
+func (s *Sidecar) Restart(ctx context.Context) error {
+ if err := s.Stop(); err != nil {
+ log.Warn().Err(err).Msg("Error stopping sidecar during restart")
+ }
+ return s.Start(ctx)
+}
+
+// BaseURL returns the base URL of the OpenCode server
+func (s *Sidecar) BaseURL() string {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.baseURL
+}
+
+// Port returns the port the OpenCode server is running on
+func (s *Sidecar) Port() int {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.port
+}
+
+// IsHealthy returns whether the sidecar is healthy
+func (s *Sidecar) IsHealthy() bool {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.healthy
+}
+
+// IsStarted returns whether the sidecar has been started
+func (s *Sidecar) IsStarted() bool {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.started
+}
+
+// waitForReady polls the health endpoint until the server is ready
+func (s *Sidecar) waitForReady(ctx context.Context, timeout time.Duration) error {
+ deadline := time.Now().Add(timeout)
+
+ for time.Now().Before(deadline) {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ }
+
+ if s.checkHealth() {
+ s.mu.Lock()
+ s.healthy = true
+ s.mu.Unlock()
+ return nil
+ }
+
+ time.Sleep(500 * time.Millisecond)
+ }
+
+ return fmt.Errorf("timeout waiting for opencode to be ready")
+}
+
+// checkHealth performs a health check against the OpenCode server
+func (s *Sidecar) checkHealth() bool {
+ client := newHTTPClient(5 * time.Second)
+ resp, err := client.Get(s.baseURL + "/global/health")
+ if err != nil {
+ return false
+ }
+ defer resp.Body.Close()
+
+ return resp.StatusCode == 200
+}
+
+// healthLoop continuously monitors the sidecar health
+func (s *Sidecar) healthLoop(ctx context.Context) {
+ ticker := time.NewTicker(30 * time.Second)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ healthy := s.checkHealth()
+
+ s.mu.Lock()
+ wasHealthy := s.healthy
+ s.healthy = healthy
+ s.lastCheck = time.Now()
+ s.mu.Unlock()
+
+ if wasHealthy && !healthy {
+ log.Warn().Msg("OpenCode sidecar became unhealthy, attempting restart")
+ if err := s.Restart(ctx); err != nil {
+ log.Error().Err(err).Msg("Failed to restart OpenCode sidecar")
+ }
+ }
+ }
+ }
+}
+
+// findFreePort finds an available TCP port
+func findFreePort() (int, error) {
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ return 0, err
+ }
+ defer listener.Close()
+
+ addr := listener.Addr().(*net.TCPAddr)
+ return addr.Port, nil
+}
+
+// logWriter writes process output to zerolog
+type logWriter struct {
+ prefix string
+ level string
+}
+
+func (w *logWriter) Write(p []byte) (n int, err error) {
+ msg := string(p)
+ switch w.level {
+ case "error":
+ log.Error().Str("source", w.prefix).Msg(msg)
+ default:
+ log.Debug().Str("source", w.prefix).Msg(msg)
+ }
+ return len(p), nil
+}
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
new file mode 100644
index 0000000000..8d02024390
--- /dev/null
+++ b/internal/api/ai_handler.go
@@ -0,0 +1,432 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httputil"
+ "net/url"
+ "strings"
+ "sync/atomic"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "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"
+ "github.com/rs/zerolog/log"
+)
+
+// AIHandler handles all AI endpoints using OpenCode
+type AIHandler struct {
+ config *config.Config
+ persistence *config.ConfigPersistence
+ service *opencode.Service
+ agentServer *agentexec.Server
+}
+
+// NewAIHandler creates a new AI handler
+func NewAIHandler(cfg *config.Config, persistence *config.ConfigPersistence, agentServer *agentexec.Server) *AIHandler {
+ return &AIHandler{
+ config: cfg,
+ persistence: persistence,
+ agentServer: agentServer,
+ }
+}
+
+// StateProvider interface for infrastructure state
+type AIStateProvider interface {
+ GetState() models.StateSnapshot
+}
+
+// Start initializes and starts the OpenCode service
+func (h *AIHandler) Start(ctx context.Context, stateProvider AIStateProvider) error {
+ aiCfg := h.loadAIConfig()
+ if aiCfg == nil || !aiCfg.Enabled {
+ log.Info().Msg("AI is disabled")
+ return nil
+ }
+
+ h.service = opencode.NewService(opencode.Config{
+ AIConfig: aiCfg,
+ StateProvider: stateProvider,
+ AgentServer: h.agentServer,
+ })
+
+ if err := h.service.Start(ctx); err != nil {
+ return err
+ }
+
+ log.Info().Msg("Pulse AI started (powered by OpenCode)")
+ return nil
+}
+
+// Stop stops the OpenCode service
+func (h *AIHandler) Stop(ctx context.Context) error {
+ if h.service != nil {
+ return h.service.Stop(ctx)
+ }
+ return nil
+}
+
+// Restart restarts the OpenCode service with updated configuration
+// Call this when model or other settings change
+func (h *AIHandler) Restart(ctx context.Context) error {
+ if h.service == nil || !h.service.IsRunning() {
+ return nil // Not running, nothing to restart
+ }
+ // Load fresh config from persistence to get latest settings
+ newCfg := h.loadAIConfig()
+ return h.service.Restart(ctx, newCfg)
+}
+
+// IsRunning returns whether AI is running
+func (h *AIHandler) IsRunning() bool {
+ return h.service != nil && h.service.IsRunning()
+}
+
+// GetService returns the underlying OpenCode service for direct access
+func (h *AIHandler) GetService() *opencode.Service {
+ return h.service
+}
+
+// GetAIConfig returns the current AI configuration
+func (h *AIHandler) GetAIConfig() *config.AIConfig {
+ return h.loadAIConfig()
+}
+
+func (h *AIHandler) loadAIConfig() *config.AIConfig {
+ if h.persistence == nil {
+ return nil
+ }
+ cfg, err := h.persistence.LoadAIConfig()
+ if err != nil {
+ log.Warn().Err(err).Msg("Failed to load AI config")
+ return nil
+ }
+ return cfg
+}
+
+// ChatRequest represents a chat request
+type ChatRequest struct {
+ Prompt string `json:"prompt"`
+ SessionID string `json:"session_id,omitempty"`
+ Model string `json:"model,omitempty"`
+}
+
+// HandleChat handles POST /api/ai/chat - streaming chat
+func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
+ // CORS
+ origin := r.Header.Get("Origin")
+ if origin != "" {
+ w.Header().Set("Access-Control-Allow-Origin", origin)
+ w.Header().Set("Access-Control-Allow-Credentials", "true")
+ w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
+ w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Accept, Cookie")
+ w.Header().Set("Vary", "Origin")
+ }
+
+ if r.Method == http.MethodOptions {
+ w.WriteHeader(http.StatusOK)
+ return
+ }
+
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ // Auth already handled by RequireAuth wrapper - no need to check again
+
+ if !h.IsRunning() {
+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)
+ return
+ }
+
+ // Parse request
+ var req ChatRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ http.Error(w, "Invalid request", http.StatusBadRequest)
+ return
+ }
+
+ // Set up SSE
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-cache")
+ w.Header().Set("Connection", "keep-alive")
+ w.Header().Set("X-Accel-Buffering", "no")
+ w.Header().Set("Transfer-Encoding", "identity")
+
+ flusher, ok := w.(http.Flusher)
+ if !ok {
+ http.Error(w, "Streaming not supported", http.StatusInternalServerError)
+ return
+ }
+
+ // Disable timeouts
+ rc := http.NewResponseController(w)
+ _ = rc.SetWriteDeadline(time.Time{})
+ _ = rc.SetReadDeadline(time.Time{})
+
+ flusher.Flush()
+
+ // Context with timeout
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
+ defer cancel()
+
+ // Heartbeat
+ heartbeatDone := make(chan struct{})
+ var clientDisconnected atomic.Bool
+
+ go func() {
+ ticker := time.NewTicker(5 * time.Second)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ _ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))
+ _, err := w.Write([]byte(": heartbeat\n\n"))
+ if err != nil {
+ clientDisconnected.Store(true)
+ return
+ }
+ flusher.Flush()
+ case <-heartbeatDone:
+ return
+ }
+ }
+ }()
+ defer close(heartbeatDone)
+
+ // Write helper
+ writeEvent := func(event opencode.StreamEvent) {
+ if clientDisconnected.Load() {
+ return
+ }
+ data, err := json.Marshal(event)
+ if err != nil {
+ return
+ }
+ _ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))
+ _, err = w.Write([]byte("data: " + string(data) + "\n\n"))
+ if err != nil {
+ clientDisconnected.Store(true)
+ return
+ }
+ flusher.Flush()
+ }
+
+ // Stream from OpenCode
+ err := h.service.ExecuteStream(ctx, opencode.ExecuteRequest{
+ Prompt: req.Prompt,
+ SessionID: req.SessionID,
+ Model: req.Model,
+ }, func(event opencode.StreamEvent) {
+ writeEvent(event)
+ })
+
+ if err != nil {
+ log.Error().Err(err).Msg("Chat stream error")
+ errData, _ := json.Marshal(err.Error())
+ writeEvent(opencode.StreamEvent{Type: "error", Data: errData})
+ }
+
+ // Send done
+ writeEvent(opencode.StreamEvent{Type: "done", Data: nil})
+}
+
+// HandleSessions handles GET /api/ai/sessions - list sessions
+func (h *AIHandler) HandleSessions(w http.ResponseWriter, r *http.Request) {
+ if !CheckAuth(h.config, w, r) {
+ return
+ }
+
+ if !h.IsRunning() {
+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)
+ return
+ }
+
+ sessions, err := h.service.ListSessions(r.Context())
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(sessions)
+}
+
+// HandleCreateSession handles POST /api/ai/sessions - create session
+func (h *AIHandler) HandleCreateSession(w http.ResponseWriter, r *http.Request) {
+ if !CheckAuth(h.config, w, r) {
+ return
+ }
+
+ if !h.IsRunning() {
+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)
+ return
+ }
+
+ session, err := h.service.CreateSession(r.Context())
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(session)
+}
+
+// HandleDeleteSession handles DELETE /api/ai/sessions/{id}
+func (h *AIHandler) HandleDeleteSession(w http.ResponseWriter, r *http.Request, sessionID string) {
+ if !CheckAuth(h.config, w, r) {
+ return
+ }
+
+ if !h.IsRunning() {
+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)
+ return
+ }
+
+ if err := h.service.DeleteSession(r.Context(), sessionID); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// HandleMessages handles GET /api/ai/sessions/{id}/messages
+func (h *AIHandler) HandleMessages(w http.ResponseWriter, r *http.Request, sessionID string) {
+ if !CheckAuth(h.config, w, r) {
+ return
+ }
+
+ if !h.IsRunning() {
+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)
+ return
+ }
+
+ messages, err := h.service.GetMessages(r.Context(), sessionID)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(messages)
+}
+
+// HandleAbort handles POST /api/ai/sessions/{id}/abort
+func (h *AIHandler) HandleAbort(w http.ResponseWriter, r *http.Request, sessionID string) {
+ if !CheckAuth(h.config, w, r) {
+ return
+ }
+
+ if !h.IsRunning() {
+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)
+ return
+ }
+
+ if err := h.service.AbortSession(r.Context(), sessionID); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ w.WriteHeader(http.StatusOK)
+}
+
+// HandleStatus handles GET /api/ai/status
+func (h *AIHandler) HandleStatus(w http.ResponseWriter, r *http.Request) {
+ if !CheckAuth(h.config, w, r) {
+ return
+ }
+
+ status := map[string]interface{}{
+ "running": h.IsRunning(),
+ "engine": "opencode",
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(status)
+}
+
+// SetAlertProvider sets the alert provider for MCP tools
+func (h *AIHandler) SetAlertProvider(provider opencode.MCPAlertProvider) {
+ if h.service != nil {
+ h.service.SetAlertProvider(provider)
+ }
+}
+
+// SetFindingsProvider sets the findings provider for MCP tools
+func (h *AIHandler) SetFindingsProvider(provider opencode.MCPFindingsProvider) {
+ if h.service != nil {
+ h.service.SetFindingsProvider(provider)
+ }
+}
+
+// SetBaselineProvider sets the baseline provider for MCP tools
+func (h *AIHandler) SetBaselineProvider(provider opencode.MCPBaselineProvider) {
+ if h.service != nil {
+ h.service.SetBaselineProvider(provider)
+ }
+}
+
+// SetPatternProvider sets the pattern provider for MCP tools
+func (h *AIHandler) SetPatternProvider(provider opencode.MCPPatternProvider) {
+ if h.service != nil {
+ h.service.SetPatternProvider(provider)
+ }
+}
+
+// SetMetricsHistory sets the metrics history provider for MCP tools
+func (h *AIHandler) SetMetricsHistory(provider opencode.MCPMetricsHistoryProvider) {
+ if h.service != nil {
+ h.service.SetMetricsHistory(provider)
+ }
+}
+
+// HandleOpenCodeUI proxies requests to OpenCode's built-in web UI
+// This allows Pulse to embed OpenCode's UI while maintaining auth
+func (h *AIHandler) HandleOpenCodeUI(w http.ResponseWriter, r *http.Request) {
+ if !h.IsRunning() {
+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)
+ return
+ }
+
+ baseURL := h.service.GetBaseURL()
+ if baseURL == "" {
+ http.Error(w, "OpenCode URL not available", http.StatusServiceUnavailable)
+ return
+ }
+
+ target, err := url.Parse(baseURL)
+ if err != nil {
+ http.Error(w, "Invalid OpenCode URL", http.StatusInternalServerError)
+ return
+ }
+
+ // Create reverse proxy
+ proxy := httputil.NewSingleHostReverseProxy(target)
+
+ // Customize the director to rewrite the path
+ originalDirector := proxy.Director
+ proxy.Director = func(req *http.Request) {
+ originalDirector(req)
+ // Strip the /opencode prefix from the path
+ req.URL.Path = strings.TrimPrefix(req.URL.Path, "/opencode")
+ if req.URL.Path == "" {
+ req.URL.Path = "/"
+ }
+ req.Host = target.Host
+ }
+
+ // Handle WebSocket upgrades
+ if r.Header.Get("Upgrade") == "websocket" {
+ proxy.ServeHTTP(w, r)
+ return
+ }
+
+ // Serve the proxied request
+ proxy.ServeHTTP(w, r)
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index 8055165bc6..2646a5905a 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -1401,6 +1401,14 @@ func (r *Router) setupRoutes() {
}))
r.mux.HandleFunc("/api/ai/sessions/", RequireAuth(r.config, r.routeOpenCodeSessions))
+ // OpenCode Web UI proxy - serves OpenCode's built-in web interface
+ // This allows users to access OpenCode directly through Pulse with auth
+ r.mux.HandleFunc("/opencode/", RequireAuth(r.config, r.aiHandler.HandleOpenCodeUI))
+ r.mux.HandleFunc("/opencode", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {
+ // Redirect /opencode to /opencode/ for proper asset loading
+ http.Redirect(w, req, "/opencode/", http.StatusMovedPermanently)
+ }))
+
// Agent WebSocket for AI command execution
r.mux.HandleFunc("/api/agent/ws", r.handleAgentWebSocket)
@@ -2416,6 +2424,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
strings.HasPrefix(req.URL.Path, "/ws") ||
strings.HasPrefix(req.URL.Path, "/socket.io/") ||
strings.HasPrefix(req.URL.Path, "/download/") ||
+ strings.HasPrefix(req.URL.Path, "/opencode") ||
req.URL.Path == "/simple-stats" ||
req.URL.Path == "/install-docker-agent.sh" ||
req.URL.Path == "/install-container-agent.sh" ||