@ericnunes/frame-code-cli 0.0.2 → 0.0.5

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 (73) hide show
  1. package/dist/agent-runtime/index.js +0 -1
  2. package/dist/agent-runtime/registry/AgentRegistry.js +108 -36
  3. package/dist/agent-runtime/registry/index.js +1 -11
  4. package/dist/app/cli.js +3 -5
  5. package/dist/cli/commands/autonomous.js +15 -12
  6. package/dist/cli/commands/interactive.js +71 -149
  7. package/dist/cli/commands/memory.js +247 -76
  8. package/dist/content/agents/README.md +36 -32
  9. package/dist/content/agents/architect.md +1 -1
  10. package/dist/content/agents/builder.md +10 -14
  11. package/dist/content/agents/code-agent.md +1 -95
  12. package/dist/index.js +0 -6
  13. package/dist/infrastructure/config/config.js +40 -0
  14. package/dist/infrastructure/telemetry/cliTelemetry.js +39 -0
  15. package/dist/tools/index.js +0 -2
  16. package/dist/tools/registry/ToolInitializer.js +15 -55
  17. package/dist/tools/registry/index.js +1 -7
  18. package/package.json +11 -23
  19. package/dist/agent-runtime/AgentFacade.js +0 -33
  20. package/dist/agent-runtime/context/hooks/compressionHook.js +0 -56
  21. package/dist/agent-runtime/context/hooks/index.js +0 -5
  22. package/dist/agent-runtime/context/project-rules/loader.js +0 -72
  23. package/dist/agent-runtime/context/system-prompts/index.js +0 -5
  24. package/dist/agent-runtime/context/system-prompts/loader.js +0 -88
  25. package/dist/agent-runtime/flows/templates/ReactAgentFlow.js +0 -49
  26. package/dist/agent-runtime/registry/agentParser.js +0 -515
  27. package/dist/agent-runtime/registry/enums/agentType.enum.js +0 -8
  28. package/dist/agent-runtime/registry/interfaces/agentDependencies.interface.js +0 -2
  29. package/dist/agent-runtime/registry/interfaces/agentRegistry.interface.js +0 -2
  30. package/dist/app/bootstrap.js +0 -22
  31. package/dist/app/index.js +0 -9
  32. package/dist/cli/commands/index.js +0 -11
  33. package/dist/cli/commands/multi-agent.js +0 -131
  34. package/dist/cli/index.js +0 -18
  35. package/dist/cli/input/images/imageInput.js +0 -77
  36. package/dist/cli/input/images/readImageAttachment.js +0 -56
  37. package/dist/cli/input/index.js +0 -14
  38. package/dist/infrastructure/compression/CompressionManager.js +0 -315
  39. package/dist/infrastructure/compression/LLMCompressionService.js +0 -211
  40. package/dist/infrastructure/compression/index.js +0 -11
  41. package/dist/infrastructure/compression/promptBuilder.js +0 -132
  42. package/dist/infrastructure/config/agentConfig.interface.js +0 -2
  43. package/dist/infrastructure/config/agentConfig.js +0 -134
  44. package/dist/infrastructure/logging/index.js +0 -5
  45. package/dist/infrastructure/logging/logger.interface.js +0 -2
  46. package/dist/infrastructure/logging/raw-output-logger.js +0 -35
  47. package/dist/infrastructure/skills/index.js +0 -5
  48. package/dist/infrastructure/skills/loader.js +0 -104
  49. package/dist/infrastructure/telemetry/index.js +0 -9
  50. package/dist/infrastructure/telemetry/telemetry.interface.js +0 -2
  51. package/dist/infrastructure/telemetry/telemetryConfig.js +0 -30
  52. package/dist/infrastructure/telemetry/traceEventFormatter.js +0 -90
  53. package/dist/infrastructure/telemetry/traceSinkConsole.js +0 -17
  54. package/dist/scripts/_validate/telemetry-autonomous.js +0 -23
  55. package/dist/scripts/_validate/telemetry-multi-agent.js +0 -50
  56. package/dist/scripts/_validate/test-agents-md-dynamic-dir.js +0 -104
  57. package/dist/scripts/_validate/test-agents-md-injection.js +0 -125
  58. package/dist/scripts/_validate/test-agents-md-loader.js +0 -71
  59. package/dist/scripts/_validate/test-agents-md-priority.js +0 -121
  60. package/dist/scripts/_validate/test-chrome-mcp-agent.js +0 -89
  61. package/dist/tools/mcp/discoverer.js +0 -95
  62. package/dist/tools/mcp/index.js +0 -9
  63. package/dist/tools/mcp/loader.js +0 -36
  64. package/dist/tools/mcp/mcpConfig.interface.js +0 -2
  65. package/dist/tools/mcp/mcpMetadata.js +0 -2
  66. package/dist/tools/mcp/register.js +0 -269
  67. package/dist/tools/native/capabilities.js +0 -155
  68. package/dist/tools/native/file-outline.js +0 -301
  69. package/dist/tools/native/index.js +0 -20
  70. package/dist/tools/native/list-directory.js +0 -148
  71. package/dist/tools/native/read-image.js +0 -140
  72. package/dist/tools/registry/toolFilter.js +0 -52
  73. package/dist/tools/registry/toolRegistry.interface.js +0 -2
