maestri-remote/src/gateway/maestri-adapter.js

533 lines
22 KiB
JavaScript

import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import { detectTerminalActivity } from '../utils/activity-detector.js';
import { resolveWorkspaceFilePath, getWorkspaceTerminalNodes } from './canvas-auto-wiring.js';
const execFileAsync = promisify(execFile);
// Limite seguro de caracteres para linha de comando/console do sistema operacional (Windows/Linux)
export const DEFAULT_MAX_CONSOLE_LENGTH = 3000;
const AI_LAUNCH_SPECS = {
agy: { preset: 'Antigravity', command: 'agy', exitSequence: '/exit\\n' },
claude: { preset: 'Claude Code', command: 'claude', exitSequence: '/exit\\n' },
gemini: { preset: null, command: 'gemini', exitSequence: '/exit\\n' },
aider: { preset: null, command: 'aider', exitSequence: '/exit\\n' },
// Kilo CLI: `/exit` encerra o TUI e devolve o shell (homologado no kilo 7.8.32); Ctrl+C isolado nao encerra.
kilo: { preset: null, command: 'kilo', exitSequence: '/exit\\n' }
};
/**
* Mapeia deterministicamente preset, comando de relançamento e sequência de saída
* para um terminal conforme atividade detectada e histórico recente.
*/
export function resolveTerminalLaunchSpec(rawOutput, activity) {
const tail = typeof rawOutput === 'string' ? rawOutput.slice(-3000) : '';
if (!activity || !activity.hasAiActivity) {
return { preset: 'Shell', command: null, exitSequence: null };
}
const direct = AI_LAUNCH_SPECS[activity.aiType];
if (direct) {
return { ...direct };
}
if (activity.aiType === 'kiro') {
return { preset: null, command: 'kiro-cli', exitSequence: '/exit\\n' };
}
if (/\bcodex\b/i.test(tail)) {
return { preset: 'Codex', command: 'codex', exitSequence: '/exit\\n' };
}
return { preset: null, command: null, exitSequence: '\\x03' };
}
export class MaestriAdapter {
constructor(options = {}) {
this.maestriCli = options.maestriCli || process.env.MAESTRI_CLI || 'maestri';
this.pipePath = options.pipePath || process.env.MAESTRI_PIPE;
this.terminalId = options.terminalId || process.env.MAESTRI_TERMINAL_ID;
this.workspaceId = options.workspaceId || process.env.MAESTRI_WORKSPACE_ID;
this.workspaceFilePath = options.workspaceFilePath;
// Terminais soltos do workspace.json não têm cabo na memória do Maestri: check/ask falham para eles.
// Por isso a mescla com o canvas só acontece quando pedida explicitamente.
this.syncCanvasTerminals = options.syncCanvasTerminals === true;
this.maxConsoleLength = options.maxConsoleLength || DEFAULT_MAX_CONSOLE_LENGTH;
this.messagesDir = options.messagesDir || path.resolve(process.cwd(), '.maestri-remote', 'messages');
this.restartDelayMs = Number.isFinite(options.restartDelayMs) ? Math.max(0, options.restartDelayMs) : 400;
this.selfAgentNames = new Set();
}
async requestPipe(method, path, headers = {}, body = null) {
if (!this.pipePath) {
throw new Error('MAESTRI_PIPE não configurado no ambiente.');
}
return new Promise((resolve) => {
let client;
try {
client = net.connect(this.pipePath, () => {
let req = `${method} ${path} HTTP/1.0\r\n` +
`Host: maestri\r\n`;
if (this.terminalId) req += `X-Terminal-ID: ${this.terminalId}\r\n`;
if (this.workspaceId) req += `X-Workspace-ID: ${this.workspaceId}\r\n`;
for (const [k, v] of Object.entries(headers)) {
req += `${k}: ${v}\r\n`;
}
if (body) {
const jsonBody = typeof body === 'string' ? body : JSON.stringify(body);
req += `Content-Type: application/json\r\nContent-Length: ${Buffer.byteLength(jsonBody)}\r\n\r\n${jsonBody}`;
} else {
req += `\r\n`;
}
client.write(req);
});
} catch (err) {
return resolve({ ok: false, error: err.message, status: 500 });
}
let rawData = '';
client.on('data', chunk => { rawData += chunk.toString(); });
client.on('end', () => {
const splitIdx = rawData.indexOf('\r\n\r\n');
const headerPart = splitIdx !== -1 ? rawData.slice(0, splitIdx) : '';
const bodyPart = splitIdx !== -1 ? rawData.slice(splitIdx + 4) : rawData;
const statusCode = parseInt(headerPart.split(' ')[1], 10) || 500;
if (statusCode >= 200 && statusCode < 300) {
resolve({ ok: true, output: bodyPart, status: statusCode });
} else {
resolve({ ok: false, error: bodyPart.trim(), status: statusCode });
}
});
client.on('error', err => resolve({ ok: false, error: err.message, status: 500 }));
});
}
async wait(ms) {
if (!ms || ms <= 0) return;
await new Promise(resolve => setTimeout(resolve, ms));
}
/**
* Salva textos que excedem a limitação de console em um arquivo físico no disco.
*/
saveLongTextToFile(text, prefix = 'msg') {
if (!fs.existsSync(this.messagesDir)) {
fs.mkdirSync(this.messagesDir, { recursive: true });
}
const safePrefix = prefix.replace(/[^a-zA-Z0-9._-]/g, '_');
const fileName = `${safePrefix}-${Date.now()}.txt`;
const filePath = path.join(this.messagesDir, fileName);
fs.writeFileSync(filePath, text, 'utf8');
return filePath;
}
/**
* Formata o prompt substituto para o agente com a referência do arquivo texto e preview.
*/
formatLongMessagePrompt(filePath, text) {
const preview = (text || '').substring(0, 300).trim();
return `[Mensagem longa do operador salva em arquivo texto: ${filePath}]\nInstrução: A mensagem do operador excedeu a limitação de console (${(text || '').length} caracteres). Por favor, leia o arquivo texto acima para verificar o conteúdo completo e atender à solicitação.\n\nTrecho inicial:\n"${preview}..."`;
}
/**
* Identifica se um erro retornado pelo processo é decorrente de limites de linha de comando/console.
*/
isConsoleLimitError(errStr) {
if (!errStr || typeof errStr !== 'string') return false;
const lower = errStr.toLowerCase();
return (
lower.includes('muito longa') ||
lower.includes('too long') ||
lower.includes('enametoolong') ||
lower.includes('e2big') ||
lower.includes('maxbuffer') ||
lower.includes('command line is too long')
);
}
/**
* Executa comandos da CLI do Maestri diretamente como processo nativo (sem cmd.exe),
* eliminando quebras de aspas e o limite de 8191 caracteres do cmd.exe.
*/
async runMaestri(argsArray) {
try {
const args = Array.isArray(argsArray) ? argsArray : argsArray.split(' ').filter(Boolean);
const { stdout, stderr } = await execFileAsync(this.maestriCli, args, {
maxBuffer: 10 * 1024 * 1024,
windowsHide: true
});
return { ok: true, output: (stdout || '').trim(), error: null };
} catch (err) {
// Limpa paths absolutos de erro do Node para manter mensagens limpas
const rawMsg = (err.stderr || '').trim() || (err.stdout || '').trim() || err.message || 'Falha ao executar comando';
const cleanError = rawMsg
.replace(/^Command failed:[^\n]*\n?/im, '')
.trim();
return { ok: false, output: (err.stdout || '').trim(), error: cleanError || rawMsg };
}
}
async listAgents() {
const res = await this.runMaestri(['list']);
const rawList = [];
const seenNames = new Set();
let isSelf = false;
let inAgentsSection = true;
if (res && res.ok && typeof res.output === 'string') {
const lines = res.output.split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith('You:')) {
isSelf = true;
inAgentsSection = true;
} else if (
trimmed.startsWith('Connected agents:') ||
trimmed.startsWith('Connected terminals:') ||
trimmed.startsWith('Agents:') ||
trimmed.startsWith('Terminals:')
) {
isSelf = false;
inAgentsSection = true;
} else if (
trimmed.startsWith('Connected notes:') ||
trimmed.startsWith('Connected portals:') ||
trimmed.startsWith('Notes:') ||
trimmed.startsWith('Portals:')
) {
inAgentsSection = false;
} else if (inAgentsSection) {
// Só conexões diretas (- name: "..."). Entradas transitivas (⎿ agent: "...") não são alcançáveis
// por check/ask a partir deste terminal ("No connection to ..."), por isso ficam de fora.
const match = trimmed.match(/^-\s*name:\s*["']?([^"',\r\n]+)["']?/i);
if (match) {
const name = match[1].trim();
if (name && !seenNames.has(name)) {
seenNames.add(name);
rawList.push({
name,
isSelf
});
}
}
}
}
} else if (res && !res.ok) {
console.warn('[Gateway:MaestriAdapter] Falha ao executar maestri list:', res.error);
}
// Só complementa com os terminais do canvas quando habilitado explicitamente (syncCanvasTerminals: true)
const canvasTerminalsMap = new Map();
if (this.syncCanvasTerminals) {
try {
const wsPath = resolveWorkspaceFilePath(this.workspaceFilePath, this.workspaceId);
if (wsPath) {
const canvasTerminals = getWorkspaceTerminalNodes(wsPath);
for (const term of canvasTerminals) {
canvasTerminalsMap.set(term.name, term);
if (!seenNames.has(term.name)) {
seenNames.add(term.name);
const isCurrentSelf = (this.terminalId && term.id === this.terminalId) ||
(typeof term.name === 'string' && /^(?:maestri-remote|maestri-remote-channel|maestri-remote-agent)$/i.test(term.name));
rawList.push({
name: term.name,
isSelf: isCurrentSelf,
fromCanvas: true,
canvasMeta: term
});
}
}
}
} catch (e) {}
}
// Inspeciona os terminais conectados em paralelo para determinar se possuem agente de IA ativo
this.selfAgentNames = new Set(rawList.filter(item => item.isSelf).map(item => item.name));
const agents = await Promise.all(
rawList.map(async (item) => {
if (item.isSelf) {
return {
name: item.name,
isSelf: true,
status: 'self',
hasAiActivity: false,
aiType: null,
shellType: null,
hasInteractiveMenu: false,
interactiveMenu: null
};
}
try {
const output = await this.checkAgent(item.name);
const activity = detectTerminalActivity(output);
let hasAiActivity = activity.hasAiActivity;
let aiType = activity.aiType;
let shellType = activity.shellType;
// Se checkAgent não detectou atividade (ex: terminal solto no canvas sem cabo ligado),
// enriquece a partir dos metadados extraídos do workspace.json
const meta = item.canvasMeta || canvasTerminalsMap.get(item.name);
if (!hasAiActivity && meta) {
const cmd = (meta.command || '').trim().toLowerCase();
const agType = (meta.agentType || '').trim().toLowerCase();
if (agType === 'antigravity_cli' || cmd === 'agy' || cmd.startsWith('agy ')) {
hasAiActivity = true;
aiType = aiType || 'agy';
} else if (agType === 'claude_code' || cmd === 'claude' || cmd.startsWith('claude ')) {
hasAiActivity = true;
aiType = aiType || 'claude';
} else if (cmd === 'gemini' || cmd.startsWith('gemini ')) {
hasAiActivity = true;
aiType = aiType || 'gemini';
} else if (cmd === 'kilo' || cmd.startsWith('kilo ')) {
hasAiActivity = true;
aiType = aiType || 'kilo';
} else if (cmd === 'kiro' || cmd.startsWith('kiro ') || cmd === 'kiro-cli' || cmd.startsWith('kiro-cli ')) {
hasAiActivity = true;
aiType = aiType || 'kiro';
} else if (cmd) {
shellType = shellType || 'shell';
}
}
return {
name: item.name,
isSelf: false,
status: activity.isPaused ? 'paused' : (hasAiActivity ? 'active' : 'idle_shell'),
hasAiActivity,
aiType,
shellType: shellType || activity.shellType,
isThinking: activity.isThinking,
isPaused: !!activity.isPaused,
pauseReason: activity.pauseReason || null,
pauseResetTime: activity.pauseResetTime || null,
hasInteractiveMenu: !!activity.hasInteractiveMenu,
interactiveMenu: activity.interactiveMenu || null
};
} catch (err) {
const meta = item.canvasMeta || canvasTerminalsMap.get(item.name);
let hasAiActivity = false;
let aiType = null;
let shellType = 'unknown_shell';
if (meta) {
const cmd = (meta.command || '').trim().toLowerCase();
const agType = (meta.agentType || '').trim().toLowerCase();
if (agType === 'antigravity_cli' || cmd === 'agy' || cmd.startsWith('agy ')) {
hasAiActivity = true;
aiType = 'agy';
} else if (agType === 'claude_code' || cmd === 'claude' || cmd.startsWith('claude ')) {
hasAiActivity = true;
aiType = 'claude';
} else if (cmd === 'gemini' || cmd.startsWith('gemini ')) {
hasAiActivity = true;
aiType = 'gemini';
} else if (cmd === 'kilo' || cmd.startsWith('kilo ')) {
hasAiActivity = true;
aiType = 'kilo';
} else if (cmd === 'kiro' || cmd.startsWith('kiro ') || cmd === 'kiro-cli' || cmd.startsWith('kiro-cli ')) {
hasAiActivity = true;
aiType = 'kiro';
} else if (cmd) {
shellType = 'shell';
}
}
return {
name: item.name,
isSelf: false,
status: hasAiActivity ? 'active' : 'idle_shell',
hasAiActivity,
aiType,
shellType,
isThinking: false,
isPaused: false,
pauseReason: null,
pauseResetTime: null,
hasInteractiveMenu: false,
interactiveMenu: null
};
}
})
);
return agents;
}
async checkAgent(agentName) {
if (this.pipePath) {
const res = await this.requestPipe('GET', '/check', { 'X-Agent-Name': agentName });
if (res.ok) return res.output;
}
const res = await this.runMaestri(['check', agentName]);
return res.output || '';
}
async sendRawInput(agentName, rawSequence) {
if (!agentName || typeof rawSequence !== 'string' || rawSequence.length === 0) {
return { ok: false, output: '', error: 'Sequência raw inválida' };
}
// Sempre pelo CLI, nunca pelo pipe: o pipe do Maestri entrega a tecla e responde EPIPE (igual a uma falha),
// entao o fallback para o CLI enviava a mesma tecla duas vezes (seta+seta, Enter+Enter). No Kilo, tocar em
// "Allow always" virava Reject. O CLI entrega uma vez e devolve a tela.
console.log(`[Gateway:MaestriAdapter] Enviando input raw para "${agentName}": ${JSON.stringify(rawSequence)}`);
const res = await this.runMaestri(['ask', agentName, '--raw', rawSequence]);
return {
ok: res.ok,
output: res.output || '',
error: res.error
};
}
/**
* Botão de desligar: encerra a ferramenta de IA do terminal (agy, Claude Code etc.) enviando
* Ctrl+C, a sequência de saída da ferramenta e Ctrl+D se preciso. Deixa o terminal no shell,
* sem relançar a ferramenta.
*/
async restartAgentTerminal(agentName, options = {}) {
const trimmedAgent = typeof agentName === 'string' ? agentName.trim() : '';
if (!trimmedAgent) {
return { ok: false, method: 'invalid_agent', output: '', error: 'Nome de agente inválido.' };
}
const isSelfTarget = options.isSelf === true || (options.isSelf !== false && this.selfAgentNames.has(trimmedAgent));
if (isSelfTarget) {
return {
ok: false,
method: 'blocked_self',
output: '',
error: 'Não é possível reiniciar o próprio terminal do daemon remoto por este comando.'
};
}
const rawBefore = await this.checkAgent(trimmedAgent);
const activityBefore = detectTerminalActivity(rawBefore);
const spec = resolveTerminalLaunchSpec(rawBefore, activityBefore);
const failRaw = (res, fallbackOut, fallbackErr) => ({
ok: false,
method: 'interrupt_ai',
output: res?.output || fallbackOut || '',
error: res?.error || fallbackErr
});
// Encerra a ferramenta de IA como um Ctrl+C do operador e deixa o terminal no shell (sem relançar).
const interruptRes = await this.sendRawInput(trimmedAgent, '\\x03');
if (!interruptRes.ok) {
return failRaw(interruptRes, rawBefore, 'Falha ao enviar comando ao terminal');
}
await this.wait(this.restartDelayMs);
let midOutput = await this.checkAgent(trimmedAgent);
let midActivity = detectTerminalActivity(midOutput);
if (spec.command && midActivity.hasAiActivity) {
const exitRes = await this.sendRawInput(trimmedAgent, spec.exitSequence || '\\x03\\x03');
if (!exitRes.ok) {
return failRaw(exitRes, midOutput, 'Falha ao enviar sequência de saída ao assistente');
}
await this.wait(this.restartDelayMs);
midOutput = await this.checkAgent(trimmedAgent);
midActivity = detectTerminalActivity(midOutput);
if (midActivity.hasAiActivity) {
const eofRes = await this.sendRawInput(trimmedAgent, '\\x04');
if (!eofRes.ok) {
return failRaw(eofRes, midOutput, 'Falha ao enviar EOF (Ctrl+D) ao terminal');
}
await this.wait(this.restartDelayMs);
midOutput = await this.checkAgent(trimmedAgent);
midActivity = detectTerminalActivity(midOutput);
}
}
if (spec.command && midActivity.hasAiActivity) {
return {
ok: false,
method: 'interrupt_ai',
output: midOutput || '',
error: `Não foi possível encerrar a sessão ativa do assistente (${spec.command}).`
};
}
return {
ok: true,
method: 'interrupt_ai',
output: midOutput || '',
error: null
};
}
async sendResponse(agentName, response) {
let payload = response || '';
// Se o payload exceder a limitação de console, salva em arquivo texto
if (payload.length > this.maxConsoleLength && !payload.startsWith('[Mensagem longa do operador salva em arquivo texto:')) {
try {
const filePath = this.saveLongTextToFile(payload, `response-${agentName}`);
console.log(`[Gateway:MaestriAdapter] Resposta longa (${payload.length} chars) salva em arquivo: ${filePath}`);
payload = this.formatLongMessagePrompt(filePath, payload);
} catch (err) {
console.error('[Gateway:MaestriAdapter] Falha ao salvar resposta longa em arquivo:', err.message);
}
}
console.log(`[Gateway:MaestriAdapter] Enviando resposta para "${agentName}": "${payload.substring(0, 100)}..."`);
let res = await this.runMaestri(['ask', agentName, payload]);
// Fallback se estourar limite de console
if (!res.ok && this.isConsoleLimitError(res.error) && !payload.startsWith('[Mensagem longa do operador salva em arquivo texto:')) {
console.warn(`[Gateway:MaestriAdapter] Detectada limitação de console ("${res.error}"). Salvando resposta em arquivo...`);
try {
const filePath = this.saveLongTextToFile(response, `fallback-response-${agentName}`);
const fallbackPayload = this.formatLongMessagePrompt(filePath, response);
res = await this.runMaestri(['ask', agentName, fallbackPayload]);
} catch (fbErr) {
console.error('[Gateway:MaestriAdapter] Falha no fallback de arquivo texto:', fbErr.message);
}
}
return res.ok;
}
async askAgent(agentName, message) {
let payload = message || '';
// Se a mensagem exceder a limitação de console, salva em arquivo texto
if (payload.length > this.maxConsoleLength && !payload.startsWith('[Mensagem longa do operador salva em arquivo texto:')) {
try {
const filePath = this.saveLongTextToFile(payload, `prompt-${agentName}`);
console.log(`[Gateway:MaestriAdapter] Mensagem longa (${payload.length} chars) salva em arquivo: ${filePath}`);
payload = this.formatLongMessagePrompt(filePath, payload);
} catch (err) {
console.error('[Gateway:MaestriAdapter] Falha ao salvar mensagem longa em arquivo:', err.message);
}
}
console.log(`[Gateway:MaestriAdapter] Enviando mensagem de chat para "${agentName}" (${payload.length} chars)`);
let res = await this.runMaestri(['ask', agentName, payload]);
// Fallback se estourar limite de console
if (!res.ok && this.isConsoleLimitError(res.error) && !payload.startsWith('[Mensagem longa do operador salva em arquivo texto:')) {
console.warn(`[Gateway:MaestriAdapter] Detectada limitação de console ("${res.error}"). Salvando em arquivo texto como fallback...`);
try {
const filePath = this.saveLongTextToFile(message, `fallback-${agentName}`);
const fallbackPayload = this.formatLongMessagePrompt(filePath, message);
res = await this.runMaestri(['ask', agentName, fallbackPayload]);
} catch (fbErr) {
console.error('[Gateway:MaestriAdapter] Falha no fallback de arquivo texto:', fbErr.message);
}
}
return {
ok: res.ok,
output: res.output || '',
error: res.error
};
}
}