@ericnunes/frame-code-cli 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +139 -0
  2. package/README.md +196 -0
  3. package/dist/agent-runtime/AgentFacade.js +33 -0
  4. package/dist/agent-runtime/context/hooks/compressionHook.js +56 -0
  5. package/dist/agent-runtime/context/hooks/index.js +5 -0
  6. package/dist/agent-runtime/context/project-rules/loader.js +72 -0
  7. package/dist/agent-runtime/context/system-prompts/index.js +5 -0
  8. package/dist/agent-runtime/context/system-prompts/loader.js +88 -0
  9. package/dist/agent-runtime/flows/templates/ReactAgentFlow.js +49 -0
  10. package/dist/agent-runtime/index.js +18 -0
  11. package/dist/agent-runtime/registry/AgentRegistry.js +93 -0
  12. package/dist/agent-runtime/registry/agentParser.js +515 -0
  13. package/dist/agent-runtime/registry/enums/agentType.enum.js +8 -0
  14. package/dist/agent-runtime/registry/index.js +20 -0
  15. package/dist/agent-runtime/registry/initialization.js +53 -0
  16. package/dist/agent-runtime/registry/interfaces/agentDependencies.interface.js +2 -0
  17. package/dist/agent-runtime/registry/interfaces/agentMetadata.interface.js +2 -0
  18. package/dist/agent-runtime/registry/interfaces/agentRegistry.interface.js +2 -0
  19. package/dist/app/bootstrap.js +22 -0
  20. package/dist/app/cli.js +31 -0
  21. package/dist/app/index.js +9 -0
  22. package/dist/cli/commands/autonomous.js +181 -0
  23. package/dist/cli/commands/index.js +11 -0
  24. package/dist/cli/commands/interactive.js +172 -0
  25. package/dist/cli/commands/memory.js +149 -0
  26. package/dist/cli/commands/multi-agent.js +131 -0
  27. package/dist/cli/index.js +18 -0
  28. package/dist/cli/input/images/attachments.js +173 -0
  29. package/dist/cli/input/images/imageInput.js +77 -0
  30. package/dist/cli/input/images/readImageAttachment.js +56 -0
  31. package/dist/cli/input/index.js +14 -0
  32. package/dist/cli/input/reader.js +26 -0
  33. package/dist/content/agents/README.md +324 -0
  34. package/dist/content/agents/architect.md +95 -0
  35. package/dist/content/agents/builder.md +85 -0
  36. package/dist/content/agents/code-agent.md +123 -0
  37. package/dist/content/agents/supervisor.md +63 -0
  38. package/dist/index.js +25 -0
  39. package/dist/infrastructure/compression/CompressionManager.js +315 -0
  40. package/dist/infrastructure/compression/LLMCompressionService.js +211 -0
  41. package/dist/infrastructure/compression/index.js +11 -0
  42. package/dist/infrastructure/compression/promptBuilder.js +132 -0
  43. package/dist/infrastructure/config/agentConfig.interface.js +2 -0
  44. package/dist/infrastructure/config/agentConfig.js +134 -0
  45. package/dist/infrastructure/config/config.interface.js +2 -0
  46. package/dist/infrastructure/config/config.js +112 -0
  47. package/dist/infrastructure/config/index.js +6 -0
  48. package/dist/infrastructure/logging/index.js +5 -0
  49. package/dist/infrastructure/logging/logger.interface.js +2 -0
  50. package/dist/infrastructure/logging/logger.js +33 -0
  51. package/dist/infrastructure/logging/raw-output-logger.js +35 -0
  52. package/dist/infrastructure/skills/index.js +5 -0
  53. package/dist/infrastructure/skills/loader.js +104 -0
  54. package/dist/infrastructure/telemetry/index.js +9 -0
  55. package/dist/infrastructure/telemetry/telemetry.interface.js +2 -0
  56. package/dist/infrastructure/telemetry/telemetryConfig.js +30 -0
  57. package/dist/infrastructure/telemetry/traceEventFormatter.js +90 -0
  58. package/dist/infrastructure/telemetry/traceSinkConsole.js +17 -0
  59. package/dist/scripts/_validate/telemetry-autonomous.js +23 -0
  60. package/dist/scripts/_validate/telemetry-multi-agent.js +50 -0
  61. package/dist/scripts/_validate/test-agents-md-dynamic-dir.js +104 -0
  62. package/dist/scripts/_validate/test-agents-md-injection.js +125 -0
  63. package/dist/scripts/_validate/test-agents-md-loader.js +71 -0
  64. package/dist/scripts/_validate/test-agents-md-priority.js +121 -0
  65. package/dist/scripts/_validate/test-chrome-mcp-agent.js +89 -0
  66. package/dist/tools/index.js +19 -0
  67. package/dist/tools/mcp/discoverer.js +95 -0
  68. package/dist/tools/mcp/index.js +9 -0
  69. package/dist/tools/mcp/loader.js +36 -0
  70. package/dist/tools/mcp/mcpConfig.interface.js +2 -0
  71. package/dist/tools/mcp/mcpMetadata.js +2 -0
  72. package/dist/tools/mcp/register.js +269 -0
  73. package/dist/tools/native/capabilities.js +155 -0
  74. package/dist/tools/native/file-outline.js +301 -0
  75. package/dist/tools/native/index.js +20 -0
  76. package/dist/tools/native/list-directory.js +148 -0
  77. package/dist/tools/native/read-image.js +140 -0
  78. package/dist/tools/registry/ToolInitializer.js +62 -0
  79. package/dist/tools/registry/index.js +11 -0
  80. package/dist/tools/registry/toolFilter.js +52 -0
  81. package/dist/tools/registry/toolRegistry.interface.js +2 -0
  82. package/package.json +81 -0
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initializeAgents = initializeAgents;
4
+ exports.getDefaultAgent = getDefaultAgent;
5
+ exports.listAgentsAvailable = listAgentsAvailable;
6
+ const AgentRegistry_1 = require("./AgentRegistry");
7
+ const logger_1 = require("../../infrastructure/logging/logger");
8
+ async function initializeAgents() {
9
+ const registry = AgentRegistry_1.AgentRegistry.getInstance();
10
+ logger_1.logger.info('[Agents] Inicializando sistema de agentes...');
11
+ logger_1.logger.debug('[Agents] Diretório: .code/agents/');
12
+ const count = await registry.load();
13
+ if (count === 0) {
14
+ logger_1.logger.warn('[Agents] Nenhum agente encontrado em .code/agents/');
15
+ logger_1.logger.info('[Agents] Crie .code/agents/NOME_AGENTE/AGENT.md para definir novos agentes');
16
+ }
17
+ else {
18
+ const stats = registry.getStats();
19
+ logger_1.logger.info(`[Agents] ${count} agentes carregados:`);
20
+ logger_1.logger.info(`[Agents] - Main agents: ${stats.mainAgents}`);
21
+ logger_1.logger.info(`[Agents] - Sub agents: ${stats.subAgents}`);
22
+ logger_1.logger.info(`[Agents] - Supervisores: ${stats.supervisors}`);
23
+ }
24
+ return count;
25
+ }
26
+ function getDefaultAgent(preferredAgent) {
27
+ const registry = AgentRegistry_1.AgentRegistry.getInstance();
28
+ if (preferredAgent && registry.has(preferredAgent)) {
29
+ return preferredAgent;
30
+ }
31
+ const mainAgents = registry.listByType('main-agent');
32
+ if (mainAgents.length > 0) {
33
+ return mainAgents[0].name;
34
+ }
35
+ throw new Error('Nenhum agente main-agent disponível');
36
+ }
37
+ function listAgentsAvailable() {
38
+ const registry = AgentRegistry_1.AgentRegistry.getInstance();
39
+ const agents = registry.listSummaries();
40
+ if (agents.length === 0) {
41
+ return 'Nenhum agente disponível.';
42
+ }
43
+ const lines = ['Agentes Disponíveis:', ''];
44
+ for (const agent of agents) {
45
+ const typeLabel = agent.type === 'main-agent' ? '[MAIN]' : '[SUB]';
46
+ const supervisorLabel = agent.canBeSupervisor ? ' [SUPERVISOR]' : '';
47
+ const keywords = agent.keywords.length > 0
48
+ ? ' (keywords: ' + agent.keywords.join(', ') + ')'
49
+ : '';
50
+ lines.push(' ' + typeLabel + supervisorLabel + ' ' + agent.name + ': ' + agent.description + keywords);
51
+ }
52
+ return lines.join('\n');
53
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bootstrap = bootstrap;
4
+ exports.createDefaultTelemetry = createDefaultTelemetry;
5
+ const config_1 = require("../infrastructure/config");
6
+ const logger_1 = require("../infrastructure/logging/logger");
7
+ const tools_1 = require("../tools");
8
+ const agent_runtime_1 = require("../agent-runtime");
9
+ const telemetry_1 = require("../infrastructure/telemetry");
10
+ async function bootstrap() {
11
+ logger_1.logger.info('[Bootstrap] Inicializando frame-code-cli...');
12
+ await (0, config_1.loadConfig)();
13
+ logger_1.logger.debug('[Bootstrap] Configuração carregada');
14
+ await (0, tools_1.initializeTools)();
15
+ logger_1.logger.debug('[Bootstrap] Ferramentas inicializadas');
16
+ const agentCount = await (0, agent_runtime_1.initializeAgents)();
17
+ logger_1.logger.info(`[Bootstrap] ${agentCount} agentes carregados`);
18
+ logger_1.logger.info('[Bootstrap] Inicialização concluída');
19
+ }
20
+ function createDefaultTelemetry() {
21
+ return (0, telemetry_1.createCliTelemetry)();
22
+ }
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.program = void 0;
5
+ exports.runCli = runCli;
6
+ const commander_1 = require("commander");
7
+ const interactive_1 = require("../cli/commands/interactive");
8
+ const autonomous_1 = require("../cli/commands/autonomous");
9
+ const memory_1 = require("../cli/commands/memory");
10
+ const multi_agent_1 = require("../cli/commands/multi-agent");
11
+ exports.program = new commander_1.Command()
12
+ .name('frame-code-cli')
13
+ .description('CLI para frame-code com agentes')
14
+ .version('0.0.1');
15
+ exports.program.addCommand(interactive_1.interactiveCommand);
16
+ exports.program.addCommand((0, autonomous_1.createAutonomousCommand)());
17
+ exports.program.addCommand(memory_1.memoryCommand);
18
+ exports.program.addCommand((0, multi_agent_1.createMultiAgentCommand)());
19
+ function runCli(argv = process.argv) {
20
+ try {
21
+ const nextArgv = [...argv];
22
+ if (nextArgv.length <= 2) {
23
+ nextArgv.push('interactive');
24
+ }
25
+ exports.program.parse(nextArgv);
26
+ }
27
+ catch (error) {
28
+ console.error('Erro:', error);
29
+ process.exit(1);
30
+ }
31
+ }
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createDefaultTelemetry = exports.bootstrap = exports.program = exports.runCli = void 0;
4
+ var cli_1 = require("./cli");
5
+ Object.defineProperty(exports, "runCli", { enumerable: true, get: function () { return cli_1.runCli; } });
6
+ Object.defineProperty(exports, "program", { enumerable: true, get: function () { return cli_1.program; } });
7
+ var bootstrap_1 = require("./bootstrap");
8
+ Object.defineProperty(exports, "bootstrap", { enumerable: true, get: function () { return bootstrap_1.bootstrap; } });
9
+ Object.defineProperty(exports, "createDefaultTelemetry", { enumerable: true, get: function () { return bootstrap_1.createDefaultTelemetry; } });
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.processAutonomousInput = processAutonomousInput;
4
+ exports.createAutonomousCommand = createAutonomousCommand;
5
+ const commander_1 = require("commander");
6
+ const fs_1 = require("fs");
7
+ const logger_1 = require("../../infrastructure/logging/logger");
8
+ const frame_agent_sdk_1 = require("@ericnunes/frame-agent-sdk");
9
+ const tools_1 = require("../../tools");
10
+ const config_1 = require("../../infrastructure/config");
11
+ const reader_1 = require("../input/reader");
12
+ const telemetry_1 = require("../../infrastructure/telemetry");
13
+ const attachments_1 = require("../input/images/attachments");
14
+ const agent_runtime_1 = require("../../agent-runtime");
15
+ async function processAutonomousInput(input, options) {
16
+ try {
17
+ logger_1.logger.info('[Autonomous] Iniciando processamento autônomo');
18
+ if (options.verbose) {
19
+ logger_1.logger.info(`[Autonomous] Input recebido: ${input.substring(0, 200)}...`);
20
+ }
21
+ const { trace, telemetry } = (0, telemetry_1.createCliTelemetry)();
22
+ const registry = agent_runtime_1.AgentRegistry.getInstance();
23
+ let agentName;
24
+ if (options.agent) {
25
+ if (!registry.has(options.agent)) {
26
+ throw new Error(`Agente "${options.agent}" não encontrado. Agentes disponíveis: ${registry.listSummaries().map(a => a.name).join(', ')}`);
27
+ }
28
+ const agent = registry.getMetadata(options.agent);
29
+ if (agent?.type !== 'main-agent') {
30
+ throw new Error(`Agente "${options.agent}" é do tipo "sub-agent" e não pode ser usado diretamente. Use um main-agent: ${registry.listByType('main-agent').map(a => a.name).join(', ')}`);
31
+ }
32
+ agentName = options.agent;
33
+ logger_1.logger.info(`[Autonomous] Usando agente especificado: ${agentName}`);
34
+ }
35
+ else {
36
+ agentName = (0, agent_runtime_1.getDefaultAgent)('code-agent');
37
+ logger_1.logger.info(`[Autonomous] Usando agente padrão: ${agentName}`);
38
+ }
39
+ const graph = await registry.createEngine(agentName, {
40
+ trace,
41
+ telemetry
42
+ });
43
+ const imagePaths = options._imagePaths ?? [];
44
+ const imageDetail = options.imageDetail ?? 'auto';
45
+ const imageHint = imagePaths.length > 0
46
+ ? `Imagens disponiveis (paths locais):\n${imagePaths.map((p) => `- ${p}`).join('\n')}\n\nSe precisar enxergar, chame a tool read_image com source=\"path\" e path do arquivo.`
47
+ : '';
48
+ const messages = [];
49
+ if (imageHint && imageHint.trim().length > 0) {
50
+ messages.push({ role: 'system', content: imageHint });
51
+ }
52
+ messages.push({ role: 'user', content: input });
53
+ logger_1.logger.debug('[Autonomous] Mensagens iniciais:', JSON.stringify(messages, null, 2));
54
+ const initialState = {
55
+ messages,
56
+ data: {
57
+ ...(options._runId ? { runId: options._runId } : {}),
58
+ ...(imagePaths.length ? { imagePaths, imageDetail } : {})
59
+ },
60
+ status: frame_agent_sdk_1.GraphStatus.RUNNING
61
+ };
62
+ const result = await graph.execute(initialState);
63
+ logger_1.logger.debug(`[Autonomous] Status final: ${result.status}`);
64
+ logger_1.logger.debug(`[Autonomous] lastToolCall:`, result.state.lastToolCall);
65
+ if (result.status === frame_agent_sdk_1.GraphStatus.ERROR) {
66
+ throw new Error(`Erro durante execução: ${result.state.logs?.join('\n') || 'Erro desconhecido'}`);
67
+ }
68
+ if (result.status !== frame_agent_sdk_1.GraphStatus.FINISHED) {
69
+ logger_1.logger.warn(`[Autonomous] Status não finalizado: ${result.status}`);
70
+ return 'Processamento concluído com status: ' + result.status;
71
+ }
72
+ const lastToolCall = result.state.lastToolCall;
73
+ if (lastToolCall?.toolName === 'final_answer') {
74
+ const answer = lastToolCall?.params?.answer;
75
+ if (typeof answer === 'string' && answer.trim().length > 0) {
76
+ return answer;
77
+ }
78
+ }
79
+ const lastAssistantMessage = result.state.messages
80
+ .filter((msg) => msg.role === 'assistant')
81
+ .pop();
82
+ return lastAssistantMessage?.content || 'Processamento concluído sem resposta';
83
+ }
84
+ catch (error) {
85
+ logger_1.logger.error('[Autonomous] Erro no processamento:', error);
86
+ throw error;
87
+ }
88
+ }
89
+ function createAutonomousCommand() {
90
+ const command = new commander_1.Command('autonomous');
91
+ const collect = (value, previous) => {
92
+ return [...(previous ?? []), value];
93
+ };
94
+ command
95
+ .description('Executar frame-code-cli em modo autônomo sem interação humana')
96
+ .argument('[agent]', 'Agente a ser usado (ex: supervisor, code-agent, chrome-mcp-agent)')
97
+ .argument('[additional-input]', 'Texto adicional com prioridade sobre o arquivo de entrada')
98
+ .option('-i, --input-file <file>', 'Arquivo de entrada com o prompt')
99
+ .option('-o, --output-file <file>', 'Arquivo de saída para a resposta')
100
+ .option('-l, --log-file <file>', 'Arquivo de log detalhado')
101
+ .option('-v, --verbose', 'Modo verboso com logs detalhados')
102
+ .option('-a, --agent <name>', 'Agente a ser usado (alternativa ao argumento posicional)')
103
+ .option('--image <path>', 'Caminho de imagem local (pode repetir)', collect, [])
104
+ .option('--image-detail <low|high|auto>', 'Nivel de detalhe para imagem (low|high|auto)', 'auto')
105
+ .action(async (agentArg, additionalInput, options) => {
106
+ try {
107
+ await (0, config_1.loadConfig)();
108
+ await (0, tools_1.initializeTools)();
109
+ await (0, agent_runtime_1.initializeAgents)();
110
+ const registry = agent_runtime_1.AgentRegistry.getInstance();
111
+ let resolvedAgent = options.agent;
112
+ let resolvedInput = additionalInput;
113
+ if (!resolvedAgent && agentArg) {
114
+ const agentMetadata = registry.getMetadata(agentArg);
115
+ if (agentMetadata && agentMetadata.type === 'main-agent') {
116
+ resolvedAgent = agentArg;
117
+ }
118
+ else {
119
+ resolvedInput = agentArg;
120
+ }
121
+ }
122
+ if (resolvedAgent && !resolvedInput && agentArg) {
123
+ resolvedInput = agentArg;
124
+ }
125
+ if (resolvedAgent) {
126
+ options.agent = resolvedAgent;
127
+ }
128
+ const input = await (0, reader_1.readCliInput)({ inputFile: options.inputFile, additionalInput: resolvedInput });
129
+ if (!input || input.trim().length === 0) {
130
+ throw new Error('Input vazio. Forneça uma tarefa para executar.');
131
+ }
132
+ if (options.image && options.image.length > 0) {
133
+ await (0, attachments_1.cleanupAttachmentsRoot)((0, attachments_1.getAttachmentsCleanupConfigFromEnv)());
134
+ const staged = await (0, attachments_1.stageImageAttachments)({ imagePaths: options.image });
135
+ options._runId = staged.runId;
136
+ options._imagePaths = staged.stagedPaths;
137
+ }
138
+ if (options.agent) {
139
+ logger_1.logger.info(`[Autonomous] Usando agente: ${options.agent}`);
140
+ }
141
+ else {
142
+ logger_1.logger.info(`[Autonomous] Usando agente padrão`);
143
+ }
144
+ if (resolvedInput) {
145
+ logger_1.logger.info(`[Autonomous] Input prioritário: ${resolvedInput.substring(0, 100)}...`);
146
+ }
147
+ logger_1.logger.debug('[Autonomous] Iniciando processamento do input');
148
+ logger_1.logger.debug(`[Autonomous] Input: "${input.substring(0, 200)}"`);
149
+ const result = await processAutonomousInput(input, options);
150
+ logger_1.logger.debug(`[Autonomous] Processamento concluído, resultado: ${result.substring(0, 50)}...`);
151
+ if (options.outputFile) {
152
+ logger_1.logger.info(`[Autonomous] Escrevendo output em: ${options.outputFile}`);
153
+ (0, fs_1.writeFileSync)(options.outputFile, result, 'utf-8');
154
+ }
155
+ else {
156
+ logger_1.logger.debug('[Autonomous] Imprimindo resultado no console');
157
+ console.log(result);
158
+ }
159
+ if (options.logFile) {
160
+ const logContent = 'Logs detalhados não implementados';
161
+ (0, fs_1.writeFileSync)(options.logFile, logContent, 'utf-8');
162
+ }
163
+ logger_1.logger.info('[Autonomous] Processamento autônomo concluído com sucesso');
164
+ process.exit(0);
165
+ }
166
+ catch (error) {
167
+ logger_1.logger.error('[Autonomous] Erro fatal:', error);
168
+ const errorMessage = error instanceof Error ? error.message : 'Erro desconhecido';
169
+ if (options.outputFile) {
170
+ logger_1.logger.debug(`[Autonomous] Escrevendo erro no arquivo: ${options.outputFile}`);
171
+ (0, fs_1.writeFileSync)(options.outputFile, `## Erro durante processamento\n\n${errorMessage}`, 'utf-8');
172
+ }
173
+ else {
174
+ logger_1.logger.debug('[Autonomous] Imprimindo erro no console');
175
+ console.error('Erro:', errorMessage);
176
+ }
177
+ process.exit(1);
178
+ }
179
+ });
180
+ return command;
181
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createMemoryCommand = exports.createMultiAgentCommand = exports.createInteractiveCommand = exports.createAutonomousCommand = void 0;
4
+ var autonomous_1 = require("./autonomous");
5
+ Object.defineProperty(exports, "createAutonomousCommand", { enumerable: true, get: function () { return autonomous_1.createAutonomousCommand; } });
6
+ var interactive_1 = require("./interactive");
7
+ Object.defineProperty(exports, "createInteractiveCommand", { enumerable: true, get: function () { return interactive_1.createInteractiveCommand; } });
8
+ var multi_agent_1 = require("./multi-agent");
9
+ Object.defineProperty(exports, "createMultiAgentCommand", { enumerable: true, get: function () { return multi_agent_1.createMultiAgentCommand; } });
10
+ var memory_1 = require("./memory");
11
+ Object.defineProperty(exports, "createMemoryCommand", { enumerable: true, get: function () { return memory_1.createMemoryCommand; } });
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.interactiveCommand = void 0;
37
+ exports.createInteractiveCommand = createInteractiveCommand;
38
+ const commander_1 = require("commander");
39
+ const readline = __importStar(require("readline"));
40
+ const logger_1 = require("../../infrastructure/logging/logger");
41
+ const frame_agent_sdk_1 = require("@ericnunes/frame-agent-sdk");
42
+ const tools_1 = require("../../tools");
43
+ const config_1 = require("../../infrastructure/config");
44
+ const telemetry_1 = require("../../infrastructure/telemetry");
45
+ const attachments_1 = require("../input/images/attachments");
46
+ const agent_runtime_1 = require("../../agent-runtime");
47
+ let interactiveExecuted = false;
48
+ function createInteractiveCommand() {
49
+ const command = new commander_1.Command('interactive');
50
+ command
51
+ .description('Iniciar modo interativo')
52
+ .option('--agent <name>', 'Agente a usar (ex: supervisor, chrome-mcp-agent, code-agent)', 'chrome-mcp-agent')
53
+ .option('--image <path>', 'Caminho de imagem local (pode repetir)', (value, previous) => [...(previous ?? []), value], [])
54
+ .option('--image-detail <low|high|auto>', 'Nivel de detalhe para imagem (low|high|auto)', 'auto')
55
+ .action(async (options) => {
56
+ try {
57
+ if (interactiveExecuted) {
58
+ return;
59
+ }
60
+ interactiveExecuted = true;
61
+ await (0, config_1.loadConfig)();
62
+ console.log('.frame-agent CLI');
63
+ console.log('==============================================');
64
+ console.log('Modo Chat Interativo');
65
+ console.log('Dica: Digite suas perguntas ou "sair" para encerrar');
66
+ console.log('');
67
+ let imagePaths = [];
68
+ let runId;
69
+ const imageDetail = options?.imageDetail ?? 'auto';
70
+ if (options?.image && options.image.length > 0) {
71
+ await (0, attachments_1.cleanupAttachmentsRoot)((0, attachments_1.getAttachmentsCleanupConfigFromEnv)());
72
+ const staged = await (0, attachments_1.stageImageAttachments)({ imagePaths: options.image });
73
+ runId = staged.runId;
74
+ imagePaths = staged.stagedPaths;
75
+ }
76
+ const imageHint = imagePaths.length > 0
77
+ ? `Imagens disponiveis (paths locais):\n${imagePaths.map((p) => `- ${p}`).join('\n')}\n\nSe precisar enxergar, chame a tool read_image com source=\"path\" e path do arquivo.`
78
+ : '';
79
+ let currentState = {
80
+ messages: [...(imageHint ? [{ role: 'system', content: imageHint }] : [])],
81
+ data: {
82
+ ...(runId ? { runId } : {}),
83
+ ...(imagePaths.length ? { imagePaths, imageDetail } : {}),
84
+ },
85
+ status: frame_agent_sdk_1.GraphStatus.RUNNING
86
+ };
87
+ const rl = readline.createInterface({
88
+ input: process.stdin,
89
+ output: process.stdout,
90
+ });
91
+ console.log('Inicializando ferramentas...');
92
+ await (0, tools_1.initializeTools)();
93
+ console.log('Inicializando agente...');
94
+ const { trace, telemetry } = (0, telemetry_1.createCliTelemetry)();
95
+ const registry = agent_runtime_1.AgentRegistry.getInstance();
96
+ const agentName = (0, agent_runtime_1.getDefaultAgent)(options?.agent);
97
+ const graph = await registry.createEngine(agentName, {
98
+ trace,
99
+ telemetry
100
+ });
101
+ console.log('Agente pronto!');
102
+ console.log('');
103
+ const processQuestion = async (question) => {
104
+ try {
105
+ const newState = {
106
+ messages: [...currentState.messages, { role: 'user', content: question }],
107
+ data: { ...currentState.data },
108
+ status: frame_agent_sdk_1.GraphStatus.RUNNING
109
+ };
110
+ console.log('Processando...');
111
+ const result = await graph.execute(newState);
112
+ currentState.messages = result.state.messages;
113
+ currentState.data = result.state.data;
114
+ currentState.status = result.state.status;
115
+ if (result.status === frame_agent_sdk_1.GraphStatus.FINISHED) {
116
+ }
117
+ else if (result.status === frame_agent_sdk_1.GraphStatus.ERROR) {
118
+ console.log('\n❌ Erro na execução: ' + (currentState.logs?.join('\n') || 'Erro desconhecido'));
119
+ }
120
+ }
121
+ catch (error) {
122
+ logger_1.logger.error('Erro no processamento da questão:', error);
123
+ console.log('\n❌ Ocorreu um erro ao processar sua solicitação.');
124
+ }
125
+ };
126
+ let promptActive = false;
127
+ const showPrompt = () => {
128
+ if (promptActive) {
129
+ return;
130
+ }
131
+ promptActive = true;
132
+ rl.question('Você: ', async (input) => {
133
+ promptActive = false;
134
+ const trimmedInput = input.trim();
135
+ if (trimmedInput.toLowerCase() === 'sair' ||
136
+ trimmedInput.toLowerCase() === 'exit' ||
137
+ trimmedInput.toLowerCase() === 'quit') {
138
+ console.log('Até mais! Obrigado por usar o frame-agent.');
139
+ rl.close();
140
+ return;
141
+ }
142
+ if (trimmedInput === '') {
143
+ showPrompt();
144
+ return;
145
+ }
146
+ try {
147
+ await processQuestion(trimmedInput);
148
+ }
149
+ catch (error) {
150
+ logger_1.logger.error('Erro em processQuestion:', error);
151
+ }
152
+ console.log('\n' + '='.repeat(50) + '\n');
153
+ showPrompt();
154
+ });
155
+ };
156
+ console.log('Bem-vindo ao Chat frame-agent! Como posso ajudar?');
157
+ showPrompt();
158
+ rl.on('close', () => {
159
+ console.log('\nSessão encerrada. Até a próxima!');
160
+ process.exit(0);
161
+ });
162
+ rl.removeAllListeners('line');
163
+ rl.removeAllListeners('question');
164
+ }
165
+ catch (error) {
166
+ logger_1.logger.error('Erro ao iniciar modo interativo:', error);
167
+ process.exit(1);
168
+ }
169
+ });
170
+ return command;
171
+ }
172
+ exports.interactiveCommand = createInteractiveCommand();
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.memoryCommand = void 0;
4
+ exports.createMemoryCommand = createMemoryCommand;
5
+ const commander_1 = require("commander");
6
+ const compression_1 = require("../../infrastructure/compression");
7
+ const logger_1 = require("../../infrastructure/logging/logger");
8
+ const config_1 = require("../../infrastructure/config");
9
+ function createMemoryStatusCommand() {
10
+ const command = new commander_1.Command('status');
11
+ command
12
+ .description('Mostrar status atual da memória e compressão')
13
+ .action(async () => {
14
+ try {
15
+ const config = await (0, config_1.loadConfig)();
16
+ if (!config.compression?.enabled) {
17
+ console.log('❌ Compressão de memória está desabilitada');
18
+ console.log('💡 Habilite com COMPRESSION_ENABLED=true no .env');
19
+ return;
20
+ }
21
+ const compressionManager = new compression_1.CompressionManager(config.compression);
22
+ const stats = compressionManager.getCompressionStats();
23
+ console.log('📊 Status da Memória e Compressão');
24
+ console.log('='.repeat(40));
25
+ console.log(`✅ Compressão: ${stats.enabled ? 'Habilitada' : 'Desabilitada'}`);
26
+ console.log(`📈 Threshold: ${(stats.threshold * 100).toFixed(0)}%`);
27
+ console.log(`🔄 Compressões atuais: ${stats.currentCompressions}/${stats.maxCompressions}`);
28
+ console.log(`📝 Total de compressões realizadas: ${stats.compressionCount}`);
29
+ console.log(`💾 Persistência: ${config.compression.persist ? 'Habilitada' : 'Desabilitada'}`);
30
+ console.log(`📊 Logging: ${config.compression.logging ? 'Habilitado' : 'Desabilitado'}`);
31
+ if (stats.compressionHistory.length > 0) {
32
+ console.log('\n📜 Histórico de Compressões:');
33
+ stats.compressionHistory.forEach((comp, index) => {
34
+ console.log(` ${index + 1}. ${comp.preview} (${comp.length} caracteres)`);
35
+ });
36
+ }
37
+ else {
38
+ console.log('\n📜 Nenhuma compressão realizada ainda');
39
+ }
40
+ }
41
+ catch (error) {
42
+ logger_1.logger.error('[MemoryCommand] Erro ao obter status:', error);
43
+ console.error('❌ Erro ao obter status da memória');
44
+ }
45
+ });
46
+ return command;
47
+ }
48
+ function createMemoryCompressCommand() {
49
+ const command = new commander_1.Command('compress');
50
+ command
51
+ .description('Forçar compressão manual da memória')
52
+ .action(async () => {
53
+ try {
54
+ const config = await (0, config_1.loadConfig)();
55
+ if (!config.compression?.enabled) {
56
+ console.log('❌ Compressão de memória está desabilitada');
57
+ console.log('💡 Habilite com COMPRESSION_ENABLED=true no .env');
58
+ return;
59
+ }
60
+ console.log('🔄 Iniciando compressão manual...');
61
+ const compressionManager = new compression_1.CompressionManager(config.compression);
62
+ const statsBefore = compressionManager.getCompressionStats();
63
+ console.log(`📊 Antes: ${statsBefore.currentCompressions}/${statsBefore.maxCompressions} compressões`);
64
+ console.log('💡 Para compressão manual during conversa, use o modo interativo');
65
+ console.log(' A compressão automática ocorrerá quando necessário');
66
+ }
67
+ catch (error) {
68
+ logger_1.logger.error('[MemoryCommand] Erro na compressão manual:', error);
69
+ console.error('❌ Erro na compressão manual');
70
+ }
71
+ });
72
+ return command;
73
+ }
74
+ function createMemoryClearCommand() {
75
+ const command = new commander_1.Command('clear');
76
+ command
77
+ .description('Limpar todo o histórico de compressões')
78
+ .action(async () => {
79
+ try {
80
+ const config = await (0, config_1.loadConfig)();
81
+ if (!config.compression?.enabled) {
82
+ console.log('❌ Compressão de memória está desabilitada');
83
+ return;
84
+ }
85
+ const compressionManager = new compression_1.CompressionManager(config.compression);
86
+ const statsBefore = compressionManager.getCompressionStats();
87
+ if (statsBefore.currentCompressions === 0) {
88
+ console.log('📝 Não há compressões para limpar');
89
+ return;
90
+ }
91
+ console.log(`🗑️ Limpando ${statsBefore.currentCompressions} compressões...`);
92
+ compressionManager.clearCompressions();
93
+ console.log('✅ Histórico de compressões limpo com sucesso');
94
+ console.log('💾 Arquivo de persistência removido (se existia)');
95
+ }
96
+ catch (error) {
97
+ logger_1.logger.error('[MemoryCommand] Erro ao limpar compressões:', error);
98
+ console.error('❌ Erro ao limpar compressões');
99
+ }
100
+ });
101
+ return command;
102
+ }
103
+ function createMemoryConfigCommand() {
104
+ const command = new commander_1.Command('config');
105
+ command
106
+ .description('Mostrar configuração atual de compressão')
107
+ .action(async () => {
108
+ try {
109
+ const config = await (0, config_1.loadConfig)();
110
+ console.log('⚙️ Configuração de Compressão');
111
+ console.log('='.repeat(30));
112
+ if (!config.compression) {
113
+ console.log('❌ Nenhuma configuração de compressão encontrada');
114
+ return;
115
+ }
116
+ console.log(`enabled: ${config.compression.enabled}`);
117
+ console.log(`threshold: ${config.compression.threshold} (${(config.compression.threshold * 100).toFixed(0)}%)`);
118
+ console.log(`maxCount: ${config.compression.maxCount}`);
119
+ console.log(`maxTokens: ${config.compression.maxTokens}`);
120
+ console.log(`model: ${config.compression.model || 'padrão do LLM'}`);
121
+ console.log(`logging: ${config.compression.logging}`);
122
+ console.log(`persist: ${config.compression.persist}`);
123
+ console.log('\n📝 Variáveis de ambiente correspondentes:');
124
+ console.log('COMPRESSION_ENABLED');
125
+ console.log('COMPRESSION_THRESHOLD');
126
+ console.log('COMPRESSION_MAX_COUNT');
127
+ console.log('COMPRESSION_MAX_TOKENS');
128
+ console.log('COMPRESSION_MODEL');
129
+ console.log('COMPRESSION_LOGGING');
130
+ console.log('COMPRESSION_PERSIST');
131
+ }
132
+ catch (error) {
133
+ logger_1.logger.error('[MemoryCommand] Erro ao mostrar configuração:', error);
134
+ console.error('❌ Erro ao mostrar configuração');
135
+ }
136
+ });
137
+ return command;
138
+ }
139
+ function createMemoryCommand() {
140
+ const command = new commander_1.Command('memory');
141
+ command
142
+ .description('Gerenciar memória e compressão da CLI');
143
+ command.addCommand(createMemoryStatusCommand());
144
+ command.addCommand(createMemoryCompressCommand());
145
+ command.addCommand(createMemoryClearCommand());
146
+ command.addCommand(createMemoryConfigCommand());
147
+ return command;
148
+ }
149
+ exports.memoryCommand = createMemoryCommand();