@@ -15,4 +15,3 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./registry"), exports);
18
- __exportStar(require("./AgentFacade"), exports);
@@ -1,11 +1,69 @@
1
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
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.agentRegistry = exports.AgentRegistry = void 0;
4
- const agentParser_1 = require("./agentParser");
5
- const logger_1 = require("../../infrastructure/logging/logger");
37
+ const path = __importStar(require("path"));
38
+ const fs = __importStar(require("fs"));
39
+ const { createFrameRuntime } = require('@ericnunes/frame-agent-core');
40
+ const config_1 = require("../../infrastructure/config");
41
+ function resolveProfile() {
42
+ return process.env.AGENT_MODE === 'autonomous' ? 'ci_headless' : 'developer_exec';
43
+ }
44
+ function resolveAgentsDirs() {
45
+ let builtin = path.join(__dirname, '../../content/agents');
46
+ if (!fs.existsSync(builtin)) {
47
+ try {
48
+ const pkg = require.resolve('@ericnunes/frame-code-cli/package.json');
49
+ const pkgDir = path.dirname(pkg);
50
+ const dist = path.join(pkgDir, 'dist', 'content', 'agents');
51
+ const direct = path.join(pkgDir, 'content', 'agents');
52
+ builtin = fs.existsSync(dist) ? dist : direct;
53
+ }
54
+ catch {
55
+ }
56
+ }
57
+ const custom = path.join(process.cwd(), '.code', 'agents');
58
+ return [builtin, custom];
59
+ }
60
+ function resolveMcpConfigFile() {
61
+ return path.join(process.cwd(), '.code', 'mcp.json');
62
+ }
6
63
  class AgentRegistry {
7
64
  constructor() {
8
65
  this.agents = new Map();
66
+ this.loaded = false;
9
67
  }
10
68
  static getInstance() {
11
69
  if (!AgentRegistry.instance) {
@@ -13,79 +71,93 @@ class AgentRegistry {
13
71
  }
14
72
  return AgentRegistry.instance;
15
73
  }
16
- async load() {
17
- const agents = (0, agentParser_1.discoverAgents)();
18
- for (const agent of agents) {
19
- this.register(agent);
20
- }
21
- logger_1.logger.info(`[AgentRegistry] Carregados ${agents.length} agentes de .code/agents/`);
22
- return agents.length;
23
- }
24
- register(metadata) {
25
- if (this.agents.has(metadata.name)) {
26
- const error = `Agent '${metadata.name}' já registrado`;
27
- logger_1.logger.warn(`[AgentRegistry] ${error}`);
28
- return { name: metadata.name, success: false, error };
74
+ async ensureRuntimeLoaded() {
75
+ if (this.loaded)
76
+ return;
77
+ await (0, config_1.loadConfig)();
78
+ const profile = resolveProfile();
79
+ const agentsDirs = resolveAgentsDirs();
80
+ const mcpConfigFile = resolveMcpConfigFile();
81
+ this.runtime = await createFrameRuntime({
82
+ projectRoot: process.cwd(),
83
+ profile,
84
+ agents: { dirs: agentsDirs },
85
+ mcp: {
86
+ enabled: process.env.MCP_TOOLS_ENABLED !== 'false',
87
+ configFile: mcpConfigFile,
88
+ },
89
+ tools: {
90
+ allowAskUser: profile !== 'ci_headless',
91
+ excludedTools: [],
92
+ },
93
+ });
94
+ const summaries = this.runtime.listAgents();
95
+ for (const s of summaries) {
96
+ const meta = this.runtime.getAgentMetadata(s.name);
97
+ if (meta)
98
+ this.agents.set(s.name, meta);
29
99
  }
30
- this.agents.set(metadata.name, metadata);
31
- logger_1.logger.debug(`[AgentRegistry] Agente registrado: ${metadata.name}`);
32
- return { name: metadata.name, success: true };
100
+ this.loaded = true;
101
+ }
102
+ async load() {
103
+ await this.ensureRuntimeLoaded();
104
+ return this.agents.size;
105
+ }
106
+ register(_metadata, _options) {
107
+ return { name: _metadata.name, success: false, error: 'register() nao suportado no adaptador core' };
108
+ }
109
+ assertLoaded() {
110
+ if (!this.loaded)
111
+ throw new Error('AgentRegistry nao inicializado. Chame initializeAgents() primeiro.');
33
112
  }
34
113
  get(name) {
114
+ this.assertLoaded();
35
115
  return this.agents.get(name);
36
116
  }
37
117
  getMetadata(name) {
38
118
  return this.get(name);
39
119
  }
40
120
  list() {
121
+ this.assertLoaded();
41
122
  return Array.from(this.agents.values());
42
123
  }
43
124
  listSummaries() {
125
+ this.assertLoaded();
44
126
  return this.list().map((metadata) => ({
45
127
  name: metadata.name,
46
128
  type: metadata.type,
47
129
  description: metadata.description,
48
130
  keywords: metadata.keywords,
49
- canBeSupervisor: metadata.canBeSupervisor
131
+ canBeSupervisor: metadata.canBeSupervisor,
50
132
  }));
51
133
  }
52
134
  listByType(type) {
53
135
  return this.list().filter((a) => a.type === type);
54
136
  }
55
- listSupervisors() {
56
- return this.list().filter((a) => a.canBeSupervisor);
57
- }
58
- searchByKeywords(keywords) {
59
- return this.list().filter((agent) => keywords.some((kw) => agent.keywords.some((akw) => akw.toLowerCase().includes(kw.toLowerCase()))));
60
- }
61
137
  has(name) {
62
138
  return this.agents.has(name);
63
139
  }
64
140
  count() {
65
141
  return this.agents.size;
66
142
  }
67
- unregister(name) {
68
- return this.agents.delete(name);
69
- }
70
143
  clear() {
71
144
  this.agents.clear();
72
- logger_1.logger.info('[AgentRegistry] Registro limpo');
145
+ this.loaded = false;
73
146
  }
74
147
  async createEngine(name, telemetry) {
75
- const metadata = this.get(name);
76
- if (!metadata) {
77
- throw new Error(`Agent '${name}' não encontrado no registro`);
78
- }
79
- logger_1.logger.info(`[AgentRegistry] Criando engine para: ${name}`);
80
- return (0, agentParser_1.createAgentFromFlow)(metadata, telemetry);
148
+ await this.ensureRuntimeLoaded();
149
+ if (!this.agents.has(name))
150
+ throw new Error(`Agent '${name}' nao encontrado no registro`);
151
+ return this.runtime.createEngine(name, telemetry);
81
152
  }
82
153
  getStats() {
154
+ this.assertLoaded();
83
155
  const agents = this.list();
84
156
  return {
85
157
  total: agents.length,
86
158
  mainAgents: agents.filter((a) => a.type === 'main-agent').length,
87
159
  subAgents: agents.filter((a) => a.type === 'sub-agent').length,
88
- supervisors: agents.filter((a) => a.canBeSupervisor).length
160
+ supervisors: agents.filter((a) => a.canBeSupervisor).length,
89
161
  };
90
162
  }
91
163
  }
@@ -1,20 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AgentFacade = exports.AgentType = exports.listAgentsAvailable = exports.getDefaultAgent = exports.initializeAgents = exports.REACT_AGENT_FLOW = exports.createAgentFromFlow = exports.discoverAgents = exports.parseAgentFile = exports.agentRegistry = exports.AgentRegistry = void 0;
3
+ exports.listAgentsAvailable = exports.getDefaultAgent = exports.initializeAgents = exports.agentRegistry = exports.AgentRegistry = void 0;
4
4
  var AgentRegistry_1 = require("./AgentRegistry");
5
5
  Object.defineProperty(exports, "AgentRegistry", { enumerable: true, get: function () { return AgentRegistry_1.AgentRegistry; } });
6
6
  Object.defineProperty(exports, "agentRegistry", { enumerable: true, get: function () { return AgentRegistry_1.agentRegistry; } });
7
- var agentParser_1 = require("./agentParser");
8
- Object.defineProperty(exports, "parseAgentFile", { enumerable: true, get: function () { return agentParser_1.parseAgentFile; } });
9
- Object.defineProperty(exports, "discoverAgents", { enumerable: true, get: function () { return agentParser_1.discoverAgents; } });
10
- Object.defineProperty(exports, "createAgentFromFlow", { enumerable: true, get: function () { return agentParser_1.createAgentFromFlow; } });
11
- var ReactAgentFlow_1 = require("../flows/templates/ReactAgentFlow");
12
- Object.defineProperty(exports, "REACT_AGENT_FLOW", { enumerable: true, get: function () { return ReactAgentFlow_1.REACT_AGENT_FLOW; } });
13
7
  var initialization_1 = require("./initialization");
14
8
  Object.defineProperty(exports, "initializeAgents", { enumerable: true, get: function () { return initialization_1.initializeAgents; } });
15
9
  Object.defineProperty(exports, "getDefaultAgent", { enumerable: true, get: function () { return initialization_1.getDefaultAgent; } });
16
10
  Object.defineProperty(exports, "listAgentsAvailable", { enumerable: true, get: function () { return initialization_1.listAgentsAvailable; } });
17
- var agentType_enum_1 = require("./enums/agentType.enum");
18
- Object.defineProperty(exports, "AgentType", { enumerable: true, get: function () { return agentType_enum_1.AgentType; } });
19
- var AgentFacade_1 = require("../AgentFacade");
20
- Object.defineProperty(exports, "AgentFacade", { enumerable: true, get: function () { return AgentFacade_1.AgentFacade; } });
package/dist/app/cli.js CHANGED
@@ -4,23 +4,21 @@ Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.program = void 0;
5
5
  exports.runCli = runCli;
6
6
  const commander_1 = require("commander");
7
- const interactive_1 = require("../cli/commands/interactive");
8
7
  const autonomous_1 = require("../cli/commands/autonomous");
8
+ const interactive_1 = require("../cli/commands/interactive");
9
9
  const memory_1 = require("../cli/commands/memory");
10
- const multi_agent_1 = require("../cli/commands/multi-agent");
11
10
  exports.program = new commander_1.Command()
12
11
  .name('frame-code-cli')
13
12
  .description('CLI para frame-code com agentes')
14
13
  .version('0.0.1');
15
- exports.program.addCommand(interactive_1.interactiveCommand);
16
14
  exports.program.addCommand((0, autonomous_1.createAutonomousCommand)());
15
+ exports.program.addCommand((0, interactive_1.createInteractiveCommand)());
17
16
  exports.program.addCommand(memory_1.memoryCommand);
18
- exports.program.addCommand((0, multi_agent_1.createMultiAgentCommand)());
19
17
  function runCli(argv = process.argv) {
20
18
  try {
21
19
  const nextArgv = [...argv];
22
20
  if (nextArgv.length <= 2) {
23
- nextArgv.push('interactive');
21
+ nextArgv.push('--help');
24
22
  }
25
23
  exports.program.parse(nextArgv);
26
24
  }
@@ -5,20 +5,22 @@ exports.createAutonomousCommand = createAutonomousCommand;
5
5
  const commander_1 = require("commander");
6
6
  const fs_1 = require("fs");
7
7
  const logger_1 = require("../../infrastructure/logging/logger");
8
- const frame_agent_sdk_1 = require("@ericnunes/frame-agent-sdk");
9
8
  const tools_1 = require("../../tools");
10
9
  const config_1 = require("../../infrastructure/config");
11
10
  const reader_1 = require("../input/reader");
12
- const telemetry_1 = require("../../infrastructure/telemetry");
13
11
  const attachments_1 = require("../input/images/attachments");
14
12
  const agent_runtime_1 = require("../../agent-runtime");
13
+ const cliTelemetry_1 = require("../../infrastructure/telemetry/cliTelemetry");
14
+ const STATUS_RUNNING = 'RUNNING';
15
+ const STATUS_FINISHED = 'FINISHED';
16
+ const STATUS_ERROR = 'ERROR';
15
17
  async function processAutonomousInput(input, options) {
18
+ const runtimeTelemetry = (0, cliTelemetry_1.createCliTelemetry)();
16
19
  try {
17
20
  logger_1.logger.info('[Autonomous] Iniciando processamento autônomo');
18
21
  if (options.verbose) {
19
22
  logger_1.logger.info(`[Autonomous] Input recebido: ${input.substring(0, 200)}...`);
20
23
  }
21
- const { trace, telemetry } = (0, telemetry_1.createCliTelemetry)();
22
24
  const registry = agent_runtime_1.AgentRegistry.getInstance();
23
25
  let agentName;
24
26
  if (options.agent) {
@@ -36,10 +38,7 @@ async function processAutonomousInput(input, options) {
36
38
  agentName = (0, agent_runtime_1.getDefaultAgent)('code-agent');
37
39
  logger_1.logger.info(`[Autonomous] Usando agente padrão: ${agentName}`);
38
40
  }
39
- const graph = await registry.createEngine(agentName, {
40
- trace,
41
- telemetry
42
- });
41
+ const graph = await registry.createEngine(agentName, runtimeTelemetry);
43
42
  const imagePaths = options._imagePaths ?? [];
44
43
  const imageDetail = options.imageDetail ?? 'auto';
45
44
  const imageHint = imagePaths.length > 0
@@ -57,15 +56,15 @@ async function processAutonomousInput(input, options) {
57
56
  ...(options._runId ? { runId: options._runId } : {}),
58
57
  ...(imagePaths.length ? { imagePaths, imageDetail } : {})
59
58
  },
60
- status: frame_agent_sdk_1.GraphStatus.RUNNING
59
+ status: STATUS_RUNNING
61
60
  };
62
61
  const result = await graph.execute(initialState);
63
62
  logger_1.logger.debug(`[Autonomous] Status final: ${result.status}`);
64
63
  logger_1.logger.debug(`[Autonomous] lastToolCall:`, result.state.lastToolCall);
65
- if (result.status === frame_agent_sdk_1.GraphStatus.ERROR) {
64
+ if (result.status === STATUS_ERROR) {
66
65
  throw new Error(`Erro durante execução: ${result.state.logs?.join('\n') || 'Erro desconhecido'}`);
67
66
  }
68
- if (result.status !== frame_agent_sdk_1.GraphStatus.FINISHED) {
67
+ if (result.status !== STATUS_FINISHED) {
69
68
  logger_1.logger.warn(`[Autonomous] Status não finalizado: ${result.status}`);
70
69
  return 'Processamento concluído com status: ' + result.status;
71
70
  }
@@ -85,6 +84,9 @@ async function processAutonomousInput(input, options) {
85
84
  logger_1.logger.error('[Autonomous] Erro no processamento:', error);
86
85
  throw error;
87
86
  }
87
+ finally {
88
+ await runtimeTelemetry.trace.flush?.();
89
+ }
88
90
  }
89
91
  function createAutonomousCommand() {
90
92
  const command = new commander_1.Command('autonomous');
@@ -161,7 +163,7 @@ function createAutonomousCommand() {
161
163
  (0, fs_1.writeFileSync)(options.logFile, logContent, 'utf-8');
162
164
  }
163
165
  logger_1.logger.info('[Autonomous] Processamento autônomo concluído com sucesso');
164
- process.exit(0);
166
+ return;
165
167
  }
166
168
  catch (error) {
167
169
  logger_1.logger.error('[Autonomous] Erro fatal:', error);
@@ -174,7 +176,8 @@ function createAutonomousCommand() {
174
176
  logger_1.logger.debug('[Autonomous] Imprimindo erro no console');
175
177
  console.error('Erro:', errorMessage);
176
178
  }
177
- process.exit(1);
179
+ process.exitCode = 1;
180
+ return;
178
181
  }
179
182
  });
180
183
  return command;
@@ -1,172 +1,94 @@
1
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
- })();
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
35
5
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.interactiveCommand = void 0;
37
6
  exports.createInteractiveCommand = createInteractiveCommand;
38
7
  const commander_1 = require("commander");
39
- const readline = __importStar(require("readline"));
8
+ const readline_1 = __importDefault(require("readline"));
40
9
  const logger_1 = require("../../infrastructure/logging/logger");
41
- const frame_agent_sdk_1 = require("@ericnunes/frame-agent-sdk");
42
10
  const tools_1 = require("../../tools");
43
11
  const config_1 = require("../../infrastructure/config");
44
- const telemetry_1 = require("../../infrastructure/telemetry");
45
- const attachments_1 = require("../input/images/attachments");
46
12
  const agent_runtime_1 = require("../../agent-runtime");
47
- let interactiveExecuted = false;
13
+ const cliTelemetry_1 = require("../../infrastructure/telemetry/cliTelemetry");
14
+ function extractAnswer(result) {
15
+ const lastToolCall = result?.state?.lastToolCall;
16
+ if (lastToolCall?.toolName === 'final_answer' && typeof lastToolCall?.params?.answer === 'string') {
17
+ return lastToolCall.params.answer;
18
+ }
19
+ const lastAssistant = result?.state?.messages?.filter((m) => m.role === 'assistant').pop();
20
+ if (lastAssistant?.content)
21
+ return String(lastAssistant.content);
22
+ return '[sem resposta]';
23
+ }
48
24
  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')
25
+ const command = new commander_1.Command('interactive')
26
+ .description('Executa o agente em modo interativo (loop de perguntas/respostas)')
27
+ .option('-a, --agent <name>', 'Agente a ser usado (default: primeiro main-agent encontrado)')
28
+ .option('-v, --verbose', 'Logs detalhados')
55
29
  .action(async (options) => {
56
30
  try {
57
- if (interactiveExecuted) {
58
- return;
59
- }
60
- interactiveExecuted = true;
61
31
  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
32
  await (0, tools_1.initializeTools)();
93
- console.log('Inicializando agente...');
94
- const { trace, telemetry } = (0, telemetry_1.createCliTelemetry)();
33
+ await (0, agent_runtime_1.initializeAgents)();
95
34
  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
- }
35
+ let agentName = options.agent;
36
+ if (!agentName) {
37
+ agentName = (0, agent_runtime_1.getDefaultAgent)('code-agent');
38
+ }
39
+ const meta = registry.getMetadata(agentName);
40
+ if (!meta)
41
+ throw new Error(`Agente "${agentName}" nao encontrado.`);
42
+ if (meta.type !== 'main-agent')
43
+ throw new Error(`Agente "${agentName}" nao eh main-agent.`);
44
+ const runtimeTelemetry = (0, cliTelemetry_1.createCliTelemetry)();
45
+ const engine = await registry.createEngine(agentName, runtimeTelemetry);
46
+ logger_1.logger.info(`[Interactive] Agente: ${agentName}`);
47
+ logger_1.logger.info('[Interactive] Digite sua mensagem. Use "exit" para sair.');
48
+ let currentState;
49
+ const rl = readline_1.default.createInterface({ input: process.stdin, output: process.stdout });
50
+ try {
51
+ const ask = () => new Promise((resolve) => rl.question('> ', resolve));
52
+ while (true) {
53
+ const input = (await ask()).trim();
54
+ if (!input)
55
+ continue;
56
+ if (input.toLowerCase() === 'exit')
57
+ break;
146
58
  try {
147
- await processQuestion(trimmedInput);
59
+ let result;
60
+ if (!currentState) {
61
+ result = await engine.execute({
62
+ messages: [{ role: 'user', content: input }],
63
+ status: 'RUNNING',
64
+ });
65
+ }
66
+ else {
67
+ result = await engine.resume(currentState, { role: 'user', content: input });
68
+ }
69
+ currentState = result?.state;
70
+ const answer = extractAnswer(result);
71
+ console.log('\n' + answer + '\n');
72
+ if (options.verbose) {
73
+ logger_1.logger.debug('[Interactive] status:', result?.status, 'state:', result?.state?.status);
74
+ }
148
75
  }
149
- catch (error) {
150
- logger_1.logger.error('Erro em processQuestion:', error);
76
+ catch (err) {
77
+ logger_1.logger.error('[Interactive] Erro:', err?.message || err);
151
78
  }
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');
79
+ }
80
+ }
81
+ finally {
82
+ rl.close();
83
+ await runtimeTelemetry.trace.flush?.();
84
+ }
85
+ logger_1.logger.info('[Interactive] Encerrado.');
164
86
  }
165
87
  catch (error) {
166
- logger_1.logger.error('Erro ao iniciar modo interativo:', error);
167
- process.exit(1);
88
+ logger_1.logger.error('[Interactive] Falha:', error);
89
+ process.exitCode = 1;
168
90
  }
169
91
  });
170
92
  return command;
171
93
  }
172
- exports.interactiveCommand = createInteractiveCommand();
94
+ exports.default = createInteractiveCommand;