406 lines
15 KiB
JavaScript
406 lines
15 KiB
JavaScript
import { execFile } from 'node:child_process';
|
|
import { promisify } from 'node:util';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { detectTerminalActivity } from '../utils/activity-detector.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' }
|
|
};
|
|
|
|
/**
|
|
* 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') {
|
|
if (/Permission required|ctrl\+f fullscreen|opencode|\bkilo\b/i.test(tail)) {
|
|
const command = (/\bopencode\b/i.test(tail) && !/\bkilo\b/i.test(tail)) ? 'opencode' : 'kilo';
|
|
return { preset: null, command, exitSequence: '/exit\\n' };
|
|
}
|
|
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.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 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']);
|
|
if (!res.ok) {
|
|
console.warn('[Gateway:MaestriAdapter] Falha ao executar maestri list:', res.error);
|
|
return [];
|
|
}
|
|
|
|
const lines = res.output.split('\n');
|
|
const rawList = [];
|
|
let isSelf = false;
|
|
|
|
for (const line of lines) {
|
|
const trimmed = line.trim();
|
|
if (trimmed.startsWith('You:')) {
|
|
isSelf = true;
|
|
} else if (trimmed.startsWith('Connected agents:')) {
|
|
isSelf = false;
|
|
} else if (trimmed.startsWith('- name:')) {
|
|
const match = trimmed.match(/- name:\s*"([^"]+)"/);
|
|
if (match) {
|
|
rawList.push({
|
|
name: match[1],
|
|
isSelf
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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);
|
|
return {
|
|
name: item.name,
|
|
isSelf: false,
|
|
status: activity.isPaused ? 'paused' : (activity.hasAiActivity ? 'active' : 'idle_shell'),
|
|
hasAiActivity: activity.hasAiActivity,
|
|
aiType: activity.aiType,
|
|
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) {
|
|
return {
|
|
name: item.name,
|
|
isSelf: false,
|
|
status: 'idle_shell',
|
|
hasAiActivity: false,
|
|
aiType: null,
|
|
shellType: 'unknown_shell',
|
|
isThinking: false,
|
|
isPaused: false,
|
|
pauseReason: null,
|
|
pauseResetTime: null,
|
|
hasInteractiveMenu: false,
|
|
interactiveMenu: null
|
|
};
|
|
}
|
|
})
|
|
);
|
|
|
|
return agents;
|
|
}
|
|
|
|
async checkAgent(agentName) {
|
|
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' };
|
|
}
|
|
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
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Reinicia ou recarrega um terminal gerenciado pelo Maestri em 2 níveis:
|
|
* 1) maestri recruit --replace (em Maestro Mode)
|
|
* 2) Fallback via --raw (\x03, saída limpa e relançamento do comando ou \n no shell)
|
|
*/
|
|
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);
|
|
|
|
let recruitArgs = null;
|
|
if (spec.preset) {
|
|
recruitArgs = ['recruit', trimmedAgent, '--preset', spec.preset, '--replace', trimmedAgent];
|
|
} else if (spec.command) {
|
|
recruitArgs = ['recruit', trimmedAgent, '--command', spec.command, '--replace', trimmedAgent];
|
|
}
|
|
|
|
const replaceRes = recruitArgs
|
|
? await this.runMaestri(recruitArgs)
|
|
: { ok: false, output: '', error: 'Sem preset ou comando mapeado' };
|
|
|
|
if (replaceRes.ok) {
|
|
await this.wait(this.restartDelayMs);
|
|
const updatedOutput = await this.checkAgent(trimmedAgent);
|
|
return {
|
|
ok: true,
|
|
method: 'recruit_replace',
|
|
output: updatedOutput || replaceRes.output || '',
|
|
error: null
|
|
};
|
|
}
|
|
|
|
const failRaw = (res, fallbackOut, fallbackErr) => ({
|
|
ok: false,
|
|
method: 'raw_restart',
|
|
output: res?.output || fallbackOut || '',
|
|
error: res?.error || fallbackErr
|
|
});
|
|
|
|
const interruptRes = await this.sendRawInput(trimmedAgent, '\\x03');
|
|
if (!interruptRes.ok) {
|
|
return failRaw(interruptRes, rawBefore, replaceRes.error || '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) {
|
|
if (midActivity.hasAiActivity) {
|
|
return {
|
|
ok: false,
|
|
method: 'raw_restart',
|
|
output: midOutput || '',
|
|
error: `Não foi possível encerrar a sessão ativa do assistente (${spec.command}) antes do relançamento.`
|
|
};
|
|
}
|
|
const launchRes = await this.sendRawInput(trimmedAgent, `${spec.command}\\n`);
|
|
if (!launchRes.ok) {
|
|
return failRaw(launchRes, midOutput, `Falha ao relançar ${spec.command} no terminal`);
|
|
}
|
|
await this.wait(this.restartDelayMs);
|
|
} else {
|
|
const promptRes = await this.sendRawInput(trimmedAgent, '\\n');
|
|
if (!promptRes.ok) {
|
|
return failRaw(promptRes, midOutput, 'Falha ao reativar prompt do terminal');
|
|
}
|
|
}
|
|
|
|
const finalOutput = await this.checkAgent(trimmedAgent);
|
|
return {
|
|
ok: true,
|
|
method: 'raw_restart',
|
|
output: finalOutput || 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
|
|
};
|
|
}
|
|
}
|