Elffuss BraidHub

kikocis/continue public

main · 5.2 KiBRawPermalink
1import fs from "node:fs";
2
3import { IDE, ILLM } from "..";
4import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex";
5import { walkDirs } from "../indexing/walkDir";
6import { pruneLinesFromTop } from "../llm/countTokens";
7
8import { getRepoMapFilePath } from "./paths";
9import { findUriInDirs } from "./uri";
10
11export interface RepoMapOptions {
12 includeSignatures?: boolean;
13 dirUris?: string[];
14 outputRelativeUriPaths: boolean;
15}
16
17class RepoMapGenerator {
18 private maxRepoMapTokens: number;
19
20 private repoMapPath: string = getRepoMapFilePath();
21 private writeStream: fs.WriteStream = fs.createWriteStream(this.repoMapPath);
22 private contentTokens: number = 0;
23 private dirs: string[] = [];
24 private allUris: string[] = [];
25 private pathsInDirsWithSnippets: Set<string> = new Set();
26
27 private SNIPPETS_BATCH_SIZE = 100;
28 private URI_BATCH_SIZE = 100;
29 private REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5;
30 private PREAMBLE =
31 "Below is a repository map. \n" +
32 "For each file in the codebase, " +
33 "this map contains the name of the file, and the signature for any " +
34 "classes, methods, or functions in the file.\n\n";
35
36 constructor(
37 private llm: ILLM,
38 private ide: IDE,
39 private options: RepoMapOptions,
40 ) {
41 this.maxRepoMapTokens =
42 llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO;
43 }
44
45 private getUriForWrite(uri: string) {
46 if (this.options.outputRelativeUriPaths) {
47 return findUriInDirs(uri, this.dirs).relativePathOrBasename;
48 }
49 return uri;
50 }
51
52 async generate(): Promise<string> {
53 this.dirs = this.options.dirUris ?? (await this.ide.getWorkspaceDirs());
54 this.allUris = await walkDirs(
55 this.ide,
56 {
57 source: "generate repo map",
58 },
59 this.dirs,
60 );
61
62 // Initialize
63 await this.writeToStream(this.PREAMBLE);
64
65 if (this.options.includeSignatures) {
66 // Process uris and signatures
67 let snippetOffset = 0;
68 let uriOffset = 0;
69 while (true) {
70 const { groupedByUri, hasMoreSnippets, hasMoreUris } =
71 await CodeSnippetsCodebaseIndex.getPathsAndSignatures(
72 this.allUris,
73 uriOffset,
74 this.URI_BATCH_SIZE,
75 snippetOffset,
76 this.SNIPPETS_BATCH_SIZE,
77 );
78 // process batch
79 for (const [uri, signatures] of Object.entries(groupedByUri)) {
80 let fileContent: string;
81
82 try {
83 fileContent = await this.ide.readFile(uri);
84 } catch (err) {
85 console.error(
86 "Failed to read file:\n" +
87 ` Uri: ${uri}\n` +
88 ` Error: ${err instanceof Error ? err.message : String(err)}`,
89 );
90
91 continue;
92 }
93
94 const filteredSignatures = signatures.filter(
95 (signature) => signature.trim() !== fileContent.trim(),
96 );
97
98 if (filteredSignatures.length > 0) {
99 this.pathsInDirsWithSnippets.add(uri);
100 }
101
102 let content = `${this.getUriForWrite(uri)}:\n`;
103
104 for (const signature of signatures.slice(0, -1)) {
105 content += `${this.indentMultilineString(signature)}\n\t...\n`;
106 }
107
108 content += `${this.indentMultilineString(
109 signatures[signatures.length - 1],
110 )}\n\n`;
111
112 if (content) {
113 await this.writeToStream(content);
114 }
115 }
116 if (this.contentTokens >= this.maxRepoMapTokens) {
117 break;
118 }
119 if (hasMoreSnippets) {
120 snippetOffset += this.SNIPPETS_BATCH_SIZE;
121 } else if (hasMoreUris) {
122 snippetOffset = 0;
123 uriOffset += this.URI_BATCH_SIZE;
124 } else {
125 break;
126 }
127 }
128
129 // Remaining Uris just so that written repo map isn't incomplete
130 const urisWithoutSnippets = this.allUris.filter(
131 (uri) => !this.pathsInDirsWithSnippets.has(uri),
132 );
133
134 if (urisWithoutSnippets.length > 0) {
135 await this.writeToStream(
136 urisWithoutSnippets.map((uri) => this.getUriForWrite(uri)).join("\n"),
137 );
138 }
139 } else {
140 // Only process uris
141 await this.writeToStream(
142 this.allUris.map((uri) => this.getUriForWrite(uri)).join("\n"),
143 );
144 }
145
146 this.writeStream.end();
147
148 if (this.contentTokens >= this.maxRepoMapTokens) {
149 console.debug(
150 "Full repo map was unable to be generated due to context window limitations",
151 );
152 }
153
154 return fs.readFileSync(this.repoMapPath, "utf8");
155 }
156
157 private async writeToStream(content: string): Promise<void> {
158 const tokens = this.llm.countTokens(content);
159
160 if (this.contentTokens + tokens > this.maxRepoMapTokens) {
161 content = pruneLinesFromTop(
162 content,
163 this.maxRepoMapTokens - this.contentTokens,
164 this.llm.model,
165 );
166 }
167
168 this.contentTokens += this.llm.countTokens(content);
169
170 await new Promise((resolve) => this.writeStream.write(content, resolve));
171 }
172
173 private indentMultilineString(str: string) {
174 return str
175 .split("\n")
176 .map((line: any) => "\t" + line)
177 .join("\n");
178 }
179}
180
181export default async function generateRepoMap(
182 llm: ILLM,
183 ide: IDE,
184 options: RepoMapOptions,
185): Promise<string> {
186 const generator = new RepoMapGenerator(llm, ide, options);
187 return generator.generate();
188}