@ericnunes/frame-code-cli 0.0.2 → 0.0.3

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 (72) 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 +8 -6
  6. package/dist/cli/commands/interactive.js +63 -146
  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/tools/index.js +0 -2
  15. package/dist/tools/registry/ToolInitializer.js +15 -55
  16. package/dist/tools/registry/index.js +1 -7
  17. package/package.json +11 -23
  18. package/dist/agent-runtime/AgentFacade.js +0 -33
  19. package/dist/agent-runtime/context/hooks/compressionHook.js +0 -56
  20. package/dist/agent-runtime/context/hooks/index.js +0 -5
  21. package/dist/agent-runtime/context/project-rules/loader.js +0 -72
  22. package/dist/agent-runtime/context/system-prompts/index.js +0 -5
  23. package/dist/agent-runtime/context/system-prompts/loader.js +0 -88
  24. package/dist/agent-runtime/flows/templates/ReactAgentFlow.js +0 -49
  25. package/dist/agent-runtime/registry/agentParser.js +0 -515
  26. package/dist/agent-runtime/registry/enums/agentType.enum.js +0 -8
  27. package/dist/agent-runtime/registry/interfaces/agentDependencies.interface.js +0 -2
  28. package/dist/agent-runtime/registry/interfaces/agentRegistry.interface.js +0 -2
  29. package/dist/app/bootstrap.js +0 -22
  30. package/dist/app/index.js +0 -9
  31. package/dist/cli/commands/index.js +0 -11
  32. package/dist/cli/commands/multi-agent.js +0 -131
  33. package/dist/cli/index.js +0 -18
  34. package/dist/cli/input/images/imageInput.js +0 -77
  35. package/dist/cli/input/images/readImageAttachment.js +0 -56
  36. package/dist/cli/input/index.js +0 -14
  37. package/dist/infrastructure/compression/CompressionManager.js +0 -315
  38. package/dist/infrastructure/compression/LLMCompressionService.js +0 -211
  39. package/dist/infrastructure/compression/index.js +0 -11
  40. package/dist/infrastructure/compression/promptBuilder.js +0 -132
  41. package/dist/infrastructure/config/agentConfig.interface.js +0 -2
  42. package/dist/infrastructure/config/agentConfig.js +0 -134
  43. package/dist/infrastructure/logging/index.js +0 -5
  44. package/dist/infrastructure/logging/logger.interface.js +0 -2
  45. package/dist/infrastructure/logging/raw-output-logger.js +0 -35
  46. package/dist/infrastructure/skills/index.js +0 -5
  47. package/dist/infrastructure/skills/loader.js +0 -104
  48. package/dist/infrastructure/telemetry/index.js +0 -9
  49. package/dist/infrastructure/telemetry/telemetry.interface.js +0 -2
  50. package/dist/infrastructure/telemetry/telemetryConfig.js +0 -30
  51. package/dist/infrastructure/telemetry/traceEventFormatter.js +0 -90
  52. package/dist/infrastructure/telemetry/traceSinkConsole.js +0 -17
  53. package/dist/scripts/_validate/telemetry-autonomous.js +0 -23
  54. package/dist/scripts/_validate/telemetry-multi-agent.js +0 -50
  55. package/dist/scripts/_validate/test-agents-md-dynamic-dir.js +0 -104
  56. package/dist/scripts/_validate/test-agents-md-injection.js +0 -125
  57. package/dist/scripts/_validate/test-agents-md-loader.js +0 -71
  58. package/dist/scripts/_validate/test-agents-md-priority.js +0 -121
  59. package/dist/scripts/_validate/test-chrome-mcp-agent.js +0 -89
  60. package/dist/tools/mcp/discoverer.js +0 -95
  61. package/dist/tools/mcp/index.js +0 -9
  62. package/dist/tools/mcp/loader.js +0 -36
  63. package/dist/tools/mcp/mcpConfig.interface.js +0 -2
  64. package/dist/tools/mcp/mcpMetadata.js +0 -2
  65. package/dist/tools/mcp/register.js +0 -269
  66. package/dist/tools/native/capabilities.js +0 -155
  67. package/dist/tools/native/file-outline.js +0 -301
  68. package/dist/tools/native/index.js +0 -20
  69. package/dist/tools/native/list-directory.js +0 -148
  70. package/dist/tools/native/read-image.js +0 -140
  71. package/dist/tools/registry/toolFilter.js +0 -52
  72. package/dist/tools/registry/toolRegistry.interface.js +0 -2
