-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathload-memory-files.ts
More file actions
337 lines (286 loc) · 9.44 KB
/
load-memory-files.ts
File metadata and controls
337 lines (286 loc) · 9.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import * as p from '@clack/prompts';
import fs from 'fs/promises';
import path from 'path';
import { allSupportedExtensions, MEMORYSETS } from './constants';
import { getDocumentContent } from './get-document-content';
import { formatDocSize } from './lib';
import loadMemoryConfig from './load-memory-config';
import {
memoryConfigSchema,
type DocumentConfigI,
type MemoryConfigI
} from 'types/memory';
import { execSync } from 'child_process';
import fg from 'fast-glob';
export interface MemoryDocumentI {
name: string;
size: string;
content: string;
blob: Blob;
path: string;
meta: Record<string, string>;
}
export const loadMemoryFiles = async (
memoryName: string
): Promise<MemoryDocumentI[]> => {
// Get memory config.
const memoryConfig = await checkMemoryConfig(memoryName);
// useDocumentsDir
const useDocumentsDir = !memoryConfig || !memoryConfig.git.enabled;
const documentConfig = memoryConfig?.documents;
// Load files from documents directory.
if (useDocumentsDir) {
return await loadMemoryFilesFromDocsDir({ memoryName, documentConfig });
}
// Load files from the repo.
return await loadMemoryFilesFromCustomDir({ memoryName, memoryConfig });
};
/**
* Loads memory files from a custom directory specified in the memory configuration.
*
* @param {Object} params - The parameters for loading memory files.
* @param {string} params.memoryName - The name of the memory.
* @param {MemoryConfigI} params.memoryConfig - The configuration for the memory, including the directory to track and the extensions to track.
* @returns {Promise<MemoryDocumentI[]>} A promise that resolves to an array of memory documents.
*
* @throws Will terminate the process if the documents directory does not exist or if it fails to read documents in the memory.
*/
export const loadMemoryFilesFromCustomDir = async ({
memoryName,
memoryConfig
}: {
memoryName: string;
memoryConfig: MemoryConfigI;
}): Promise<MemoryDocumentI[]> => {
const includePatterns = memoryConfig.git.include;
if (!Array.isArray(includePatterns) || includePatterns.length === 0) {
p.cancel(`No include patterns specified for memory '${memoryName}'`);
process.exit(1);
}
// Get all files that match the glob patterns and are tracked by git
let allFiles: string[];
try {
// First get all git tracked files
const gitFiles = new Set([
...execSync('git ls-files', { encoding: 'utf-8' })
.split('\n')
.filter(Boolean),
...execSync('git ls-files --others --exclude-standard', {
encoding: 'utf-8'
})
.split('\n')
.filter(Boolean),
...execSync('git diff --name-only', { encoding: 'utf-8' })
.split('\n')
.filter(Boolean)
]);
// Then match against glob patterns
const matchedFiles = await fg(includePatterns, {
ignore: ['node_modules/**'],
dot: true,
gitignore: memoryConfig.git.gitignore || true
});
// Only keep files that are both tracked by git and match the patterns
allFiles = matchedFiles.filter((file: string) => gitFiles.has(file));
} catch (error) {
p.cancel(`Failed to read documents in memory '${memoryName}'.`);
process.exit(1);
}
const memoryFilesContent = await Promise.all(
allFiles.map(async filePath => {
// Check if the file is allowed
const isSupportedExtension = allSupportedExtensions.some(
extension => filePath.endsWith(extension)
);
if (!isSupportedExtension) {
return null;
}
let fileContentBuffer: Buffer;
try {
fileContentBuffer = await fs.readFile(filePath);
} catch (error) {
p.log.warn(`Failed to read file: ${filePath}. Skipping.`);
return null;
}
const fileContentBlob = new Blob([fileContentBuffer]);
const size = fileContentBlob.size;
if (size > MEMORYSETS.MAX_DOC_SIZE) {
p.log.warn(
`Skipping ${filePath}; File exceeds the maximum size of ${formatDocSize(MEMORYSETS.MAX_DOC_SIZE)}.`
);
return null;
}
const memoryFile = {
path: filePath,
name: path.basename(filePath.replace(/\//g, '-')),
size: formatDocSize(fileContentBlob.size),
content: await getDocumentContent(fileContentBlob),
blob: fileContentBlob
};
let meta = {};
if (memoryConfig?.documents?.meta) {
meta = memoryConfig.documents.meta(memoryFile) || {};
}
return { ...memoryFile, meta };
})
);
const memoryFilesContentFiltered = memoryFilesContent.filter(
(file): file is MemoryDocumentI => file !== null
);
if (memoryFilesContentFiltered.length === 0) {
return [];
}
return memoryFilesContentFiltered;
};
/**
* Loads memory files from the specified memory directory.
*
* @param memoryName - The name of the memory directory to load files from.
* @returns A promise that resolves to an array of `MemoryDocumentI` objects.
*
* @throws Will exit the process if the documents directory does not exist or if reading the directory fails.
*
* The function performs the following steps:
* 1. Constructs the path to the memory directory and the documents subdirectory.
* 2. Checks if the documents directory exists. If not, logs an error and exits the process.
* 3. Reads the list of files in the documents directory. If reading fails, logs an error and exits the process.
* 4. Reads the content of each file and filters out files that:
* - Cannot be read.
* - Exceed the maximum allowed size.
* - Have unsupported file extensions.
* 5. Returns an array of `MemoryDocumentI` objects representing the valid memory files.
*/
export const loadMemoryFilesFromDocsDir = async ({
memoryName,
documentConfig
}: {
memoryName: string;
documentConfig?: DocumentConfigI;
}): Promise<MemoryDocumentI[]> => {
const memoryDir = path.join(process.cwd(), 'baseai', 'memory', memoryName);
const memoryFilesPath = path.join(memoryDir, 'documents');
try {
await fs.access(memoryFilesPath);
} catch (error) {
p.cancel(
`Documents directory for memory '${memoryName}' does not exist.`
);
process.exit(1);
}
let memoryFiles: string[];
try {
memoryFiles = await fs.readdir(memoryFilesPath);
} catch (error) {
p.cancel(`Failed to read documents in memory '${memoryName}'.`);
process.exit(1);
}
const memoryFilesContent = await Promise.all(
memoryFiles.map(async file => {
// Check if the file is allowed.
const isSupportedExtension = allSupportedExtensions.some(
extension => file.endsWith(extension)
);
if (!isSupportedExtension) {
p.log.warn(`Skipping ${file}; Unsupported file extension.`);
return null;
}
const filePath = path.join(memoryFilesPath, file);
let fileContentBuffer: Buffer;
try {
fileContentBuffer = await fs.readFile(filePath);
} catch (error) {
p.log.warn(`Failed to read file: ${file}. Skipping.`);
return null;
}
const fileContentBlob = new Blob([fileContentBuffer]);
const size = fileContentBlob.size;
if (size > MEMORYSETS.MAX_DOC_SIZE) {
p.log.warn(
`Skipping ${file}; File exceeds the maximum size of ${formatDocSize(MEMORYSETS.MAX_DOC_SIZE)}.`
);
return null;
}
const memoryFile = {
name: file,
path: filePath,
size: formatDocSize(fileContentBlob.size),
content: await getDocumentContent(fileContentBlob),
blob: fileContentBlob
};
let meta = {};
if (documentConfig?.meta) {
meta = documentConfig.meta(memoryFile) || {};
}
return { ...memoryFile, meta };
})
);
const memoryFilesContentFiltered = memoryFilesContent.filter(
(file): file is MemoryDocumentI => file !== null
);
if (memoryFilesContentFiltered.length === 0) {
return [];
}
return memoryFilesContentFiltered;
};
/**
* Asynchronously checks the configuration for a given memory name.
*
* @param memoryName - The name of the memory to check the configuration for.
* @returns A promise that resolves to the memory configuration if it exists and is valid,
* resolves to null if the configuration does not exist,
* or does not resolve if the configuration is invalid (process exits).
*/
async function checkMemoryConfig(
memoryName: string
): Promise<MemoryConfigI | null | void> {
// Load config for memory.
const memoryConfig = await loadMemoryConfig(memoryName);
// Check if config exists.
const configExists = memoryConfig !== null;
// No config exists for memory.
if (!configExists) {
return null;
}
// Check if config is valid.
const validatedConfig = memoryConfigSchema.safeParse(memoryConfig);
// Config is invalid.
if (!validatedConfig.success) {
p.cancel(`Memory '${memoryName}' has an invalid config.`);
process.exit(1);
}
return {
...memoryConfig
};
}
export const getMemoryFileNames = async (
memoryName: string
): Promise<string[]> => {
const memoryDir = path.join(process.cwd(), 'baseai', 'memory', memoryName);
const memoryFilesPath = path.join(memoryDir, 'documents');
try {
await fs.access(memoryFilesPath);
} catch (error) {
p.cancel(
`Documents directory for memory '${memoryName}' does not exist.`
);
process.exit(1);
}
try {
const memoryFiles = await fs.readdir(memoryFilesPath);
const validFiles = await Promise.all(
memoryFiles.map(async file => {
const filePath = path.join(memoryFilesPath, file);
const stats = await fs.stat(filePath);
const isSupportedExtension = allSupportedExtensions.some(
extension => file.endsWith(extension)
);
const isNotTooLarge = stats.size <= MEMORYSETS.MAX_DOC_SIZE;
return isSupportedExtension && isNotTooLarge ? file : null;
})
);
return validFiles.filter((file): file is string => file !== null);
} catch (error) {
p.cancel(`Failed to read documents in memory '${memoryName}'.`);
process.exit(1);
}
};