forked from CodebuffAI/codebuff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.ts
More file actions
339 lines (304 loc) · 8.9 KB
/
Copy pathfile.ts
File metadata and controls
339 lines (304 loc) · 8.9 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
338
339
import * as os from 'os'
import * as path from 'path'
import { z } from 'zod/v4'
import type { CodebuffFileSystem } from '../types/filesystem'
import type { SkillsMap } from '../types/skill'
export const FileTreeNodeSchema: z.ZodType<FileTreeNode> = z.object({
name: z.string(),
type: z.enum(['file', 'directory']),
children: z.lazy(() => z.array(FileTreeNodeSchema).optional()),
filePath: z.string(),
})
export interface FileTreeNode {
name: string
type: 'file' | 'directory'
filePath: string
lastReadTime?: number
children?: FileTreeNode[]
}
export interface DirectoryNode extends FileTreeNode {
type: 'directory'
children: FileTreeNode[]
}
export interface FileNode extends FileTreeNode {
type: 'file'
lastReadTime: number
}
export const FileVersionSchema = z.object({
path: z.string(),
content: z.string(),
})
export type FileVersion = z.infer<typeof FileVersionSchema>
export const customToolDefinitionsSchema = z
.record(
z.string(),
z.object({
// inputSchema can be a Zod schema (from MCP tools) or a JSON Schema object
// (from SDK custom tools that have been serialized). The agent-runtime
// converts JSON schemas to Zod using ensureZodSchema() before use.
inputSchema: z.custom<z.ZodType | Record<string, unknown>>(),
endsAgentStep: z.boolean().optional().default(false),
description: z.string().optional(),
exampleInputs: z.record(z.string(), z.any()).array().optional(),
}),
)
.default(() => ({}))
export type CustomToolDefinitions = NonNullable<
z.input<typeof customToolDefinitionsSchema>
>
export const ProjectFileContextSchema = z.object({
projectRoot: z.string(),
cwd: z.string(),
fileTree: z.array(z.custom<FileTreeNode>()),
fileTokenScores: z.record(z.string(), z.record(z.string(), z.number())),
tokenCallers: z
.record(z.string(), z.record(z.string(), z.array(z.string())))
.optional(),
knowledgeFiles: z.record(z.string(), z.string()),
userKnowledgeFiles: z.record(z.string(), z.string()).optional(),
agentTemplates: z.record(z.string(), z.any()).default(() => ({})),
customToolDefinitions: customToolDefinitionsSchema,
skills: z.record(z.string(), z.any()).optional(),
gitChanges: z.object({
status: z.string(),
diff: z.string(),
diffCached: z.string(),
lastCommitMessages: z.string(),
}),
changesSinceLastChat: z.record(z.string(), z.string()),
shellConfigFiles: z.record(z.string(), z.string()),
systemInfo: z.object({
platform: z.string(),
shell: z.string(),
nodeVersion: z.string(),
arch: z.string(),
homedir: z.string(),
cpus: z.number(),
chromeAvailable: z.boolean(),
}),
})
export type ProjectFileContext = {
projectRoot: string
cwd: string
fileTree: FileTreeNode[]
fileTokenScores: Record<string, Record<string, number>>
tokenCallers?: Record<string, Record<string, string[]>>
knowledgeFiles: Record<string, string>
userKnowledgeFiles?: Record<string, string>
agentTemplates: Record<string, any>
customToolDefinitions: CustomToolDefinitions
skills?: SkillsMap
gitChanges: {
status: string
diff: string
diffCached: string
lastCommitMessages: string
}
changesSinceLastChat: Record<string, string>
shellConfigFiles: Record<string, string>
systemInfo: {
platform: string
shell: string
nodeVersion: string
arch: string
homedir: string
cpus: number
chromeAvailable: boolean
}
}
export const fileRegex =
/<write_file>\s*<path>([^<]+)<\/path>\s*<content>([\s\S]*?)<\/content>\s*<\/write_file>/g
export const fileWithNoPathRegex = /<write_file>([\s\S]*?)<\/write_file>/g
export const parseFileBlocks = (fileBlocks: string) => {
let fileMatch
const files: Record<string, string> = {}
while ((fileMatch = fileRegex.exec(fileBlocks)) !== null) {
const [, filePath, fileContent] = fileMatch
files[filePath] = fileContent.startsWith('\n')
? fileContent.slice(1)
: fileContent
}
return files
}
export const getStubProjectFileContext = (): ProjectFileContext => ({
projectRoot: '',
cwd: '',
fileTree: [],
fileTokenScores: {},
knowledgeFiles: {},
userKnowledgeFiles: {},
agentTemplates: {},
customToolDefinitions: {},
skills: {},
gitChanges: {
status: '',
diff: '',
diffCached: '',
lastCommitMessages: '',
},
changesSinceLastChat: {},
shellConfigFiles: {},
systemInfo: {
platform: '',
shell: '',
nodeVersion: '',
arch: '',
homedir: '',
cpus: 0,
chromeAvailable: false,
},
})
export const createMarkdownFileBlock = (filePath: string, content: string) => {
return `\`\`\`${filePath}\n${content}\n\`\`\``
}
export const parseMarkdownCodeBlock = (content: string) => {
const match = content.match(/^```(?:[a-zA-Z]+)?\n([\s\S]*)\n```$/)
if (match) {
return match[1] + '\n'
}
return content
}
export const createSearchReplaceBlock = (search: string, replace: string) => {
return `<<<<<<< SEARCH\n${search}\n=======\n${replace}\n>>>>>>> REPLACE`
}
export function printFileTree(
nodes: FileTreeNode[],
depth: number = 0,
): string {
let result = ''
const indentation = ' '.repeat(depth)
for (const node of nodes) {
result += `${indentation}${node.name}${node.type === 'directory' ? '/' : ''}\n`
if (node.type === 'directory' && node.children) {
result += printFileTree(node.children, depth + 1)
}
}
return result
}
export function printFileTreeWithTokens(
nodes: FileTreeNode[],
fileTokenScores: Record<string, Record<string, number>>,
path: string[] = [],
): string {
let result = ''
const depth = path.length
const indentToken = ' '
const indentation = indentToken.repeat(depth)
const indentationWithFile = indentToken.repeat(depth + 1)
for (const node of nodes) {
if (
node.type === 'directory' &&
(!node.children || node.children.length === 0)
) {
// Skip empty directories
continue
}
result += `${indentation}${node.name}${node.type === 'directory' ? '/' : ''}`
path.push(node.name)
const filePath = path.join('/')
const tokenScores = fileTokenScores[filePath]
if (node.type === 'file' && tokenScores) {
const tokens = Object.keys(tokenScores)
if (tokens.length > 0) {
result += `\n${indentationWithFile}${tokens.join(' ')}`
}
}
result += '\n'
if (node.type === 'directory' && node.children) {
result += printFileTreeWithTokens(node.children, fileTokenScores, path)
}
path.pop()
}
return result
}
/**
* Ensures the given file contents ends with a newline character.
* @param contents - The file contents
* @returns the file contents with a newline character.
*/
export const ensureEndsWithNewline = (
contents: string | null,
): string | null => {
if (contents === null || contents === '') {
// Leave empty file as is
return contents
}
if (contents.endsWith('\n')) {
return contents
}
return contents + '\n'
}
/**
* Node-compatible file existence check.
* Uses fs.stat instead of Bun-specific fs.exists.
*/
export async function fileExists(params: {
filePath: string
fs: CodebuffFileSystem
}): Promise<boolean> {
const { filePath, fs } = params
try {
await fs.stat(filePath)
return true
} catch {
return false
}
}
export const ensureDirectoryExists = async (params: {
baseDir: string
fs: CodebuffFileSystem
}) => {
const { baseDir, fs } = params
const baseDirExists = await fileExists({ filePath: baseDir, fs })
if (!baseDirExists) {
await fs.mkdir(baseDir, { recursive: true })
}
}
/**
* Removes markdown code block syntax if present, including any language tag
*/
export const cleanMarkdownCodeBlock = (content: string): string => {
const cleanResponse = content.match(/^```(?:[a-zA-Z]+)?\n([\s\S]*)\n```$/)
? content.replace(/^```(?:[a-zA-Z]+)?\n/, '').replace(/\n```$/, '')
: content
return cleanResponse
}
export function isValidFilePath(path: string) {
if (!path) return false
// Check for whitespace
if (/\s/.test(path)) return false
// Check for invalid characters
const invalidChars = /[<>:"|?*\x00-\x1F]/g
if (invalidChars.test(path)) return false
return true
}
export async function isDir(params: {
path: string
fs: CodebuffFileSystem
}): Promise<boolean> {
const { path, fs } = params
try {
const stats = await fs.stat(path)
return stats.isDirectory()
} catch {
return false
}
}
/**
* Returns true if the `toPath` is a subdirectory of `fromPath`.
*/
export function isSubdir(fromPath: string, toPath: string) {
const resolvedFrom = path.resolve(fromPath)
const resolvedTo = path.resolve(toPath)
if (process.platform === 'win32') {
const fromDrive = path.parse(resolvedFrom).root.toLowerCase()
const toDrive = path.parse(resolvedTo).root.toLowerCase()
if (fromDrive !== toDrive) {
return false
}
}
return !path.relative(resolvedFrom, resolvedTo).startsWith('..')
}
export function isValidProjectRoot(dir: string): boolean {
return !isSubdir(dir, os.homedir())
}