@@ -1,131 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.processMultiAgentInput = processMultiAgentInput;
4
- exports.createMultiAgentCommand = createMultiAgentCommand;
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 registry_1 = require("../../agent-runtime/registry");
12
- const reader_1 = require("../input/reader");
13
- const telemetry_1 = require("../../infrastructure/telemetry");
14
- const attachments_1 = require("../input/images/attachments");
15
- async function processMultiAgentInput(input, options) {
16
- try {
17
- logger_1.logger.info('[MultiAgent] Starting multi-agent execution');
18
- const normalizedInput = input.trim();
19
- const isPlaceholder = normalizedInput.length === 0;
20
- if (isPlaceholder) {
21
- logger_1.logger.warn('[MultiAgent] Empty input detected, using default task');
22
- input = 'Explique como usar o frame-code-cli com base no codigo atual. Nao modifique arquivos e nao use ferramentas.';
23
- }
24
- if (options.verbose) {
25
- logger_1.logger.info(`[MultiAgent] Input received: ${input.substring(0, 200)}...`);
26
- }
27
- await (0, config_1.loadConfig)();
28
- const { trace, telemetry } = (0, telemetry_1.createCliTelemetry)();
29
- const registry = registry_1.AgentRegistry.getInstance();
30
- const previousMode = process.env.AGENT_MODE;
31
- process.env.AGENT_MODE = 'autonomous';
32
- await (0, tools_1.initializeTools)({ allowAskUser: true });
33
- if (previousMode !== undefined) {
34
- process.env.AGENT_MODE = previousMode;
35
- }
36
- const graph = await registry.createEngine('supervisor', {
37
- trace,
38
- telemetry
39
- });
40
- const imagePaths = options._imagePaths ?? [];
41
- const imageDetail = options.imageDetail ?? 'auto';
42
- const initialState = {
43
- messages: [],
44
- data: {
45
- input,
46
- shared: {
47
- ...(imagePaths.length ? { imagePaths, imageDetail } : {})
48
- },
49
- ...(options._runId ? { runId: options._runId } : {})
50
- },
51
- status: frame_agent_sdk_1.GraphStatus.RUNNING
52
- };
53
- const result = await graph.execute(initialState);
54
- if (result.status === frame_agent_sdk_1.GraphStatus.ERROR) {
55
- throw new Error(`Execution error: ${result.state.logs?.join('\n') || 'Unknown error'}`);
56
- }
57
- if (result.status !== frame_agent_sdk_1.GraphStatus.FINISHED) {
58
- return `Execution finished with status: ${result.status}`;
59
- }
60
- const shared = result.state.data?.shared;
61
- const output = shared?.output;
62
- if (typeof output === 'string' && output.trim().length > 0) {
63
- return `[supervisor] ${output}`;
64
- }
65
- return '[supervisor] Execution finished without captured output';
66
- }
67
- catch (error) {
68
- logger_1.logger.error('[MultiAgent] Execution failed:', error);
69
- throw error;
70
- }
71
- }
72
- function createMultiAgentCommand() {
73
- const command = new commander_1.Command('multi-agent');
74
- const collect = (value, previous) => {
75
- return [...(previous ?? []), value];
76
- };
77
- command
78
- .description('Run multi-agent planner + implementer flow')
79
- .argument('[additional-input]', 'Additional text with priority over input file')
80
- .option('-i, --input-file <file>', 'Input file with prompt')
81
- .option('-o, --output-file <file>', 'Output file for response')
82
- .option('-l, --log-file <file>', 'Log file for details')
83
- .option('-v, --verbose', 'Verbose mode')
84
- .option('--image <path>', 'Caminho de imagem local (pode repetir)', collect, [])
85
- .option('--image-detail <low|high|auto>', 'Nivel de detalhe para imagem (low|high|auto)', 'auto')
86
- .action(async (additionalInput, options) => {
87
- try {
88
- if (options.inputFile) {
89
- logger_1.logger.info(`[MultiAgent] Reading input from: ${options.inputFile}`);
90
- }
91
- if (additionalInput) {
92
- logger_1.logger.info(`[MultiAgent] Adding input: ${additionalInput.substring(0, 100)}...`);
93
- }
94
- if (!options.inputFile && !additionalInput) {
95
- logger_1.logger.info('[MultiAgent] Reading input from stdin');
96
- }
97
- const input = await (0, reader_1.readCliInput)({ inputFile: options.inputFile, additionalInput });
98
- if (options.image && options.image.length > 0) {
99
- await (0, attachments_1.cleanupAttachmentsRoot)((0, attachments_1.getAttachmentsCleanupConfigFromEnv)());
100
- const staged = await (0, attachments_1.stageImageAttachments)({ imagePaths: options.image });
101
- options._runId = staged.runId;
102
- options._imagePaths = staged.stagedPaths;
103
- }
104
- const result = await processMultiAgentInput(input, options);
105
- if (options.outputFile) {
106
- logger_1.logger.info(`[MultiAgent] Writing output to: ${options.outputFile}`);
107
- (0, fs_1.writeFileSync)(options.outputFile, result, 'utf-8');
108
- }
109
- else {
110
- console.log(result);
111
- }
112
- if (options.logFile) {
113
- (0, fs_1.writeFileSync)(options.logFile, 'Detailed logs not implemented', 'utf-8');
114
- }
115
- logger_1.logger.info('[MultiAgent] Execution completed');
116
- process.exit(0);
117
- }
118
- catch (error) {
119
- logger_1.logger.error('[MultiAgent] Fatal error:', error);
120
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
121
- if (options.outputFile) {
122
- (0, fs_1.writeFileSync)(options.outputFile, `## Error\n\n${errorMessage}`, 'utf-8');
123
- }
124
- else {
125
- console.error('Error:', errorMessage);
126
- }
127
- process.exit(1);
128
- }
129
- });
130
- return command;
131
- }
package/dist/cli/index.js DELETED
@@ -1,18 +0,0 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./commands"), exports);
18
- __exportStar(require("./input"), exports);
@@ -1,77 +0,0 @@
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.readFileAsDataUrl = readFileAsDataUrl;
37
- exports.buildMultimodalContent = buildMultimodalContent;
38
- const fs_1 = require("fs");
39
- const path = __importStar(require("path"));
40
- const crypto_1 = require("crypto");
41
- function inferMimeType(filePath) {
42
- const ext = path.extname(filePath).toLowerCase();
43
- switch (ext) {
44
- case '.png':
45
- return 'image/png';
46
- case '.jpg':
47
- case '.jpeg':
48
- return 'image/jpeg';
49
- case '.webp':
50
- return 'image/webp';
51
- case '.gif':
52
- return 'image/gif';
53
- case '.bmp':
54
- return 'image/bmp';
55
- default:
56
- return 'application/octet-stream';
57
- }
58
- }
59
- async function readFileAsDataUrl(absolutePath) {
60
- const buffer = await fs_1.promises.readFile(absolutePath);
61
- const mimeType = inferMimeType(absolutePath);
62
- const hash = (0, crypto_1.createHash)('sha256').update(buffer).digest('hex');
63
- const base64 = buffer.toString('base64');
64
- return {
65
- url: `data:${mimeType};base64,${base64}`,
66
- mimeType,
67
- bytes: buffer.length,
68
- hash,
69
- };
70
- }
71
- function buildMultimodalContent(options) {
72
- const detail = options.detail ?? 'auto';
73
- return [
74
- { type: 'text', text: options.text },
75
- { type: 'image_url', image_url: { url: options.dataUrl, detail } },
76
- ];
77
- }
@@ -1,56 +0,0 @@
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.maybeAttachReadImageToContext = maybeAttachReadImageToContext;
37
- const path = __importStar(require("path"));
38
- const imageInput_1 = require("./imageInput");
39
- async function maybeAttachReadImageToContext(options) {
40
- const metadataObj = (options.metadata ?? {});
41
- const readImage = (metadataObj.readImage ?? null);
42
- const imagePath = readImage?.path?.trim();
43
- if (!imagePath)
44
- return false;
45
- const dataUrl = await (0, imageInput_1.readFileAsDataUrl)(imagePath);
46
- const detail = readImage?.detail ?? 'auto';
47
- const shortName = path.basename(imagePath);
48
- const prefix = options.textPrefix?.trim() || 'Imagem anexada (use-a para tomar decisōes no próximo passo).';
49
- const text = `${prefix}\nArquivo: ${shortName}`;
50
- const contentParts = (0, imageInput_1.buildMultimodalContent)({ text, dataUrl: dataUrl.url, detail });
51
- options.engine.addMessage({
52
- role: 'user',
53
- content: contentParts,
54
- });
55
- return true;
56
- }
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.maybeAttachReadImageToContext = exports.buildMultimodalContent = exports.readFileAsDataUrl = exports.getAttachmentsCleanupConfigFromEnv = exports.stageImageAttachments = exports.cleanupAttachmentsRoot = exports.readCliInput = void 0;
4
- var reader_1 = require("./reader");
5
- Object.defineProperty(exports, "readCliInput", { enumerable: true, get: function () { return reader_1.readCliInput; } });
6
- var attachments_1 = require("./images/attachments");
7
- Object.defineProperty(exports, "cleanupAttachmentsRoot", { enumerable: true, get: function () { return attachments_1.cleanupAttachmentsRoot; } });
8
- Object.defineProperty(exports, "stageImageAttachments", { enumerable: true, get: function () { return attachments_1.stageImageAttachments; } });
9
- Object.defineProperty(exports, "getAttachmentsCleanupConfigFromEnv", { enumerable: true, get: function () { return attachments_1.getAttachmentsCleanupConfigFromEnv; } });
10
- var imageInput_1 = require("./images/imageInput");
11
- Object.defineProperty(exports, "readFileAsDataUrl", { enumerable: true, get: function () { return imageInput_1.readFileAsDataUrl; } });
12
- Object.defineProperty(exports, "buildMultimodalContent", { enumerable: true, get: function () { return imageInput_1.buildMultimodalContent; } });
13
- var readImageAttachment_1 = require("./images/readImageAttachment");
14
- Object.defineProperty(exports, "maybeAttachReadImageToContext", { enumerable: true, get: function () { return readImageAttachment_1.maybeAttachReadImageToContext; } });
@@ -1,315 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CompressionManager = void 0;
4
- const frame_agent_sdk_1 = require("@ericnunes/frame-agent-sdk");
5
- const frame_agent_sdk_2 = require("@ericnunes/frame-agent-sdk");
6
- const LLMCompressionService_1 = require("./LLMCompressionService");
7
- const logger_1 = require("../logging/logger");
8
- const config_1 = require("../config");
9
- class CompressionManager {
10
- constructor(config) {
11
- this.compressoes = [];
12
- this.compressionCount = 0;
13
- const defaultConfig = (0, config_1.loadConfigSync)();
14
- this.compressionConfig = {
15
- enabled: true,
16
- threshold: 0.8,
17
- maxCount: 5,
18
- maxTokens: 300,
19
- logging: true,
20
- persist: true,
21
- ...config
22
- };
23
- this.maxCompressoes = this.compressionConfig.maxCount;
24
- this.persistKey = sanitizePersistKey(this.compressionConfig.persistKey ?? 'default');
25
- this.llmService = new LLMCompressionService_1.LLMCompressionService();
26
- if (!this.llmService.isConfigured()) {
27
- logger_1.logger.warn('[CompressionManager] LLM não configurado corretamente');
28
- logger_1.logger.debug('[CompressionManager] Config info:', this.llmService.getConfigInfo());
29
- }
30
- this.initializeTokenization(defaultConfig.defaults?.maxContextTokens || 240000);
31
- if (this.compressionConfig.persist) {
32
- this.loadPersistedCompressions();
33
- }
34
- logger_1.logger.info('[CompressionManager] Inicializado', {
35
- enabled: this.compressionConfig.enabled,
36
- maxCompressoes: this.maxCompressoes,
37
- threshold: this.compressionConfig.threshold,
38
- currentCompressions: this.compressoes.length,
39
- persistKey: this.persistKey
40
- });
41
- }
42
- initializeTokenization(maxContextTokens) {
43
- try {
44
- this.tokenizerService = new frame_agent_sdk_1.TokenizerService('gpt-4');
45
- this.chatHistoryManager = new frame_agent_sdk_1.ChatHistoryManager({
46
- maxContextTokens,
47
- tokenizer: this.tokenizerService
48
- });
49
- logger_1.logger.debug('[CompressionManager] Serviços de tokenização inicializados');
50
- }
51
- catch (error) {
52
- logger_1.logger.error('[CompressionManager] Erro ao inicializar tokenização:', error);
53
- }
54
- }
55
- async handleTokenOverflow(error, state) {
56
- if (!this.compressionConfig.enabled) {
57
- throw error;
58
- }
59
- logger_1.logger.error('[CompressionManager] Estouro de tokens detectado, iniciando compressão emergencial');
60
- logger_1.logger.debug('[CompressionManager] Erro original:', error.message);
61
- try {
62
- const messages = this.extractMessagesFromState(state);
63
- await this.performEmergencyCompression(messages);
64
- const compressedState = await this.buildCompressedState(state);
65
- logger_1.logger.info('[CompressionManager] Compressão emergencial concluída, retentando execução');
66
- return compressedState;
67
- }
68
- catch (compressionError) {
69
- logger_1.logger.error('[CompressionManager] Falha na compressão emergencial:', compressionError);
70
- throw error;
71
- }
72
- }
73
- async checkProactiveCompression(state) {
74
- if (!this.compressionConfig.enabled || !this.chatHistoryManager) {
75
- return false;
76
- }
77
- try {
78
- const messages = this.extractMessagesFromState(state);
79
- const currentTokens = this.tokenizerService.countTokens(messages);
80
- const maxTokens = 240000;
81
- const usageRatio = currentTokens / maxTokens;
82
- const shouldCompress = usageRatio >= this.compressionConfig.threshold;
83
- if (this.compressionConfig.logging) {
84
- logger_1.logger.debug(`[CompressionManager] Uso de tokens: ${currentTokens}/${maxTokens} (${(usageRatio * 100).toFixed(1)}%)`);
85
- if (shouldCompress) {
86
- logger_1.logger.info(`[CompressionManager] Threshold atingido (${(this.compressionConfig.threshold * 100)}%), compressão proativa recomendada`);
87
- }
88
- }
89
- return shouldCompress;
90
- }
91
- catch (error) {
92
- logger_1.logger.error('[CompressionManager] Erro na verificação proativa:', error);
93
- return false;
94
- }
95
- }
96
- async performProactiveCompression(state) {
97
- logger_1.logger.info('[CompressionManager] Iniciando compressão proativa');
98
- try {
99
- const messages = this.extractMessagesFromState(state);
100
- await this.performEmergencyCompression(messages);
101
- return await this.buildCompressedState(state);
102
- }
103
- catch (error) {
104
- logger_1.logger.error('[CompressionManager] Erro na compressão proativa:', error);
105
- throw error;
106
- }
107
- }
108
- async performEmergencyCompression(messages) {
109
- if (!this.llmService.isConfigured()) {
110
- throw new Error('LLM não configurado para compressão');
111
- }
112
- const protectedMessages = this.extractProtectedMessages(messages);
113
- const contextToCompress = this.extractCompressibleContext(messages);
114
- if (contextToCompress.trim().length === 0) {
115
- logger_1.logger.warn('[CompressionManager] Nenhum contexto para comprimir');
116
- return;
117
- }
118
- try {
119
- let newCompression;
120
- if (this.compressionCount === 0) {
121
- newCompression = await this.llmService.compressInitial(contextToCompress);
122
- this.compressionCount = 1;
123
- this.compressoes.push(newCompression);
124
- }
125
- else {
126
- newCompression = await this.llmService.compressIncremental(this.compressoes, contextToCompress);
127
- if (this.compressoes.length >= this.maxCompressoes) {
128
- await this.mergeOldestCompressions();
129
- }
130
- this.compressionCount++;
131
- this.compressoes.push(newCompression);
132
- }
133
- if (this.compressionConfig.persist) {
134
- this.persistCompressions();
135
- }
136
- logger_1.logger.info(`[CompressionManager] Compressão #${this.compressionCount} realizada com sucesso`);
137
- }
138
- catch (error) {
139
- logger_1.logger.error('[CompressionManager] Erro durante compressão emergencial:', error);
140
- throw error;
141
- }
142
- }
143
- async mergeOldestCompressions() {
144
- if (this.compressoes.length < 2) {
145
- return;
146
- }
147
- logger_1.logger.info('[CompressionManager] Mesclando compressões mais antigas');
148
- let oldest1;
149
- let oldest2;
150
- try {
151
- oldest1 = this.compressoes.shift();
152
- oldest2 = this.compressoes.shift();
153
- if (!oldest1 || !oldest2) {
154
- throw new Error('Não há compressões suficientes para mesclar');
155
- }
156
- const merged = await this.llmService.mergeCompressions(oldest1, oldest2);
157
- this.compressoes.unshift(merged);
158
- logger_1.logger.info('[CompressionManager] Compressões mescladas com sucesso');
159
- }
160
- catch (error) {
161
- logger_1.logger.error('[CompressionManager] Erro ao mesclar compressões:', error);
162
- if (oldest1 && oldest2) {
163
- this.compressoes.unshift(oldest2, oldest1);
164
- }
165
- throw error;
166
- }
167
- }
168
- extractProtectedMessages(messages) {
169
- const protectedMessages = [];
170
- const systemMessage = messages.find(msg => msg.role === 'system');
171
- if (systemMessage) {
172
- protectedMessages.push(systemMessage);
173
- }
174
- const userMessages = messages.filter(msg => msg.role === 'user');
175
- if (userMessages.length > 0) {
176
- protectedMessages.push(userMessages[0]);
177
- }
178
- if (userMessages.length > 1) {
179
- protectedMessages.push(userMessages[userMessages.length - 1]);
180
- }
181
- return protectedMessages;
182
- }
183
- extractCompressibleContext(messages) {
184
- const protectedIndices = new Set();
185
- messages.forEach((msg, index) => {
186
- if (msg.role === 'system') {
187
- protectedIndices.add(index);
188
- }
189
- else if (msg.role === 'user') {
190
- const userMessages = messages.filter(m => m.role === 'user');
191
- if (index === messages.indexOf(userMessages[0]) || index === messages.lastIndexOf(userMessages[userMessages.length - 1])) {
192
- protectedIndices.add(index);
193
- }
194
- }
195
- });
196
- const compressibleMessages = messages.filter((_, index) => !protectedIndices.has(index));
197
- return compressibleMessages
198
- .map(msg => `[${msg.role.toUpperCase()}]: ${(0, frame_agent_sdk_2.extractTextFromMessage)(msg)}`)
199
- .join('\n\n');
200
- }
201
- extractMessagesFromState(state) {
202
- return state.messages || [];
203
- }
204
- async buildCompressedState(originalState) {
205
- const originalMessages = this.extractMessagesFromState(originalState);
206
- const protectedMessages = this.extractProtectedMessages(originalMessages);
207
- const newMessages = [...protectedMessages];
208
- if (this.compressoes.length > 0) {
209
- const compressionContext = this.getCompressionPrompt();
210
- newMessages.unshift({
211
- role: 'system',
212
- content: compressionContext
213
- });
214
- }
215
- return {
216
- ...originalState,
217
- messages: newMessages
218
- };
219
- }
220
- getCompressionPrompt() {
221
- if (this.compressoes.length === 0) {
222
- return '';
223
- }
224
- return `CONTEXTO ACUMULADO DA SESSÃO:
225
- ${this.compressoes.join('\n')}`;
226
- }
227
- getCompressionHistory() {
228
- return [...this.compressoes];
229
- }
230
- getCompressionStats() {
231
- return {
232
- compressionCount: this.compressionCount,
233
- currentCompressions: this.compressoes.length,
234
- maxCompressions: this.maxCompressoes,
235
- enabled: this.compressionConfig.enabled,
236
- threshold: this.compressionConfig.threshold,
237
- persistKey: this.persistKey,
238
- compressionHistory: this.compressoes.map((comp, index) => ({
239
- index: index + 1,
240
- preview: comp.substring(0, 100) + (comp.length > 100 ? '...' : ''),
241
- length: comp.length
242
- }))
243
- };
244
- }
245
- clearCompressions() {
246
- this.compressoes = [];
247
- this.compressionCount = 0;
248
- if (this.compressionConfig.persist) {
249
- this.clearPersistedCompressions();
250
- }
251
- logger_1.logger.info('[CompressionManager] Compressões limpas');
252
- }
253
- persistCompressions() {
254
- try {
255
- const fs = require('fs');
256
- const path = require('path');
257
- const persistPath = path.join(process.cwd(), `.frame-code-compressions.${this.persistKey}.json`);
258
- const data = {
259
- compressoes: this.compressoes,
260
- compressionCount: this.compressionCount,
261
- persistKey: this.persistKey,
262
- timestamp: new Date().toISOString()
263
- };
264
- fs.writeFileSync(persistPath, JSON.stringify(data, null, 2));
265
- logger_1.logger.debug('[CompressionManager] Compressões persistidas');
266
- }
267
- catch (error) {
268
- logger_1.logger.error('[CompressionManager] Erro ao persistir compressões:', error);
269
- }
270
- }
271
- loadPersistedCompressions() {
272
- try {
273
- const fs = require('fs');
274
- const path = require('path');
275
- const persistPath = path.join(process.cwd(), `.frame-code-compressions.${this.persistKey}.json`);
276
- if (fs.existsSync(persistPath)) {
277
- const data = JSON.parse(fs.readFileSync(persistPath, 'utf-8'));
278
- this.compressoes = data.compressoes || [];
279
- this.compressionCount = data.compressionCount || 0;
280
- logger_1.logger.info(`[CompressionManager] Carregadas ${this.compressoes.length} compressões persistidas`);
281
- }
282
- }
283
- catch (error) {
284
- logger_1.logger.error('[CompressionManager] Erro ao carregar compressões persistidas:', error);
285
- }
286
- }
287
- clearPersistedCompressions() {
288
- try {
289
- const fs = require('fs');
290
- const path = require('path');
291
- const persistPath = path.join(process.cwd(), `.frame-code-compressions.${this.persistKey}.json`);
292
- if (fs.existsSync(persistPath)) {
293
- fs.unlinkSync(persistPath);
294
- logger_1.logger.debug('[CompressionManager] Arquivo de persistência removido');
295
- }
296
- }
297
- catch (error) {
298
- logger_1.logger.error('[CompressionManager] Erro ao limpar persistência:', error);
299
- }
300
- }
301
- async forceCompression(state) {
302
- logger_1.logger.info('[CompressionManager] Forçando compressão manual');
303
- if (!this.compressionConfig.enabled) {
304
- throw new Error('Compressão está desabilitada');
305
- }
306
- return await this.performProactiveCompression(state);
307
- }
308
- }
309
- exports.CompressionManager = CompressionManager;
310
- function sanitizePersistKey(value) {
311
- const trimmed = value.trim();
312
- if (!trimmed)
313
- return 'default';
314
- return trimmed.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80);
315
- }