import WebSocket from 'ws'; import crypto from 'node:crypto'; import os from 'node:os'; import fs from 'node:fs'; import path from 'node:path'; import { MaestriAdapter } from './maestri-adapter.js'; import { cleanTerminalOutput } from '../utils/text-sanitizer.js'; import { detectTerminalActivity } from '../utils/activity-detector.js'; import { AgentUpdater } from './agent-updater.js'; let CanvasAutoWiringMonitor = class FallbackAutoWiringMonitor { constructor() {} start() {} stop() {} }; try { const autoWiringModule = await import('./canvas-auto-wiring.js'); if (autoWiringModule && autoWiringModule.CanvasAutoWiringMonitor) { CanvasAutoWiringMonitor = autoWiringModule.CanvasAutoWiringMonitor; } } catch (err) { console.warn('[GatewayDaemon] Modulo canvas-auto-wiring nao disponivel ou falhou ao carregar:', err.message); } export class GatewayDaemon { constructor(options = {}) { this.relayUrl = options.relayUrl || process.env.RELAY_URL || 'wss://remote.winicomw.ddnsfree.com/ws/gateway'; this.publicHost = options.publicHost || process.env.PUBLIC_HOST || 'https://remote.winicomw.ddnsfree.com'; this.pin = options.pin || this.loadOrGeneratePin(options.resetPin); this.machineName = options.machineName || os.hostname() || 'Dev-Machine'; this.adapter = options.adapter || new MaestriAdapter({ workspaceFilePath: options.workspaceFilePath, workspaceId: options.workspaceId, syncCanvasTerminals: options.syncCanvasTerminals !== undefined ? options.syncCanvasTerminals : true }); this.updater = options.updater || new AgentUpdater({ publicHost: this.publicHost }); this.autoWiringMonitor = options.autoWiringMonitor || new CanvasAutoWiringMonitor({ workspaceFilePath: options.workspaceFilePath, workspaceId: options.workspaceId || this.adapter?.workspaceId, concentratorId: options.concentratorId || this.adapter?.terminalId || process.env.MAESTRI_TERMINAL_ID, concentratorName: options.concentratorName, onWired: (res) => { if (res.modified) { this.syncAgents(); } } }); this.ws = null; this.reconnectTimer = null; this.pollTimer = null; this.adaptivePollTimer = null; this.updateTimer = null; this.connected = false; this.lastAgents = []; this.recentAgentCommands = new Map(); } markRecentActivity(agentName) { if (!agentName) return; this.recentAgentCommands.set(agentName, Date.now()); this.scheduleAdaptiveCheck(agentName, 50); } scheduleAdaptiveCheck(agentName, delayMs = 50) { setTimeout(async () => { try { if (agentName && this.adapter && typeof this.adapter.checkAgent === 'function') { const rawOutput = await this.adapter.checkAgent(agentName); this.emitTerminalOutput(agentName, rawOutput); } await this.syncAgents(); } catch (e) {} }, delayMs); } loadOrGeneratePin(resetPin = false) { const sessionFile = path.resolve('.maestri-remote-session.json'); if (!resetPin) { if (process.env.MAESTRI_REMOTE_PIN && /^\d{4,8}$/.test(process.env.MAESTRI_REMOTE_PIN.trim())) { return process.env.MAESTRI_REMOTE_PIN.trim(); } if (fs.existsSync(sessionFile)) { try { const data = JSON.parse(fs.readFileSync(sessionFile, 'utf8')); if (data.pin && /^\d{4,8}$/.test(data.pin)) { return data.pin; } } catch (e) {} } } const newPin = this.generatePin(); try { fs.writeFileSync(sessionFile, JSON.stringify({ pin: newPin, createdAt: new Date().toISOString(), note: 'PIN fixo persistido para auto-login do Maestri Remote' }, null, 2), 'utf8'); } catch (e) {} return newPin; } generatePin() { return Math.floor(100000 + Math.random() * 900000).toString(); } getMagicLink() { return `${this.publicHost}/?pin=${this.pin}`; } start() { const version = this.updater?.getLocalVersion ? this.updater.getLocalVersion() : '1.0.9'; console.log('\n======================================================'); console.log(' MAESTRI REMOTE — Mobile Supervisor Daemon '); console.log('======================================================'); console.log(`Versão: \x1b[1m\x1b[36mv${version}\x1b[0m`); console.log(`PIN da Sessão: \x1b[1m\x1b[32m${this.pin}\x1b[0m`); console.log(`Magic Link: \x1b[36m${this.getMagicLink()}\x1b[0m`); console.log(`Relay Conexão: ${this.relayUrl}`); console.log('------------------------------------------------------'); console.log('Abra o link no seu smartphone ou digite o PIN no app.'); console.log('Pressione Ctrl+C para encerrar a sessão remota.\n'); this.connect(); this.startPollingAgents(); this.startAutoUpdateChecker(); if (this.autoWiringMonitor) { this.autoWiringMonitor.start(); } } async checkForAutoUpdate() { if (!this.updater) return; try { await this.updater.checkAndApply(); } catch (err) { console.warn('[Gateway] Verificação de auto-atualização:', err.message); } } startAutoUpdateChecker() { // Checagem inicial 3 segundos após o boot setTimeout(() => this.checkForAutoUpdate(), 3000); // Checagem periódica a cada 60 segundos para rápida propagação de atualizações this.updateTimer = setInterval(() => { this.checkForAutoUpdate(); }, 60 * 1000); } connect() { if (this.ws) { try { this.ws.close(); } catch (e) {} } console.log(`[Gateway] Conectando ao Relay Server em ${this.relayUrl}...`); this.ws = new WebSocket(this.relayUrl, { maxPayload: 150 * 1024 * 1024 }); this.ws.on('open', () => { console.log('[Gateway] Conectado com sucesso ao Relay Server!'); this.connected = true; // Autentica o gateway com o PIN this.ws.send(JSON.stringify({ type: 'AUTH_GATEWAY', pin: this.pin, machineName: this.machineName })); // Envia lista inicial de agentes this.syncAgents(); }); this.ws.on('message', async (data) => { try { const msg = JSON.parse(data.toString()); await this.handleRelayMessage(msg); } catch (err) { console.error('[Gateway] Erro ao processar mensagem do Relay:', err.message); } }); this.ws.on('close', () => { this.connected = false; console.warn('[Gateway] Conexão com Relay perdida. Tentando reconectar em 5 segundos...'); clearTimeout(this.reconnectTimer); this.reconnectTimer = setTimeout(() => this.connect(), 5000); }); this.ws.on('error', (err) => { console.error('[Gateway] Erro de WebSocket:', err.message); }); } async prepareSlashCommandContext(agentName) { const cachedAgent = Array.isArray(this.lastAgents) ? this.lastAgents.find(a => a && a.name === agentName) : null; let aiType = cachedAgent?.aiType; const checkOut = await this.adapter.checkAgent(agentName); const detected = detectTerminalActivity(checkOut); if ((!aiType || aiType === 'generic_ai') && detected.aiType) { aiType = detected.aiType; } if (detected.hasInteractiveMenu) { await this.adapter.sendRawInput(agentName, '\\x1b'); await this.adapter.wait(150); } const isKiro = aiType === 'kiro' || /kiro|kilo|opencode/i.test(cachedAgent?.preset || cachedAgent?.name || ''); return { aiType, isKiro }; } async handleRelayMessage(msg) { if (msg.type === 'AUTH_SUCCESS') { console.log(`[Gateway] Pareamento confirmado para a sessão ${msg.pin}`); } else if (msg.type === 'RESOLVE_PROMPT') { console.log(`[Gateway] Resposta recebida do celular para ${msg.agentName}: "${msg.response}"`); this.markRecentActivity(msg.agentName); await this.adapter.sendResponse(msg.agentName, msg.response); // Confirmação de volta if (this.ws && this.connected) { this.ws.send(JSON.stringify({ type: 'PROMPT_RESOLVED_CONFIRMED', requestId: msg.requestId })); } } else if (msg.type === 'CHAT_SEND') { let text = msg.message || msg.text || ''; console.log(`[Gateway] Mensagem de chat recebida para ${msg.agentName}: "${text}"`); this.markRecentActivity(msg.agentName); // Envia confirmação imediata (ACK) ao cliente mobile if (this.ws && this.connected) { this.ws.send(JSON.stringify({ type: 'CHAT_ACK', chatId: msg.chatId, agentName: msg.agentName, timestamp: new Date().toISOString() })); } // Se houver anexos (prints, documentos, áudios), salva localmente no disco const rawAttachments = Array.isArray(msg.attachments) && msg.attachments.length > 0 ? msg.attachments : (msg.attachment && msg.attachment.dataBase64 ? [msg.attachment] : []); if (rawAttachments.length > 0) { const savedPaths = []; for (const att of rawAttachments) { if (att && att.dataBase64) { try { const savedFilePath = await this.saveAttachment(att); if (savedFilePath) { savedPaths.push(savedFilePath); console.log(`[Gateway] Anexo salvo com sucesso em: ${savedFilePath}`); } } catch (attErr) { console.error(`[Gateway] Erro ao salvar anexo recebido (${att.name || 'arquivo'}):`, attErr.message); } } } if (savedPaths.length === 1) { text = `[Anexo recebido do operador: ${savedPaths[0]}] ${text}`.trim(); } else if (savedPaths.length > 1) { const pathList = savedPaths.map(p => `- ${p}`).join('\n'); text = `[Anexos recebidos do operador:\n${pathList}]\n${text}`.trim(); } } // Se for comando de alternância de modelo (/model, /modelo ou /models) e não tiver anexos, // roteia em modo raw para evitar o Enter prematuro que fecha o menu interativo imediatamente const modelCommandMatch = (rawAttachments.length === 0) ? text.match(/^\s*\/(?:model|modelo|models)(?:\s+(.*))?\s*$/i) : null; if (modelCommandMatch) { console.log(`[Gateway] Comando de menu de modelo detectado para ${msg.agentName}: "${text}"`); const filterArg = (modelCommandMatch[1] || '').trim(); await this.prepareSlashCommandContext(msg.agentName); await this.adapter.sendRawInput(msg.agentName, '\\x15/model\\n'); if (filterArg) { await this.adapter.wait(150); await this.adapter.sendRawInput(msg.agentName, filterArg); } else { await this.adapter.wait(200); } const rawOutput = await this.adapter.checkAgent(msg.agentName); this.emitTerminalOutput(msg.agentName, rawOutput); this.syncAgents(); if (this.ws && this.connected) { this.ws.send(JSON.stringify({ type: 'CHAT_RESPONSE', chatId: msg.chatId, agentName: msg.agentName, reply: '🎛️ Menu de modelos interativo aberto. Selecione uma opção no painel.', response: '🎛️ Menu de modelos interativo aberto. Selecione uma opção no painel.', ok: true, timestamp: new Date().toISOString() })); } return; } // Se for comando de alternância de esforço de raciocínio (/effort, /esforco ou /esforço) e não tiver anexos, // roteia em modo raw para abrir a tela horizontal Set Effort ou aplicar o nível diretamente const effortCommandMatch = (rawAttachments.length === 0) ? text.match(/^\s*\/(?:effort|esforco|esforço)(?:\s+(.*))?\s*$/i) : null; if (effortCommandMatch) { console.log(`[Gateway] Comando de esforço detectado para ${msg.agentName}: "${text}"`); const rawArg = (effortCommandMatch[1] || '').trim().toLowerCase(); let normalizedArg = rawArg; if (['baixo', 'min', 'low'].includes(rawArg)) normalizedArg = 'low'; else if (['medio', 'médio', 'med', 'medium'].includes(rawArg)) normalizedArg = 'medium'; else if (['alto', 'max', 'high'].includes(rawArg)) normalizedArg = 'high'; const { isKiro } = await this.prepareSlashCommandContext(msg.agentName); if (normalizedArg && ['low', 'medium', 'high'].includes(normalizedArg)) { await this.adapter.sendRawInput(msg.agentName, `\\x15/effort ${normalizedArg}\\n`); await this.adapter.wait(200); const rawOutput = await this.adapter.checkAgent(msg.agentName); this.emitTerminalOutput(msg.agentName, rawOutput); this.syncAgents(); if (this.ws && this.connected) { const replyMsg = `⚡ Nível de esforço de raciocínio definido para "${normalizedArg}".`; this.ws.send(JSON.stringify({ type: 'CHAT_RESPONSE', chatId: msg.chatId, agentName: msg.agentName, reply: replyMsg, response: replyMsg, ok: true, timestamp: new Date().toISOString() })); } return; } // Sem argumento: abre a interface interativa Set Effort no Antigravity CLI ou Kiro CLI await this.adapter.sendRawInput(msg.agentName, '\\x15/effort\\n'); await this.adapter.wait(200); const rawOutput = await this.adapter.checkAgent(msg.agentName); this.emitTerminalOutput(msg.agentName, rawOutput); this.syncAgents(); if (this.ws && this.connected) { const replyText = isKiro ? '🎛️ Painel de controles/esforço do modelo aberto. Selecione uma opção no painel.' : '🎛️ Menu de esforço de raciocínio aberto. Selecione uma opção no painel.'; this.ws.send(JSON.stringify({ type: 'CHAT_RESPONSE', chatId: msg.chatId, agentName: msg.agentName, reply: replyText, response: replyText, ok: true, timestamp: new Date().toISOString() })); } return; } const result = await this.adapter.askAgent(msg.agentName, text); if (this.ws && this.connected) { const rawReply = result.output || result.error || 'Sem resposta do agente.'; const replyText = cleanTerminalOutput(rawReply); this.ws.send(JSON.stringify({ type: 'CHAT_RESPONSE', chatId: msg.chatId, agentName: msg.agentName, reply: replyText, response: replyText, ok: result.ok, timestamp: new Date().toISOString() })); } } else if (msg.type === 'GET_AGENTS') { console.log('[Gateway] Solicitação de lista de agentes recebida do mobile'); this.syncAgents(); } else if (msg.type === 'GET_AGENT_TERMINAL') { console.log(`[Gateway] Solicitando saída do terminal para ${msg.agentName}`); const rawOutput = await this.adapter.checkAgent(msg.agentName); this.emitTerminalOutput(msg.agentName, rawOutput); } else if (msg.type === 'TERMINAL_RAW_INPUT') { const agentName = typeof msg.agentName === 'string' ? msg.agentName.trim() : ''; const sequences = (Array.isArray(msg.keys) && msg.keys.length > 0) ? msg.keys.filter(k => typeof k === 'string' && k.length > 0) : ((typeof msg.raw === 'string' && msg.raw.length > 0) ? [msg.raw] : []); if (!agentName || sequences.length === 0) { return; } console.log(`[Gateway] Input raw TUI recebido para ${agentName}: ${JSON.stringify(sequences)}`); let lastRes = null; for (const seq of sequences) { lastRes = await this.adapter.sendRawInput(agentName, seq); if (!lastRes || !lastRes.ok) { console.warn(`[Gateway] Input raw abortado para ${agentName} na sequência ${JSON.stringify(seq)}: ${lastRes?.error || 'falha desconhecida'}`); break; } } const rawOutput = (lastRes && lastRes.ok && lastRes.output && lastRes.output.trim()) ? lastRes.output : await this.adapter.checkAgent(agentName); this.emitTerminalOutput(agentName, rawOutput); this.syncAgents(); } else if (msg.type === 'RESTART_AGENT_TERMINAL') { const agentName = typeof msg.agentName === 'string' ? msg.agentName.trim() : ''; if (!agentName) { return; } const cachedAgent = Array.isArray(this.lastAgents) ? this.lastAgents.find(a => a && a.name === agentName) : null; const isSelf = cachedAgent ? Boolean(cachedAgent.isSelf) : (msg.isSelf === true ? true : undefined); console.log(`[Gateway] Solicitado reinício/reload de terminal para ${agentName} (isSelf=${Boolean(isSelf)})`); let restartRes; try { restartRes = await this.adapter.restartAgentTerminal(agentName, { isSelf }); } catch (err) { restartRes = { ok: false, method: 'raw_restart', output: '', error: err?.message || 'Erro interno ao reiniciar terminal' }; } if (this.ws && this.connected) { this.ws.send(JSON.stringify({ type: 'AGENT_TERMINAL_RESTARTED', agentName, ok: !!restartRes?.ok, method: restartRes?.method || null, error: restartRes?.error || null, timestamp: new Date().toISOString() })); } const rawOutput = (restartRes && restartRes.output) ? restartRes.output : await this.adapter.checkAgent(agentName); this.emitTerminalOutput(agentName, rawOutput); await this.syncAgents(); } else if (msg.type === 'AGENT_UPDATE_AVAILABLE') { console.log('[Gateway] Notificação push do Relay: Nova versão do daemon disponível!'); this.checkForAutoUpdate(); } else if (msg.type === 'FILE_READ_REQ') { const reqPath = typeof msg.path === 'string' ? msg.path.trim() : ''; const agentName = msg.agentName || ''; const chatId = msg.chatId || ''; const respondFailure = (errorMsg) => { if (this.ws && this.connected) { this.ws.send(JSON.stringify({ type: 'FILE_READ_RESP', path: reqPath, ok: false, error: errorMsg, chatId, agentName, timestamp: new Date().toISOString() })); } }; if (!reqPath) { respondFailure('Caminho de arquivo inválido ou não informado.'); return; } try { const workspaceRoot = path.resolve(process.cwd()); const normalizedInput = path.normalize(reqPath); const targetPath = path.isAbsolute(normalizedInput) ? path.resolve(normalizedInput) : path.resolve(workspaceRoot, normalizedInput); const relative = path.relative(workspaceRoot, targetPath); const isInsideWorkspace = !relative.startsWith('..') && !path.isAbsolute(relative); if (!isInsideWorkspace) { console.warn(`[Gateway:Security] Bloqueio de sandbox para path fora do workspace: ${reqPath} -> ${targetPath}`); respondFailure('Acesso negado: o arquivo solicitado está fora do workspace do projeto.'); return; } if (!fs.existsSync(targetPath)) { respondFailure('Arquivo não encontrado no host.'); return; } const stats = fs.statSync(targetPath); if (!stats.isFile()) { respondFailure('O caminho solicitado não é um arquivo regular.'); return; } const MAX_SIZE = 20 * 1024 * 1024; // 20 MB if (stats.size > MAX_SIZE) { respondFailure('Arquivo excede o limite máximo de 20 MB.'); return; } const mimeType = this.detectMimeType(targetPath); const contentBase64 = fs.readFileSync(targetPath).toString('base64'); const fileName = path.basename(targetPath); if (this.ws && this.connected) { this.ws.send(JSON.stringify({ type: 'FILE_READ_RESP', path: reqPath, name: fileName, mimeType, size: stats.size, contentBase64, ok: true, chatId, agentName, timestamp: new Date().toISOString() })); console.log(`[Gateway] Arquivo lido e despachado: ${fileName} (${stats.size} bytes, ${mimeType})`); } } catch (err) { console.error(`[Gateway] Erro ao ler arquivo ${reqPath}:`, err.message); respondFailure(`Erro ao ler arquivo: ${err.message}`); } } } detectMimeType(filePath) { const ext = path.extname(filePath).toLowerCase().replace('.', ''); const mimeMap = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', svg: 'image/svg+xml', webp: 'image/webp', ico: 'image/x-icon', pdf: 'application/pdf', txt: 'text/plain', md: 'text/markdown', markdown: 'text/markdown', json: 'application/json', js: 'text/javascript', mjs: 'text/javascript', ts: 'text/typescript', html: 'text/html', htm: 'text/html', css: 'text/css', csv: 'text/csv', xml: 'application/xml', yaml: 'text/yaml', yml: 'text/yaml', log: 'text/plain', sh: 'text/x-sh', ps1: 'text/plain', bat: 'text/plain', cmd: 'text/plain', zip: 'application/zip', tar: 'application/x-tar', gz: 'application/gzip', apk: 'application/vnd.android.package-archive' }; return mimeMap[ext] || 'application/octet-stream'; } emitTerminalOutput(agentName, rawOutput) { const activity = detectTerminalActivity(rawOutput); const output = cleanTerminalOutput(rawOutput); if (this.ws && this.connected) { this.ws.send(JSON.stringify({ type: 'AGENT_TERMINAL_OUTPUT', agentName, output: output || 'Terminal vazio no momento.', rawOutput, hasAiActivity: activity.hasAiActivity, aiType: activity.aiType, isThinking: activity.isThinking, isPaused: activity.isPaused, pauseReason: activity.pauseReason, pauseResetTime: activity.pauseResetTime, hasInteractiveMenu: !!activity.hasInteractiveMenu, interactiveMenu: activity.interactiveMenu || null, details: activity.details, timestamp: new Date().toISOString() })); } } async syncAgents() { if (!this.connected || !this.ws) return; try { const agents = await this.adapter.listAgents(); this.lastAgents = Array.isArray(agents) ? agents : []; this.ws.send(JSON.stringify({ type: 'AGENTS_UPDATE', agents })); } catch (err) { console.error('[Gateway] Erro ao sincronizar agentes:', err.message); } } startPollingAgents() { // Polling adaptativo rápido (350ms): monitora agentes ativos/pensando ou com comando nos últimos 10s this.adaptivePollTimer = setInterval(async () => { if (!this.connected || !this.ws) return; const now = Date.now(); const activeTargets = (this.lastAgents || []).filter(a => { if (!a || a.isSelf) return false; const lastCmd = this.recentAgentCommands.get(a.name) || 0; return a.isThinking === true || (now - lastCmd < 10000); }); for (const target of activeTargets) { try { const rawOut = await this.adapter.checkAgent(target.name); this.emitTerminalOutput(target.name, rawOut); } catch (e) {} } }, 350); // Polling base (15s): atualiza lista global de agentes ociosos/em repouso this.pollTimer = setInterval(() => { this.syncAgents(); }, 15000); } // Notifica o smartphone de um prompt que aguarda resposta dispatchPrompt({ requestId, agentName, prompt, options = [] }) { if (!this.connected || !this.ws) return false; const reqId = requestId || `req-${Date.now()}`; console.log(`[Gateway] Disparando prompt para o celular: [${agentName}] ${prompt}`); this.ws.send(JSON.stringify({ type: 'PROMPT_PENDING', requestId: reqId, agentName, prompt, options, timestamp: new Date().toISOString() })); return reqId; } async saveAttachment(attachment) { if (!attachment || !attachment.dataBase64) return null; const uploadsDir = path.resolve(process.cwd(), '.maestri-remote', 'uploads'); if (!fs.existsSync(uploadsDir)) { fs.mkdirSync(uploadsDir, { recursive: true }); } const rawName = attachment.name || 'anexo.bin'; let safeBaseName = path.basename(rawName).replace(/[^a-zA-Z0-9._-]/g, '_'); // Sanitização e garantia de extensão adequada para vídeos e multimídia let ext = path.extname(safeBaseName).toLowerCase(); if (!ext || ext === '.') { const mime = (attachment.mimeType || '').toLowerCase(); if (mime.includes('mp4')) ext = '.mp4'; else if (mime.includes('webm')) ext = '.webm'; else if (mime.includes('quicktime') || mime.includes('mov')) ext = '.mov'; else if (mime.includes('mkv')) ext = '.mkv'; else if (mime.includes('ogg') || mime.includes('ogv')) ext = '.ogv'; else if (mime.includes('jpeg') || mime.includes('jpg')) ext = '.jpg'; else if (mime.includes('png')) ext = '.png'; else if (mime.includes('webp')) ext = '.webp'; else if (mime.includes('pdf')) ext = '.pdf'; else ext = '.bin'; safeBaseName = safeBaseName.replace(/\.+$/, '') + ext; } const fileName = `${Date.now()}-${safeBaseName}`; const filePath = path.join(uploadsDir, fileName); const buffer = Buffer.from(attachment.dataBase64, 'base64'); fs.writeFileSync(filePath, buffer); return filePath; } stop() { clearTimeout(this.reconnectTimer); clearInterval(this.pollTimer); clearInterval(this.adaptivePollTimer); clearInterval(this.updateTimer); if (this.autoWiringMonitor) { this.autoWiringMonitor.stop(); } if (this.ws) { this.ws.close(); } console.log('[Gateway] Sessão remota encerrada.'); } }