import crypto from 'node:crypto'; import { z } from 'zod'; import { AlertsFileSchema, ServerConfigSchema, SettingsSchema, SnippetSchema, SnippetsFileSchema, SystemConfigSchema, WorkflowConfigSchema, } from '../../shared/schemas/index.js'; import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js'; import type { WsHub } from '../api/ws-hub.js'; import type { ConfigManager } from '../config/config-manager.js'; import { computeLineDiff, type DiffLine } from '../config/diff.js'; import type { AuditService } from '../security/audit.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import { buildSurfaceGuideAndInventory, type AiDraftKind, type AiSurface, } from './guides.js'; import { collectVaultSecretStrings, redactSecrets } from './redactor.js'; export class AiDisabledError extends Error { readonly code = 'AI_DISABLED'; readonly status = 403; constructor() { super('AI Assistant is disabled in settings.json (settings.ai.enabled=false).'); } } export interface ChatMessageInput { role: 'user' | 'assistant'; content: string; } interface ActiveAiChat { chatId: string; abortController: AbortController; frames: ServerWsFrame[]; replayBytes: number; done: boolean; } const MAX_REPLAY_BYTES = 128 * 1024; const MAX_RETAINED_CHATS = 25; export function normalizeChatCompletionsUrl(baseUrl: string): string { const trimmed = baseUrl.trim().replace(/\/+$/, ''); if (trimmed.endsWith('/chat/completions')) return trimmed; if (trimmed.endsWith('/v1')) return `${trimmed}/chat/completions`; return `${trimmed}/v1/chat/completions`; } export class AiService { private readonly chats = new Map(); private closed = false; constructor( private readonly configManager: ConfigManager, private readonly vaultService: VaultService, private readonly sshPool: SSHPool, private readonly wsHub: WsHub, private readonly auditService: AuditService, ) {} getReplayFrames(chatId: string): ServerWsFrame[] { return [...(this.chats.get(chatId)?.frames ?? [])]; } cancelChat(chatId: string): boolean { const chat = this.chats.get(chatId); if (!chat || chat.done) return false; chat.abortController.abort(); return true; } cancelAll(): void { for (const chat of this.chats.values()) { if (!chat.done) { chat.abortController.abort(); } } } close(): void { this.closed = true; this.cancelAll(); } private resolveBearerToken(secretRef?: string): string | undefined { if (!secretRef || !this.vaultService.isRuntimeReady) return undefined; const cred = this.vaultService.getRuntimeSecret(secretRef); if (!cred) return undefined; if (cred.type === 'api-token') return cred.token; if (cred.type === 'webhook-secret') return cred.secret; if (cred.type === 'ssh-password' || cred.type === 'sudo-password') return cred.password; return undefined; } previewContext(opts: { surface: AiSurface; contextText?: string; serverId?: string; targetPath?: string; }): { enabled: boolean; baseUrl: string; model: string; surface: AiSurface; defaultDraftKind?: AiDraftKind; systemPrompt: string; inventorySummary: string; sanitizedContext: string; redactedCount: number; truncated: boolean; } { const aiCfg = this.configManager.getSettings().ai; const knownSecrets = collectVaultSecretStrings(this.vaultService); const guide = buildSurfaceGuideAndInventory( opts.surface, { configManager: this.configManager, vaultService: this.vaultService, sshPool: this.sshPool, }, { serverId: opts.serverId, targetPath: opts.targetPath }, ); const ctxRedacted = redactSecrets( opts.contextText ?? '', knownSecrets, aiCfg.maxContextChars, ); const invRedacted = redactSecrets(guide.inventorySummary, knownSecrets, 12_000); return { enabled: aiCfg.enabled, baseUrl: aiCfg.baseUrl, model: aiCfg.model, surface: opts.surface, defaultDraftKind: guide.defaultDraftKind, systemPrompt: guide.systemPrompt, inventorySummary: invRedacted.text, sanitizedContext: ctxRedacted.text, redactedCount: ctxRedacted.redactedCount + invRedacted.redactedCount, truncated: ctxRedacted.truncated || invRedacted.truncated, }; } startChat(opts: { chatId?: string; surface: AiSurface; messages: ChatMessageInput[]; contextText?: string; serverId?: string; targetPath?: string; actorIp: string; sessionIdHash: string | null; }): { chatId: string; redactedCount: number; truncated: boolean } { if (this.closed) { throw new Error('AiService is closed'); } const aiCfg = this.configManager.getSettings().ai; if (!aiCfg.enabled) { throw new AiDisabledError(); } const knownSecrets = collectVaultSecretStrings(this.vaultService); const guide = buildSurfaceGuideAndInventory( opts.surface, { configManager: this.configManager, vaultService: this.vaultService, sshPool: this.sshPool, }, { serverId: opts.serverId, targetPath: opts.targetPath }, ); let totalRedacted = 0; let anyTruncated = false; const invRedacted = redactSecrets(guide.inventorySummary, knownSecrets, 12_000); totalRedacted += invRedacted.redactedCount; if (invRedacted.truncated) anyTruncated = true; const ctxRedacted = redactSecrets( opts.contextText ?? '', knownSecrets, aiCfg.maxContextChars, ); totalRedacted += ctxRedacted.redactedCount; if (ctxRedacted.truncated) anyTruncated = true; const sanitizedMessages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }> = [ { role: 'system', content: [ guide.systemPrompt, '', 'SANITIZED HUB INVENTORY:', invRedacted.text, ...(ctxRedacted.text.trim() ? ['', 'ATTACHED SANITIZED CONTEXT:', ctxRedacted.text] : []), ].join('\n'), }, ]; for (const msg of opts.messages) { const mRedacted = redactSecrets(msg.content, knownSecrets, aiCfg.maxContextChars); totalRedacted += mRedacted.redactedCount; if (mRedacted.truncated) anyTruncated = true; sanitizedMessages.push({ role: msg.role, content: mRedacted.text }); } const chatId = opts.chatId?.trim() || `chat-${crypto.randomBytes(6).toString('hex')}`; const abortController = new AbortController(); const state: ActiveAiChat = { chatId, abortController, frames: [], replayBytes: 0, done: false, }; this.chats.set(chatId, state); this.auditService.log({ action: 'ai.chat', actorIp: opts.actorIp, sessionIdHash: opts.sessionIdHash, target: opts.surface, status: 'ok', details: { chatId, model: aiCfg.model, redactedCount: totalRedacted, }, }); const endpointUrl = normalizeChatCompletionsUrl(aiCfg.baseUrl); const bearer = this.resolveBearerToken(aiCfg.secretRef); void this.runStreamingRequest(state, endpointUrl, aiCfg.model, sanitizedMessages, bearer); return { chatId, redactedCount: totalRedacted, truncated: anyTruncated, }; } private emitDelta( chat: ActiveAiChat, frame: { chunk: string; done?: boolean; error?: string }, ): void { const fullFrame: ServerWsFrame = { type: 'ai:delta', chatId: chat.chatId, chunk: frame.chunk, ...(frame.done ? { done: true } : {}), ...(frame.error ? { error: frame.error } : {}), }; const bytes = Buffer.byteLength(JSON.stringify(fullFrame), 'utf8'); chat.frames.push(fullFrame); chat.replayBytes += bytes; while (chat.replayBytes > MAX_REPLAY_BYTES && chat.frames.length > 0) { const dropped = chat.frames.shift()!; chat.replayBytes -= Buffer.byteLength(JSON.stringify(dropped), 'utf8'); } this.wsHub.broadcastChannel(WS_CHANNELS.ai(chat.chatId), fullFrame); } private async runStreamingRequest( chat: ActiveAiChat, endpointUrl: string, model: string, messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>, bearerToken?: string, ): Promise { try { const headers: Record = { 'Content-Type': 'application/json', Accept: 'text/event-stream, application/json', }; if (bearerToken) { headers.Authorization = `Bearer ${bearerToken}`; } const res = await fetch(endpointUrl, { method: 'POST', headers, body: JSON.stringify({ model, stream: true, messages }), signal: chat.abortController.signal, }); if (!res.ok) { const errBody = await res.text().catch(() => ''); this.emitDelta(chat, { chunk: '', done: true, error: `LLM endpoint HTTP ${res.status}${errBody ? `: ${errBody.slice(0, 240)}` : ''}`, }); return; } const contentType = res.headers.get('content-type') ?? ''; if (!contentType.includes('text/event-stream') || !res.body) { const jsonData = (await res.json().catch(() => ({}))) as { choices?: Array<{ message?: { content?: string }; text?: string }>; }; const content = jsonData.choices?.[0]?.message?.content ?? jsonData.choices?.[0]?.text ?? ''; if (content) { this.emitDelta(chat, { chunk: content }); } this.emitDelta(chat, { chunk: '', done: true }); return; } const reader = res.body.getReader(); const decoder = new TextDecoder(); let buf = ''; let doneSent = false; while (true) { const { value, done } = await reader.read(); if (done) break; buf += decoder.decode(value, { stream: true }); let nlIdx: number; while ((nlIdx = buf.indexOf('\n')) >= 0) { const line = buf.slice(0, nlIdx).trim(); buf = buf.slice(nlIdx + 1); if (!line || !line.startsWith('data:')) continue; const payloadStr = line.slice(5).trim(); if (payloadStr === '[DONE]') { doneSent = true; this.emitDelta(chat, { chunk: '', done: true }); return; } try { const parsed = JSON.parse(payloadStr) as { choices?: Array<{ delta?: { content?: string }; message?: { content?: string }; }>; error?: { message?: string }; }; if (parsed.error?.message) { doneSent = true; this.emitDelta(chat, { chunk: '', done: true, error: parsed.error.message }); return; } const chunk = parsed.choices?.[0]?.delta?.content ?? parsed.choices?.[0]?.message?.content ?? ''; if (chunk) { this.emitDelta(chat, { chunk }); } } catch { // Ignore partial/non-JSON keepalive lines } } } if (!doneSent) { this.emitDelta(chat, { chunk: '', done: true }); } } catch (err) { const msg = chat.abortController.signal.aborted ? 'Generation cancelled' : err instanceof Error ? err.message : String(err); this.emitDelta(chat, { chunk: '', done: true, error: chat.abortController.signal.aborted ? undefined : msg, }); } finally { chat.done = true; this.pruneChats(); } } private pruneChats(): void { const done = [...this.chats.values()].filter((c) => c.done); while (done.length > MAX_RETAINED_CHATS) { const oldest = done.shift()!; this.chats.delete(oldest.chatId); } } async testEndpoint(override?: { baseUrl?: string; model?: string; secretRef?: string; }): Promise<{ ok: boolean; latencyMs: number; replyPreview?: string; error?: string }> { const saved = this.configManager.getSettings().ai; const baseUrl = override?.baseUrl?.trim() || saved.baseUrl; const model = override?.model?.trim() || saved.model; const secretRef = override && 'secretRef' in override ? override.secretRef?.trim() || undefined : saved.secretRef; const url = normalizeChatCompletionsUrl(baseUrl); const bearer = this.resolveBearerToken(secretRef); const started = Date.now(); try { const headers: Record = { 'Content-Type': 'application/json' }; if (bearer) headers.Authorization = `Bearer ${bearer}`; const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify({ model, stream: false, max_tokens: 16, messages: [{ role: 'user', content: 'Reply with OK' }], }), signal: AbortSignal.timeout(10_000), }); const latencyMs = Date.now() - started; if (!res.ok) { const text = await res.text().catch(() => ''); return { ok: false, latencyMs, error: `HTTP ${res.status}${text ? `: ${text.slice(0, 180)}` : ''}`, }; } const data = (await res.json().catch(() => ({}))) as { choices?: Array<{ message?: { content?: string }; text?: string }>; }; const preview = data.choices?.[0]?.message?.content ?? data.choices?.[0]?.text ?? 'Connected'; return { ok: true, latencyMs, replyPreview: String(preview).trim().slice(0, 120) }; } catch (err) { return { ok: false, latencyMs: Date.now() - started, error: err instanceof Error ? err.message : String(err), }; } } validateDraft(opts: { kind: AiDraftKind; jsonText: string; targetId?: string; }): | { valid: true; kind: AiDraftKind; targetPath: string; id?: string; normalizedJson: string; diffLines: DiffLine[]; } | { valid: false; issues: Array<{ path: string; message: string }>; } { let cleaned = opts.jsonText.trim(); const fenceMatch = /^```(?:json)?\s*\r?\n([\s\S]*?)\r?\n```\s*$/i.exec(cleaned); if (fenceMatch?.[1]) { cleaned = fenceMatch[1].trim(); } let rawObj: unknown; try { rawObj = JSON.parse(cleaned); } catch (err) { return { valid: false, issues: [ { path: '(json)', message: err instanceof Error ? err.message : 'Invalid JSON syntax', }, ], }; } const withOptionalId = (obj: unknown) => opts.targetId && obj && typeof obj === 'object' && !Array.isArray(obj) ? { ...(obj as Record), id: (obj as Record).id ?? opts.targetId } : obj; let targetPath: string; let normalizedJson: string; let entityId: string | undefined; if (opts.kind === 'workflow') { const parsed = WorkflowConfigSchema.safeParse(withOptionalId(rawObj)); if (!parsed.success) { return { valid: false, issues: parsed.error.issues.map((i) => ({ path: i.path.join('.') || '(root)', message: i.message, })), }; } entityId = parsed.data.id; targetPath = `workflows/${entityId}.json`; normalizedJson = `${JSON.stringify(parsed.data, null, 2)}\n`; } else if (opts.kind === 'system') { const parsed = SystemConfigSchema.safeParse(withOptionalId(rawObj)); if (!parsed.success) { return { valid: false, issues: parsed.error.issues.map((i) => ({ path: i.path.join('.') || '(root)', message: i.message, })), }; } entityId = parsed.data.id; targetPath = `systems/${entityId}.json`; normalizedJson = `${JSON.stringify(parsed.data, null, 2)}\n`; } else if (opts.kind === 'server') { const parsed = ServerConfigSchema.safeParse(withOptionalId(rawObj)); if (!parsed.success) { return { valid: false, issues: parsed.error.issues.map((i) => ({ path: i.path.join('.') || '(root)', message: i.message, })), }; } entityId = parsed.data.id; targetPath = `servers/${entityId}.json`; normalizedJson = `${JSON.stringify(parsed.data, null, 2)}\n`; } else if (opts.kind === 'snippet') { const parsed = SnippetSchema.safeParse(withOptionalId(rawObj)); if (!parsed.success) { return { valid: false, issues: parsed.error.issues.map((i) => ({ path: i.path.join('.') || '(root)', message: i.message, })), }; } entityId = parsed.data.id; targetPath = 'snippets.json'; const current = this.configManager.getSnippets(); const exists = current.snippets.some((s) => s.id === parsed.data.id); const nextSnippets = SnippetsFileSchema.parse({ version: 1, snippets: exists ? current.snippets.map((s) => (s.id === parsed.data.id ? parsed.data : s)) : [...current.snippets, parsed.data], }); normalizedJson = `${JSON.stringify(nextSnippets, null, 2)}\n`; } else if (opts.kind === 'alerts') { const candidate = rawObj && typeof rawObj === 'object' && !Array.isArray(rawObj) ? { version: 1, ...(rawObj as Record) } : rawObj; const parsed = AlertsFileSchema.safeParse(candidate); if (!parsed.success) { return { valid: false, issues: parsed.error.issues.map((i) => ({ path: i.path.join('.') || '(root)', message: i.message, })), }; } targetPath = 'alerts.json'; normalizedJson = `${JSON.stringify(parsed.data, null, 2)}\n`; } else { const candidate = rawObj && typeof rawObj === 'object' && !Array.isArray(rawObj) ? { version: 1, ...(rawObj as Record) } : rawObj; const parsed = SettingsSchema.safeParse(candidate); if (!parsed.success) { return { valid: false, issues: parsed.error.issues.map((i) => ({ path: i.path.join('.') || '(root)', message: i.message, })), }; } targetPath = 'settings.json'; normalizedJson = `${JSON.stringify(parsed.data, null, 2)}\n`; } let currentContent = ''; try { currentContent = this.configManager.readRawFile(targetPath).rawContent; } catch { currentContent = ''; } const diff = computeLineDiff(currentContent, normalizedJson, 'existing', 'draft'); return { valid: true, kind: opts.kind, targetPath, id: entityId, normalizedJson, diffLines: diff.lines, }; } } export const AiDraftKindSchema = z.enum([ 'workflow', 'system', 'snippet', 'server', 'alerts', 'settings', ]);