forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGlobTool.ts
More file actions
198 lines (190 loc) · 5.92 KB
/
Copy pathGlobTool.ts
File metadata and controls
198 lines (190 loc) · 5.92 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
import { z } from 'zod/v4'
import type { ValidationResult } from '../../Tool.js'
import { buildTool, type ToolDef } from '../../Tool.js'
import { getCwd } from '../../utils/cwd.js'
import { isENOENT } from '../../utils/errors.js'
import {
FILE_NOT_FOUND_CWD_NOTE,
suggestPathUnderCwd,
} from '../../utils/file.js'
import { getFsImplementation } from '../../utils/fsOperations.js'
import { glob } from '../../utils/glob.js'
import { lazySchema } from '../../utils/lazySchema.js'
import { expandPath, toRelativePath } from '../../utils/path.js'
import { checkReadPermissionForTool } from '../../utils/permissions/filesystem.js'
import type { PermissionDecision } from '../../utils/permissions/PermissionResult.js'
import { matchWildcardPattern } from '../../utils/permissions/shellRuleMatching.js'
import { DESCRIPTION, GLOB_TOOL_NAME } from './prompt.js'
import {
getToolUseSummary,
renderToolResultMessage,
renderToolUseErrorMessage,
renderToolUseMessage,
userFacingName,
} from './UI.js'
const inputSchema = lazySchema(() =>
z.strictObject({
pattern: z.string().describe('The glob pattern to match files against'),
path: z
.string()
.optional()
.describe(
'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.',
),
}),
)
type InputSchema = ReturnType<typeof inputSchema>
const outputSchema = lazySchema(() =>
z.object({
durationMs: z
.number()
.describe('Time taken to execute the search in milliseconds'),
numFiles: z.number().describe('Total number of files found'),
filenames: z
.array(z.string())
.describe('Array of file paths that match the pattern'),
truncated: z
.boolean()
.describe('Whether results were truncated (limited to 100 files)'),
}),
)
type OutputSchema = ReturnType<typeof outputSchema>
export type Output = z.infer<OutputSchema>
export const GlobTool = buildTool({
name: GLOB_TOOL_NAME,
searchHint: 'find files by name pattern or wildcard',
maxResultSizeChars: 100_000,
async description() {
return DESCRIPTION
},
userFacingName,
getToolUseSummary,
getActivityDescription(input) {
const summary = getToolUseSummary(input)
return summary ? `Finding ${summary}` : 'Finding files'
},
get inputSchema(): InputSchema {
return inputSchema()
},
get outputSchema(): OutputSchema {
return outputSchema()
},
isConcurrencySafe() {
return true
},
isReadOnly() {
return true
},
toAutoClassifierInput(input) {
return input.pattern
},
isSearchOrReadCommand() {
return { isSearch: true, isRead: false }
},
getPath({ path }): string {
return path ? expandPath(path) : getCwd()
},
async preparePermissionMatcher({ pattern }) {
return rulePattern => matchWildcardPattern(rulePattern, pattern)
},
async validateInput({ path }): Promise<ValidationResult> {
// If path is provided, validate that it exists and is a directory
if (path) {
const fs = getFsImplementation()
const absolutePath = expandPath(path)
// SECURITY: Skip filesystem operations for UNC paths to prevent NTLM credential leaks.
if (absolutePath.startsWith('\\\\') || absolutePath.startsWith('//')) {
return { result: true }
}
let stats
try {
stats = await fs.stat(absolutePath)
} catch (e: unknown) {
if (isENOENT(e)) {
const cwdSuggestion = await suggestPathUnderCwd(absolutePath)
let message = `Directory does not exist: ${path}. ${FILE_NOT_FOUND_CWD_NOTE} ${getCwd()}.`
if (cwdSuggestion) {
message += ` Did you mean ${cwdSuggestion}?`
}
return {
result: false,
message,
errorCode: 1,
}
}
throw e
}
if (!stats.isDirectory()) {
return {
result: false,
message: `Path is not a directory: ${path}`,
errorCode: 2,
}
}
}
return { result: true }
},
async checkPermissions(input, context): Promise<PermissionDecision> {
const appState = context.getAppState()
return checkReadPermissionForTool(
GlobTool,
input,
appState.toolPermissionContext,
)
},
async prompt() {
return DESCRIPTION
},
renderToolUseMessage,
renderToolUseErrorMessage,
renderToolResultMessage,
// Reuses Grep's render (UI.tsx:65) — shows filenames.join. durationMs/
// numFiles are "Found 3 files in 12ms" chrome (under-count, fine).
extractSearchText({ filenames }) {
return filenames.join('\n')
},
async call(input, { abortController, getAppState, globLimits }) {
const start = Date.now()
const appState = getAppState()
const limit = globLimits?.maxResults ?? 100
const { files, truncated } = await glob(
input.pattern,
GlobTool.getPath(input),
{ limit, offset: 0 },
abortController.signal,
appState.toolPermissionContext,
)
// Relativize paths under cwd to save tokens (same as GrepTool)
const filenames = files.map(toRelativePath)
const output: Output = {
filenames,
durationMs: Date.now() - start,
numFiles: filenames.length,
truncated,
}
return {
data: output,
}
},
mapToolResultToToolResultBlockParam(output, toolUseID) {
if (output.filenames.length === 0) {
return {
tool_use_id: toolUseID,
type: 'tool_result',
content: 'No files found',
}
}
return {
tool_use_id: toolUseID,
type: 'tool_result',
content: [
...output.filenames,
...(output.truncated
? [
'(Results are truncated. Consider using a more specific path or pattern.)',
]
: []),
].join('\n'),
}
},
} satisfies ToolDef<InputSchema, Output>)