@loxia-labs/loxia-autopilot-one 1.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.
- package/LICENSE +267 -0
- package/README.md +509 -0
- package/bin/cli.js +117 -0
- package/package.json +94 -0
- package/scripts/install-scanners.js +236 -0
- package/src/analyzers/CSSAnalyzer.js +297 -0
- package/src/analyzers/ConfigValidator.js +690 -0
- package/src/analyzers/ESLintAnalyzer.js +320 -0
- package/src/analyzers/JavaScriptAnalyzer.js +261 -0
- package/src/analyzers/PrettierFormatter.js +247 -0
- package/src/analyzers/PythonAnalyzer.js +266 -0
- package/src/analyzers/SecurityAnalyzer.js +729 -0
- package/src/analyzers/TypeScriptAnalyzer.js +247 -0
- package/src/analyzers/codeCloneDetector/analyzer.js +344 -0
- package/src/analyzers/codeCloneDetector/detector.js +203 -0
- package/src/analyzers/codeCloneDetector/index.js +160 -0
- package/src/analyzers/codeCloneDetector/parser.js +199 -0
- package/src/analyzers/codeCloneDetector/reporter.js +148 -0
- package/src/analyzers/codeCloneDetector/scanner.js +59 -0
- package/src/core/agentPool.js +1474 -0
- package/src/core/agentScheduler.js +2147 -0
- package/src/core/contextManager.js +709 -0
- package/src/core/messageProcessor.js +732 -0
- package/src/core/orchestrator.js +548 -0
- package/src/core/stateManager.js +877 -0
- package/src/index.js +631 -0
- package/src/interfaces/cli.js +549 -0
- package/src/interfaces/webServer.js +2162 -0
- package/src/modules/fileExplorer/controller.js +280 -0
- package/src/modules/fileExplorer/index.js +37 -0
- package/src/modules/fileExplorer/middleware.js +92 -0
- package/src/modules/fileExplorer/routes.js +125 -0
- package/src/modules/fileExplorer/types.js +44 -0
- package/src/services/aiService.js +1232 -0
- package/src/services/apiKeyManager.js +164 -0
- package/src/services/benchmarkService.js +366 -0
- package/src/services/budgetService.js +539 -0
- package/src/services/contextInjectionService.js +247 -0
- package/src/services/conversationCompactionService.js +637 -0
- package/src/services/errorHandler.js +810 -0
- package/src/services/fileAttachmentService.js +544 -0
- package/src/services/modelRouterService.js +366 -0
- package/src/services/modelsService.js +322 -0
- package/src/services/qualityInspector.js +796 -0
- package/src/services/tokenCountingService.js +536 -0
- package/src/tools/agentCommunicationTool.js +1344 -0
- package/src/tools/agentDelayTool.js +485 -0
- package/src/tools/asyncToolManager.js +604 -0
- package/src/tools/baseTool.js +800 -0
- package/src/tools/browserTool.js +920 -0
- package/src/tools/cloneDetectionTool.js +621 -0
- package/src/tools/dependencyResolverTool.js +1215 -0
- package/src/tools/fileContentReplaceTool.js +875 -0
- package/src/tools/fileSystemTool.js +1107 -0
- package/src/tools/fileTreeTool.js +853 -0
- package/src/tools/imageTool.js +901 -0
- package/src/tools/importAnalyzerTool.js +1060 -0
- package/src/tools/jobDoneTool.js +248 -0
- package/src/tools/seekTool.js +956 -0
- package/src/tools/staticAnalysisTool.js +1778 -0
- package/src/tools/taskManagerTool.js +2873 -0
- package/src/tools/terminalTool.js +2304 -0
- package/src/tools/webTool.js +1430 -0
- package/src/types/agent.js +519 -0
- package/src/types/contextReference.js +972 -0
- package/src/types/conversation.js +730 -0
- package/src/types/toolCommand.js +747 -0
- package/src/utilities/attachmentValidator.js +292 -0
- package/src/utilities/configManager.js +582 -0
- package/src/utilities/constants.js +722 -0
- package/src/utilities/directoryAccessManager.js +535 -0
- package/src/utilities/fileProcessor.js +307 -0
- package/src/utilities/logger.js +436 -0
- package/src/utilities/tagParser.js +1246 -0
- package/src/utilities/toolConstants.js +317 -0
- package/web-ui/build/index.html +15 -0
- package/web-ui/build/logo.png +0 -0
- package/web-ui/build/logo2.png +0 -0
- package/web-ui/build/static/index-CjkkcnFA.js +344 -0
- package/web-ui/build/static/index-Dy2bYbOa.css +1 -0
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Attachment Service
|
|
3
|
+
* Manages file attachments for agents with CRUD operations and reference counting
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import path from 'path';
|
|
7
|
+
import { fileURLToPath } from 'url';
|
|
8
|
+
import { randomUUID } from 'crypto';
|
|
9
|
+
import FileProcessor from '../utilities/fileProcessor.js';
|
|
10
|
+
import AttachmentValidator from '../utilities/attachmentValidator.js';
|
|
11
|
+
|
|
12
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
13
|
+
const __dirname = path.dirname(__filename);
|
|
14
|
+
|
|
15
|
+
const ATTACHMENTS_DIR = path.join(process.cwd(), 'loxia-state', 'attachments');
|
|
16
|
+
const INDEX_FILE = path.join(ATTACHMENTS_DIR, 'attachments-index.json');
|
|
17
|
+
|
|
18
|
+
class FileAttachmentService {
|
|
19
|
+
constructor(config = {}, logger = null) {
|
|
20
|
+
this.config = config;
|
|
21
|
+
this.logger = logger;
|
|
22
|
+
this.fileProcessor = new FileProcessor(config, logger);
|
|
23
|
+
this.validator = new AttachmentValidator(config, logger);
|
|
24
|
+
this.index = null; // Lazy loaded
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Initialize service (create directories, load index)
|
|
29
|
+
* @returns {Promise<void>}
|
|
30
|
+
*/
|
|
31
|
+
async initialize() {
|
|
32
|
+
try {
|
|
33
|
+
await this.fileProcessor.createDirectory(ATTACHMENTS_DIR);
|
|
34
|
+
await this.loadIndex();
|
|
35
|
+
this.logger?.info('FileAttachmentService initialized', { attachmentsDir: ATTACHMENTS_DIR });
|
|
36
|
+
} catch (error) {
|
|
37
|
+
this.logger?.error('Error initializing FileAttachmentService', { error: error.message });
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Load index file
|
|
44
|
+
* @returns {Promise<Object>}
|
|
45
|
+
*/
|
|
46
|
+
async loadIndex() {
|
|
47
|
+
try {
|
|
48
|
+
const exists = await this.fileProcessor.fileExists(INDEX_FILE);
|
|
49
|
+
if (!exists) {
|
|
50
|
+
this.index = { attachments: {}, agentRefs: {} };
|
|
51
|
+
await this.saveIndex();
|
|
52
|
+
} else {
|
|
53
|
+
const content = await this.fileProcessor.readFile(INDEX_FILE, 'utf8');
|
|
54
|
+
this.index = JSON.parse(content);
|
|
55
|
+
}
|
|
56
|
+
return this.index;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
this.logger?.error('Error loading index', { error: error.message });
|
|
59
|
+
this.index = { attachments: {}, agentRefs: {} };
|
|
60
|
+
return this.index;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Save index file
|
|
66
|
+
* @returns {Promise<void>}
|
|
67
|
+
*/
|
|
68
|
+
async saveIndex() {
|
|
69
|
+
try {
|
|
70
|
+
await this.fileProcessor.writeFile(INDEX_FILE, JSON.stringify(this.index, null, 2), 'utf8');
|
|
71
|
+
} catch (error) {
|
|
72
|
+
this.logger?.error('Error saving index', { error: error.message });
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Upload file attachment
|
|
79
|
+
* @param {Object} options
|
|
80
|
+
* @param {string} options.agentId - Agent ID
|
|
81
|
+
* @param {string} options.filePath - Source file path
|
|
82
|
+
* @param {string} options.mode - 'content' or 'reference'
|
|
83
|
+
* @param {string} options.fileName - Optional custom file name
|
|
84
|
+
* @returns {Promise<Object>} Attachment metadata
|
|
85
|
+
*/
|
|
86
|
+
async uploadFile({ agentId, filePath, mode = 'content', fileName = null }) {
|
|
87
|
+
if (!this.index) {
|
|
88
|
+
await this.loadIndex();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
try {
|
|
92
|
+
// Validate file exists
|
|
93
|
+
const exists = await this.fileProcessor.fileExists(filePath);
|
|
94
|
+
if (!exists) {
|
|
95
|
+
throw new Error(`File not found: ${filePath}`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Get file stats
|
|
99
|
+
const stats = await this.fileProcessor.getFileStats(filePath);
|
|
100
|
+
const actualFileName = fileName || path.basename(filePath);
|
|
101
|
+
const fileExtension = path.extname(actualFileName);
|
|
102
|
+
|
|
103
|
+
// Validate
|
|
104
|
+
const validation = this.validator.validate({
|
|
105
|
+
fileName: actualFileName,
|
|
106
|
+
size: stats.size,
|
|
107
|
+
mode,
|
|
108
|
+
path: mode === 'reference' ? filePath : null
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
if (!validation.valid) {
|
|
112
|
+
throw new Error(`Validation failed: ${validation.errors.join(', ')}`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Generate file ID
|
|
116
|
+
const fileId = randomUUID();
|
|
117
|
+
|
|
118
|
+
// Calculate hash
|
|
119
|
+
const hash = await this.fileProcessor.calculateHash(filePath);
|
|
120
|
+
|
|
121
|
+
// Determine content type
|
|
122
|
+
const contentType = this.validator.getContentType(actualFileName);
|
|
123
|
+
|
|
124
|
+
// Create attachment directory
|
|
125
|
+
const attachmentDir = path.join(ATTACHMENTS_DIR, agentId, fileId);
|
|
126
|
+
await this.fileProcessor.createDirectory(attachmentDir);
|
|
127
|
+
|
|
128
|
+
// Process and save content (for content mode)
|
|
129
|
+
let tokenEstimate = 0;
|
|
130
|
+
let contentFileName = null;
|
|
131
|
+
|
|
132
|
+
if (mode === 'content') {
|
|
133
|
+
const processResult = await this.fileProcessor.processFile(filePath, contentType);
|
|
134
|
+
const content = processResult.content;
|
|
135
|
+
|
|
136
|
+
// Determine content file name based on type
|
|
137
|
+
if (contentType === 'text') {
|
|
138
|
+
contentFileName = 'content.txt';
|
|
139
|
+
} else if (contentType === 'image') {
|
|
140
|
+
contentFileName = 'content.base64';
|
|
141
|
+
} else if (contentType === 'pdf') {
|
|
142
|
+
contentFileName = 'content.txt';
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Save content
|
|
146
|
+
const contentFilePath = path.join(attachmentDir, contentFileName);
|
|
147
|
+
await this.fileProcessor.writeFile(contentFilePath, content, 'utf8');
|
|
148
|
+
|
|
149
|
+
// Estimate tokens
|
|
150
|
+
tokenEstimate = this.fileProcessor.estimateTokens(content);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Create metadata
|
|
154
|
+
const metadata = {
|
|
155
|
+
fileId,
|
|
156
|
+
agentId,
|
|
157
|
+
fileName: actualFileName,
|
|
158
|
+
originalPath: filePath,
|
|
159
|
+
fileType: this.validator.getMimeType(actualFileName),
|
|
160
|
+
fileExtension,
|
|
161
|
+
size: stats.size,
|
|
162
|
+
mode,
|
|
163
|
+
active: true,
|
|
164
|
+
uploadedAt: new Date().toISOString(),
|
|
165
|
+
lastModified: stats.modified.toISOString(),
|
|
166
|
+
hash,
|
|
167
|
+
tokenEstimate,
|
|
168
|
+
contentType,
|
|
169
|
+
contentFileName,
|
|
170
|
+
warnings: validation.warnings,
|
|
171
|
+
sizeLevel: validation.sizeLevel,
|
|
172
|
+
importedFrom: null,
|
|
173
|
+
referencedBy: [agentId] // Reference counting
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// Save metadata
|
|
177
|
+
const metadataPath = path.join(attachmentDir, 'metadata.json');
|
|
178
|
+
await this.fileProcessor.writeFile(metadataPath, JSON.stringify(metadata, null, 2), 'utf8');
|
|
179
|
+
|
|
180
|
+
// Update index
|
|
181
|
+
this.index.attachments[fileId] = {
|
|
182
|
+
fileId,
|
|
183
|
+
agentId,
|
|
184
|
+
fileName: actualFileName,
|
|
185
|
+
mode,
|
|
186
|
+
active: metadata.active,
|
|
187
|
+
referencedBy: metadata.referencedBy
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
if (!this.index.agentRefs[agentId]) {
|
|
191
|
+
this.index.agentRefs[agentId] = [];
|
|
192
|
+
}
|
|
193
|
+
this.index.agentRefs[agentId].push(fileId);
|
|
194
|
+
|
|
195
|
+
await this.saveIndex();
|
|
196
|
+
|
|
197
|
+
this.logger?.info('File uploaded', { fileId, agentId, fileName: actualFileName, mode });
|
|
198
|
+
|
|
199
|
+
return metadata;
|
|
200
|
+
} catch (error) {
|
|
201
|
+
this.logger?.error('Error uploading file', { agentId, filePath, error: error.message });
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Get attachments for an agent
|
|
208
|
+
* @param {string} agentId - Agent ID
|
|
209
|
+
* @param {Object} filters - Optional filters { active, mode }
|
|
210
|
+
* @returns {Promise<Array>} Array of attachment metadata
|
|
211
|
+
*/
|
|
212
|
+
async getAttachments(agentId, filters = {}) {
|
|
213
|
+
if (!this.index) {
|
|
214
|
+
await this.loadIndex();
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
try {
|
|
218
|
+
const fileIds = this.index.agentRefs[agentId] || [];
|
|
219
|
+
const attachments = [];
|
|
220
|
+
|
|
221
|
+
for (const fileId of fileIds) {
|
|
222
|
+
const metadata = await this.getAttachment(fileId);
|
|
223
|
+
if (metadata) {
|
|
224
|
+
// Apply filters
|
|
225
|
+
if (filters.active !== undefined && metadata.active !== filters.active) {
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (filters.mode && metadata.mode !== filters.mode) {
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
attachments.push(metadata);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return attachments;
|
|
236
|
+
} catch (error) {
|
|
237
|
+
this.logger?.error('Error getting attachments', { agentId, error: error.message });
|
|
238
|
+
throw error;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Get single attachment
|
|
244
|
+
* @param {string} fileId - File ID
|
|
245
|
+
* @returns {Promise<Object|null>} Attachment metadata or null
|
|
246
|
+
*/
|
|
247
|
+
async getAttachment(fileId) {
|
|
248
|
+
if (!this.index) {
|
|
249
|
+
await this.loadIndex();
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
try {
|
|
253
|
+
const indexEntry = this.index.attachments[fileId];
|
|
254
|
+
if (!indexEntry) {
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const metadataPath = path.join(ATTACHMENTS_DIR, indexEntry.agentId, fileId, 'metadata.json');
|
|
259
|
+
const exists = await this.fileProcessor.fileExists(metadataPath);
|
|
260
|
+
|
|
261
|
+
if (!exists) {
|
|
262
|
+
this.logger?.warn('Metadata file not found', { fileId });
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const content = await this.fileProcessor.readFile(metadataPath, 'utf8');
|
|
267
|
+
return JSON.parse(content);
|
|
268
|
+
} catch (error) {
|
|
269
|
+
this.logger?.error('Error getting attachment', { fileId, error: error.message });
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Get attachment content
|
|
276
|
+
* @param {string} fileId - File ID
|
|
277
|
+
* @returns {Promise<string|null>} File content or null
|
|
278
|
+
*/
|
|
279
|
+
async getAttachmentContent(fileId) {
|
|
280
|
+
try {
|
|
281
|
+
const metadata = await this.getAttachment(fileId);
|
|
282
|
+
if (!metadata || metadata.mode !== 'content') {
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const contentPath = path.join(ATTACHMENTS_DIR, metadata.agentId, fileId, metadata.contentFileName);
|
|
287
|
+
const exists = await this.fileProcessor.fileExists(contentPath);
|
|
288
|
+
|
|
289
|
+
if (!exists) {
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return await this.fileProcessor.readFile(contentPath, 'utf8');
|
|
294
|
+
} catch (error) {
|
|
295
|
+
this.logger?.error('Error getting attachment content', { fileId, error: error.message });
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Toggle attachment active state
|
|
302
|
+
* @param {string} fileId - File ID
|
|
303
|
+
* @returns {Promise<Object>} Updated metadata
|
|
304
|
+
*/
|
|
305
|
+
async toggleActive(fileId) {
|
|
306
|
+
try {
|
|
307
|
+
const metadata = await this.getAttachment(fileId);
|
|
308
|
+
if (!metadata) {
|
|
309
|
+
throw new Error(`Attachment not found: ${fileId}`);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
metadata.active = !metadata.active;
|
|
313
|
+
metadata.lastModified = new Date().toISOString();
|
|
314
|
+
|
|
315
|
+
// Save updated metadata
|
|
316
|
+
const metadataPath = path.join(ATTACHMENTS_DIR, metadata.agentId, fileId, 'metadata.json');
|
|
317
|
+
await this.fileProcessor.writeFile(metadataPath, JSON.stringify(metadata, null, 2), 'utf8');
|
|
318
|
+
|
|
319
|
+
// Update index
|
|
320
|
+
if (this.index.attachments[fileId]) {
|
|
321
|
+
this.index.attachments[fileId].active = metadata.active;
|
|
322
|
+
await this.saveIndex();
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
this.logger?.info('Attachment active state toggled', { fileId, active: metadata.active });
|
|
326
|
+
|
|
327
|
+
return metadata;
|
|
328
|
+
} catch (error) {
|
|
329
|
+
this.logger?.error('Error toggling attachment', { fileId, error: error.message });
|
|
330
|
+
throw error;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Update attachment metadata
|
|
336
|
+
* @param {string} fileId - File ID
|
|
337
|
+
* @param {Object} updates - Fields to update
|
|
338
|
+
* @returns {Promise<Object>} Updated metadata
|
|
339
|
+
*/
|
|
340
|
+
async updateAttachment(fileId, updates) {
|
|
341
|
+
try {
|
|
342
|
+
const metadata = await this.getAttachment(fileId);
|
|
343
|
+
if (!metadata) {
|
|
344
|
+
throw new Error(`Attachment not found: ${fileId}`);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Allow only safe updates
|
|
348
|
+
const allowedFields = ['fileName', 'active'];
|
|
349
|
+
for (const field of allowedFields) {
|
|
350
|
+
if (updates[field] !== undefined) {
|
|
351
|
+
metadata[field] = updates[field];
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
metadata.lastModified = new Date().toISOString();
|
|
356
|
+
|
|
357
|
+
// Save updated metadata
|
|
358
|
+
const metadataPath = path.join(ATTACHMENTS_DIR, metadata.agentId, fileId, 'metadata.json');
|
|
359
|
+
await this.fileProcessor.writeFile(metadataPath, JSON.stringify(metadata, null, 2), 'utf8');
|
|
360
|
+
|
|
361
|
+
// Update index
|
|
362
|
+
if (this.index.attachments[fileId]) {
|
|
363
|
+
if (updates.fileName) {
|
|
364
|
+
this.index.attachments[fileId].fileName = updates.fileName;
|
|
365
|
+
}
|
|
366
|
+
if (updates.active !== undefined) {
|
|
367
|
+
this.index.attachments[fileId].active = updates.active;
|
|
368
|
+
}
|
|
369
|
+
await this.saveIndex();
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
this.logger?.info('Attachment updated', { fileId, updates });
|
|
373
|
+
|
|
374
|
+
return metadata;
|
|
375
|
+
} catch (error) {
|
|
376
|
+
this.logger?.error('Error updating attachment', { fileId, error: error.message });
|
|
377
|
+
throw error;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Delete attachment (with reference counting)
|
|
383
|
+
* @param {string} fileId - File ID
|
|
384
|
+
* @param {string} agentId - Agent ID requesting deletion
|
|
385
|
+
* @returns {Promise<boolean>} true if deleted, false if still referenced
|
|
386
|
+
*/
|
|
387
|
+
async deleteAttachment(fileId, agentId) {
|
|
388
|
+
try {
|
|
389
|
+
const metadata = await this.getAttachment(fileId);
|
|
390
|
+
if (!metadata) {
|
|
391
|
+
throw new Error(`Attachment not found: ${fileId}`);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Remove agent from referencedBy
|
|
395
|
+
metadata.referencedBy = metadata.referencedBy.filter(id => id !== agentId);
|
|
396
|
+
|
|
397
|
+
// If still referenced by other agents, just update metadata
|
|
398
|
+
if (metadata.referencedBy.length > 0) {
|
|
399
|
+
const metadataPath = path.join(ATTACHMENTS_DIR, metadata.agentId, fileId, 'metadata.json');
|
|
400
|
+
await this.fileProcessor.writeFile(metadataPath, JSON.stringify(metadata, null, 2), 'utf8');
|
|
401
|
+
|
|
402
|
+
// Update index
|
|
403
|
+
if (this.index.attachments[fileId]) {
|
|
404
|
+
this.index.attachments[fileId].referencedBy = metadata.referencedBy;
|
|
405
|
+
}
|
|
406
|
+
if (this.index.agentRefs[agentId]) {
|
|
407
|
+
this.index.agentRefs[agentId] = this.index.agentRefs[agentId].filter(id => id !== fileId);
|
|
408
|
+
}
|
|
409
|
+
await this.saveIndex();
|
|
410
|
+
|
|
411
|
+
this.logger?.info('Attachment dereferenced', { fileId, agentId, remainingRefs: metadata.referencedBy.length });
|
|
412
|
+
return false;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// No more references, delete physical files
|
|
416
|
+
const attachmentDir = path.join(ATTACHMENTS_DIR, metadata.agentId, fileId);
|
|
417
|
+
await this.fileProcessor.deleteDirectory(attachmentDir);
|
|
418
|
+
|
|
419
|
+
// Remove from index
|
|
420
|
+
delete this.index.attachments[fileId];
|
|
421
|
+
if (this.index.agentRefs[agentId]) {
|
|
422
|
+
this.index.agentRefs[agentId] = this.index.agentRefs[agentId].filter(id => id !== fileId);
|
|
423
|
+
}
|
|
424
|
+
await this.saveIndex();
|
|
425
|
+
|
|
426
|
+
this.logger?.info('Attachment deleted', { fileId, agentId });
|
|
427
|
+
return true;
|
|
428
|
+
} catch (error) {
|
|
429
|
+
this.logger?.error('Error deleting attachment', { fileId, agentId, error: error.message });
|
|
430
|
+
throw error;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Delete all attachments for an agent
|
|
436
|
+
* @param {string} agentId - Agent ID
|
|
437
|
+
* @returns {Promise<Object>} { deleted: number, dereferenced: number }
|
|
438
|
+
*/
|
|
439
|
+
async deleteAgentAttachments(agentId) {
|
|
440
|
+
try {
|
|
441
|
+
const fileIds = this.index.agentRefs[agentId] || [];
|
|
442
|
+
let deleted = 0;
|
|
443
|
+
let dereferenced = 0;
|
|
444
|
+
|
|
445
|
+
for (const fileId of fileIds) {
|
|
446
|
+
const wasDeleted = await this.deleteAttachment(fileId, agentId);
|
|
447
|
+
if (wasDeleted) {
|
|
448
|
+
deleted++;
|
|
449
|
+
} else {
|
|
450
|
+
dereferenced++;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
this.logger?.info('Agent attachments deleted', { agentId, deleted, dereferenced });
|
|
455
|
+
|
|
456
|
+
return { deleted, dereferenced };
|
|
457
|
+
} catch (error) {
|
|
458
|
+
this.logger?.error('Error deleting agent attachments', { agentId, error: error.message });
|
|
459
|
+
throw error;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Import attachment from another agent
|
|
465
|
+
* @param {string} sourceFileId - Source file ID
|
|
466
|
+
* @param {string} targetAgentId - Target agent ID
|
|
467
|
+
* @returns {Promise<Object>} New attachment metadata
|
|
468
|
+
*/
|
|
469
|
+
async importFromAgent(sourceFileId, targetAgentId) {
|
|
470
|
+
try {
|
|
471
|
+
const sourceMetadata = await this.getAttachment(sourceFileId);
|
|
472
|
+
if (!sourceMetadata) {
|
|
473
|
+
throw new Error(`Source attachment not found: ${sourceFileId}`);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// Add target agent to referencedBy
|
|
477
|
+
if (!sourceMetadata.referencedBy.includes(targetAgentId)) {
|
|
478
|
+
sourceMetadata.referencedBy.push(targetAgentId);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
sourceMetadata.lastModified = new Date().toISOString();
|
|
482
|
+
sourceMetadata.importedFrom = sourceMetadata.agentId;
|
|
483
|
+
|
|
484
|
+
// Save updated metadata
|
|
485
|
+
const metadataPath = path.join(ATTACHMENTS_DIR, sourceMetadata.agentId, sourceFileId, 'metadata.json');
|
|
486
|
+
await this.fileProcessor.writeFile(metadataPath, JSON.stringify(sourceMetadata, null, 2), 'utf8');
|
|
487
|
+
|
|
488
|
+
// Update index
|
|
489
|
+
if (this.index.attachments[sourceFileId]) {
|
|
490
|
+
this.index.attachments[sourceFileId].referencedBy = sourceMetadata.referencedBy;
|
|
491
|
+
}
|
|
492
|
+
if (!this.index.agentRefs[targetAgentId]) {
|
|
493
|
+
this.index.agentRefs[targetAgentId] = [];
|
|
494
|
+
}
|
|
495
|
+
if (!this.index.agentRefs[targetAgentId].includes(sourceFileId)) {
|
|
496
|
+
this.index.agentRefs[targetAgentId].push(sourceFileId);
|
|
497
|
+
}
|
|
498
|
+
await this.saveIndex();
|
|
499
|
+
|
|
500
|
+
this.logger?.info('Attachment imported', { sourceFileId, targetAgentId });
|
|
501
|
+
|
|
502
|
+
return sourceMetadata;
|
|
503
|
+
} catch (error) {
|
|
504
|
+
this.logger?.error('Error importing attachment', { sourceFileId, targetAgentId, error: error.message });
|
|
505
|
+
throw error;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* Get active attachments for an agent
|
|
511
|
+
* @param {string} agentId - Agent ID
|
|
512
|
+
* @returns {Promise<Array>} Array of active attachment metadata
|
|
513
|
+
*/
|
|
514
|
+
async getActiveAttachments(agentId) {
|
|
515
|
+
return await this.getAttachments(agentId, { active: true });
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Get attachment preview (first 1000 characters)
|
|
520
|
+
* @param {string} fileId - File ID
|
|
521
|
+
* @returns {Promise<string|null>} Preview text or null
|
|
522
|
+
*/
|
|
523
|
+
async getAttachmentPreview(fileId) {
|
|
524
|
+
try {
|
|
525
|
+
const content = await this.getAttachmentContent(fileId);
|
|
526
|
+
if (!content) {
|
|
527
|
+
return null;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// For base64 images, return metadata instead of content
|
|
531
|
+
if (content.startsWith('data:image')) {
|
|
532
|
+
return '[Image content - base64 encoded]';
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// Return first 1000 characters
|
|
536
|
+
return content.length > 1000 ? content.substring(0, 1000) + '...' : content;
|
|
537
|
+
} catch (error) {
|
|
538
|
+
this.logger?.error('Error getting attachment preview', { fileId, error: error.message });
|
|
539
|
+
return null;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
export default FileAttachmentService;
|