@deepseek-ai/dsh-tool-fs-search 0.2.2-alpha.3 → 0.2.2-rc.2

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/src/grep.ts ADDED
@@ -0,0 +1,370 @@
1
+ /**
2
+ * The model-facing `grep` tool: search file contents with a ripgrep regular
3
+ * expression. Execution spawns the packaged ripgrep binary
4
+ * (`@vscode/ripgrep`) directly through the subprocess seam with a plain argv
5
+ * vector using a fixed line-oriented `rg --json` command so file path, line
6
+ * number, and line text parse without colon-splitting ambiguity — this module
7
+ * owns the model-facing schema, argument validation, argv construction,
8
+ * `--json` record parsing, per-line preview retention, match retention,
9
+ * grouping, and formatting; process concerns stay behind `ctx.subprocess`.
10
+ *
11
+ * @module @deepseek-ai/dsh-tool-fs-search/grep
12
+ */
13
+
14
+ import type { Context } from '@deepseek-ai/cordis'
15
+ import { ToolArgsError, defineTool } from '@deepseek-ai/dsh-tools'
16
+ import type { GenericCallView, SearchResultView, ToolResult } from '@deepseek-ai/dsh-tools'
17
+ import type { RetainedItems } from '@deepseek-ai/dsh-output-retention'
18
+ import type { SpillRef } from '@deepseek-ai/dsh-spill'
19
+ import type { GrepMatch } from './search-core.ts'
20
+ import { SearchError, previewLine, retainGrepMatches, runRipgrep, toWorkdirRelative, trySaveFormattedResult } from './search-core.ts'
21
+ import { grepSearchMeta, searchViewFromMeta } from './presentation.ts'
22
+ import { acceptedDirectCallValue } from './direct-call.ts'
23
+
24
+ /**
25
+ * Default cap on flat matches retained inline by one `grep` call (the
26
+ * `grepMaxMatches` config), matching Claude Code's default `GrepTool`
27
+ * `head_limit`.
28
+ */
29
+ export const GREP_MAX_MATCHES = 250
30
+
31
+ /**
32
+ * Default cap in bytes on one matched-line preview (the `grepMaxLineBytes`
33
+ * config); the cut preserves UTF-8 boundaries.
34
+ */
35
+ export const GREP_MAX_LINE_BYTES = 2000
36
+
37
+ /** Resolved grep-tool caps — plugin config after defaulting (see `Config` in index.ts). */
38
+ export interface GrepToolCaps {
39
+ /** Max flat matches retained inline; later matches go to the formatted spill file. */
40
+ maxMatches: number
41
+ /** Max bytes retained per matched-line preview. */
42
+ maxLineBytes: number
43
+ /** Max bytes of serialized `presentationMeta`; trailing file groups drop past it. */
44
+ maxMetaBytes: number
45
+ /** Cap on the complete raw `rg` stdout the tool will parse. */
46
+ rawOutputMaxBytes: number
47
+ /** Terminate-escalation grace period (ms) for the search process. */
48
+ graceMs: number
49
+ /** Cap on the retained stderr diagnostic tail. */
50
+ stderrMaxBytes: number
51
+ /** Cooperative tool-call budget (ms) attached as `ToolDefinition.timeoutMs`. */
52
+ timeoutMs: number
53
+ }
54
+
55
+ /** Validated `grep` arguments. */
56
+ export interface GrepInput {
57
+ pattern: string
58
+ path?: string
59
+ include?: string
60
+ }
61
+
62
+ /**
63
+ * Reject an `include` that is not ONE positive glob filter: blank strings,
64
+ * negated patterns (`!…`), and comma-separated lists. A comma inside a brace
65
+ * group is fine — `*.{ts,tsx}` is one glob with alternation, not a list.
66
+ */
67
+ function validateInclude(include: string): void {
68
+ if (include.trim().length === 0) throw new ToolArgsError(['include must be a non-empty glob when given'])
69
+ if (include.startsWith('!')) throw new ToolArgsError(['include must be a positive glob filter; negated patterns ("!…") are not supported'])
70
+ let braceDepth = 0
71
+ for (const char of include) {
72
+ if (char === '{') braceDepth++
73
+ else if (char === '}') braceDepth = Math.max(0, braceDepth - 1)
74
+ else if (char === ',' && braceDepth === 0) {
75
+ throw new ToolArgsError(['include must be one glob, not a comma-separated list (use {a,b} alternation instead)'])
76
+ }
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Validate value constraints the schema DSL can't express: a non-EMPTY
82
+ * `pattern` (whitespace is a legitimate regex), a non-blank `path` when given,
83
+ * and a single positive `include` glob ({@link GrepInput}). An exact empty
84
+ * `include` is treated as omitted; whitespace-only values remain invalid.
85
+ * Throws `ToolArgsError` (`INVALID_ARGS`) otherwise.
86
+ *
87
+ * @param args - the schema-validated `grep` arguments.
88
+ * @returns the accepted input with an empty `include` omitted.
89
+ */
90
+ export function parseGrepArgs(args: { pattern: string; path?: string; include?: string }): GrepInput {
91
+ if (args.pattern.length === 0) throw new ToolArgsError(['pattern must be a non-empty string'])
92
+ if (args.path !== undefined && args.path.trim().length === 0) throw new ToolArgsError(['path must be a non-empty string when given'])
93
+ const include = args.include === '' ? undefined : args.include
94
+ if (include !== undefined) validateInclude(include)
95
+ return {
96
+ pattern: args.pattern,
97
+ ...args.path !== undefined ? { path: args.path } : {},
98
+ ...include !== undefined ? { include } : {},
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Build the fixed line-oriented `rg --json` argv for one `grep` call. Every
104
+ * model-controlled value ({@link GrepInput.pattern}, {@link GrepInput.path},
105
+ * {@link GrepInput.include}) is a plain argv element — no shell layer exists,
106
+ * so no quoting applies; the pattern and include ride in `--flag=value` form
107
+ * and the target behind `--`, so a leading-dash value can never be parsed as
108
+ * a flag.
109
+ *
110
+ * @param input - the validated arguments.
111
+ * @returns the complete ripgrep argument vector (excluding the binary itself).
112
+ */
113
+ export function buildGrepCommand(input: GrepInput): string[] {
114
+ const parts = ['--json', `--regexp=${input.pattern}`]
115
+ if (input.include !== undefined) parts.push(`--glob=${input.include}`)
116
+ if (input.path !== undefined) parts.push('--', input.path)
117
+ return parts
118
+ }
119
+
120
+ /**
121
+ * The uniform malformed-output failure: raw `rg --json` is an internal
122
+ * transport, so missing or invalid response fields cause a search failure, not a partial result.
123
+ */
124
+ function malformedRecord(detail: string, cause?: unknown): SearchError {
125
+ return new SearchError(`grep received malformed ripgrep --json output (${detail})`, 'SEARCH_FAILED', cause !== undefined ? { cause } : undefined)
126
+ }
127
+
128
+ /**
129
+ * Parse one `rg --json` NDJSON line into a match, `undefined` for the
130
+ * non-match record types (`begin`/`end`/`context`/`summary`). A line that is
131
+ * not JSON, or a `match` record missing its path / line number / line content,
132
+ * throws {@link SearchError} `SEARCH_FAILED`. A match whose line is not valid
133
+ * UTF-8 (ripgrep sends base64 `bytes` instead of `text`) yields a placeholder
134
+ * preview rather than failing the whole search.
135
+ */
136
+ function parseRecord(line: string): GrepMatch | undefined {
137
+ let parsed: unknown
138
+ try {
139
+ parsed = JSON.parse(line)
140
+ } catch (error: unknown) {
141
+ throw malformedRecord('a line is not JSON', error)
142
+ }
143
+ if (typeof parsed !== 'object' || parsed === null) throw malformedRecord('a record is not an object')
144
+ const record = parsed as { type?: unknown; data?: unknown }
145
+ // Non-match record types (begin/end/context/summary — and any future type)
146
+ // are transport framing, not results: skipped, not malformed.
147
+ if (record.type !== 'match') return undefined
148
+ if (typeof record.data !== 'object' || record.data === null) throw malformedRecord('a match record has no data')
149
+ const data = record.data as { path?: unknown; line_number?: unknown; lines?: unknown }
150
+ const pathText = typeof data.path === 'object' && data.path !== null ? (data.path as { text?: unknown }).text : undefined
151
+ if (typeof pathText !== 'string') throw malformedRecord('a match record has no path text')
152
+ if (typeof data.line_number !== 'number') throw malformedRecord('a match record has no line number')
153
+ if (typeof data.lines !== 'object' || data.lines === null) throw malformedRecord('a match record has no line content')
154
+ const lines = data.lines as { text?: unknown; bytes?: unknown }
155
+ if (typeof lines.text === 'string') {
156
+ return { path: pathText, lineNumber: data.line_number, line: lines.text.replace(/\r?\n$/, '') }
157
+ }
158
+ if (typeof lines.bytes === 'string') {
159
+ return { path: pathText, lineNumber: data.line_number, line: '(line is not valid UTF-8)' }
160
+ }
161
+ throw malformedRecord('a match record has neither line text nor bytes')
162
+ }
163
+
164
+ /**
165
+ * Parse complete `rg --json` stdout into flat matches, in output order (ripgrep
166
+ * emits one file's matches contiguously). Only `match` records are consumed.
167
+ *
168
+ * @param stdout - the complete raw `rg --json` stdout.
169
+ * @returns the flat matches; empty for output with no match records.
170
+ */
171
+ export function parseGrepMatches(stdout: string): GrepMatch[] {
172
+ const matches: GrepMatch[] = []
173
+ for (const line of stdout.split('\n')) {
174
+ if (line.length === 0) continue
175
+ const match = parseRecord(line)
176
+ if (match !== undefined) matches.push(match)
177
+ }
178
+ return matches
179
+ }
180
+
181
+ /** `match` / `matches` for a count. */
182
+ function matchNoun(count: number): string {
183
+ return count === 1 ? 'match' : 'matches'
184
+ }
185
+
186
+ /**
187
+ * Group flat matches by file (first-seen order) into the model-facing body:
188
+ * each file's display path, then one `Line N: <text>` row per match.
189
+ *
190
+ * @param matches - the flat matches to render.
191
+ * @returns the grouped body text.
192
+ */
193
+ export function formatGrepMatches(matches: GrepMatch[]): string {
194
+ const byFile = new Map<string, GrepMatch[]>()
195
+ for (const match of matches) {
196
+ const group = byFile.get(match.path)
197
+ if (group !== undefined) group.push(match)
198
+ else byFile.set(match.path, [match])
199
+ }
200
+ const sections: string[] = []
201
+ for (const [path, group] of byFile) {
202
+ sections.push(`${path}\n${group.map(m => `Line ${m.lineNumber}: ${m.line}`).join('\n')}`)
203
+ }
204
+ return sections.join('\n\n')
205
+ }
206
+
207
+ /**
208
+ * Format the model-facing `grep` result: a found-count header, the retained
209
+ * matches grouped by file, then — when the result was capped — a footer
210
+ * carrying either the formatted-spill recovery locator or the could-not-save
211
+ * explanation. The omitted count is a budget fact: the search itself completed.
212
+ *
213
+ * @param retained - the retention outcome over every parsed match.
214
+ * @param spillRef - the saved complete-result reference, or `undefined` when unsaved.
215
+ * @returns the model-facing text.
216
+ */
217
+ export function formatGrepOutput(retained: RetainedItems<GrepMatch>, spillRef: SpillRef | undefined): string {
218
+ const header = retained.truncated
219
+ ? `Found ${retained.kept} of ${retained.seen} matches`
220
+ : `Found ${retained.seen} ${matchNoun(retained.seen)}`
221
+ const body = formatGrepMatches(retained.items)
222
+ if (!retained.truncated) return `${header}\n\n${body}`
223
+ const recovery = spillRef !== undefined
224
+ ? `Full grep result stored at: ${spillRef.locator}. ${spillRef.retrievalHint}`
225
+ : 'The complete result could not be saved; narrow pattern, path, or include to see more.'
226
+ return `${header}\n\n${body}\n\n(${recovery})`
227
+ }
228
+
229
+ /** Format one already-retained match list for the Native surface. */
230
+ function formatRetainedGrep(retained: RetainedItems<GrepMatch>, spillRef?: SpillRef): string {
231
+ if (retained.seen === 0) return 'No matches found'
232
+ return formatGrepOutput(retained, spillRef)
233
+ }
234
+
235
+ /**
236
+ * Pending-call presentation: a search card titled by the pattern (and target /
237
+ * include filter). An exact empty include contributes no filter suffix.
238
+ *
239
+ * @param args - the raw tool arguments; `pattern`, `path`, and `include` feed the title.
240
+ * @returns the generic card view (`kind: 'search'`) shown while the call runs.
241
+ */
242
+ export function presentGrepCall(args: { pattern: string; path?: string; include?: string }): GenericCallView {
243
+ const where = args.path !== undefined ? ` in ${args.path}` : ''
244
+ const filter = args.include !== undefined && args.include !== '' ? ` (${args.include})` : ''
245
+ return { card: 'generic', title: `Grep ${args.pattern}${where}${filter}`, kind: 'search', rawInput: args.pattern }
246
+ }
247
+
248
+ /**
249
+ * Completed-call presentation: the search card projected from the result's
250
+ * `presentationMeta` (matches grouped by file, with the truncation signal). A UI
251
+ * without a search card falls back to the raw `tool/result` content, so the view
252
+ * carries no result text of its own. Malformed or absent metadata (an obsolete or
253
+ * hand-edited replayed log) falls back to the generic card.
254
+ *
255
+ * @param _args - the raw tool arguments; unused, the view derives from the result.
256
+ * @param result - the final model-facing tool result carrying the projected metadata.
257
+ * @returns the search card view, or `undefined` for the generic fallback.
258
+ */
259
+ export function presentGrepResult(
260
+ _args: { pattern: string; path?: string; include?: string },
261
+ result: ToolResult,
262
+ ): SearchResultView | undefined {
263
+ if (result.isError) return undefined
264
+ const view = searchViewFromMeta(result.meta)
265
+ if (view === undefined || view.shape !== 'matches') return undefined
266
+ return view
267
+ }
268
+
269
+ /**
270
+ * Register the `grep` tool and its scope-aware system-prompt guidance.
271
+ *
272
+ * @param ctx - the plugin context; registrations are effects scoped to it, and
273
+ * execution uses its `subprocess` service.
274
+ * @param caps - the deployment's resolved grep caps (plugin config after defaulting).
275
+ */
276
+ export function applyGrepTool(ctx: Context, caps: GrepToolCaps): void {
277
+ ctx.systemPrompt.section({
278
+ name: 'tool:grep',
279
+ order: ctx.systemPrompt.getSectionOrder('TOOL_GREP'),
280
+ text: ({ scope }) => ctx.tools.get('grep', scope) === undefined
281
+ ? ''
282
+ : 'Use the grep tool — not shell grep or rg — to search file contents.'
283
+ + (ctx.tools.get('read', scope) === undefined ? '' : ' Use read on a matched file when you need surrounding context.'),
284
+ })
285
+
286
+ const tool = defineTool({
287
+ name: 'grep',
288
+ description: 'Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. '
289
+ + `Returns up to ${caps.maxMatches} matches; a larger result reports where the complete match list was saved.`,
290
+ parameters: {
291
+ pattern: { type: 'string', required: true, description: 'Regular expression to search for (ripgrep syntax).' },
292
+ path: { type: 'string', description: 'File or directory to search. Defaults to the session workspace; a relative path resolves against it.' },
293
+ include: { type: 'string', description: 'One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported.' },
294
+ },
295
+ timeoutMs: caps.timeoutMs,
296
+ // Matches record no file observation; over-cap spilling runs in model-ordered post-execute.
297
+ isConcurrencySafe: () => true,
298
+ output: {
299
+ schema: {
300
+ type: 'object',
301
+ additionalProperties: false,
302
+ properties: {
303
+ matches: {
304
+ type: 'array',
305
+ required: true,
306
+ items: {
307
+ type: 'object',
308
+ additionalProperties: false,
309
+ properties: {
310
+ path: { type: 'string', required: true },
311
+ lineNumber: { type: 'integer', required: true },
312
+ line: { type: 'string', required: true },
313
+ },
314
+ },
315
+ },
316
+ },
317
+ },
318
+ render: (_args, value) => [{
319
+ type: 'text',
320
+ text: formatRetainedGrep(retainGrepMatches(value.matches, caps.maxMatches, caps.maxLineBytes)),
321
+ }],
322
+ presentationMeta: (_args, value) =>
323
+ grepSearchMeta(retainGrepMatches(value.matches, caps.maxMatches, caps.maxLineBytes), caps.maxMetaBytes),
324
+ },
325
+ async execute(args, exec) {
326
+ const input = parseGrepArgs(args)
327
+ const run = await runRipgrep(ctx, exec, 'grep', buildGrepCommand(input), caps.rawOutputMaxBytes, caps.graceMs, caps.stderrMaxBytes)
328
+ if (run.noMatches) return { matches: [] }
329
+
330
+ const all: GrepMatch[] = []
331
+ for (const raw of parseGrepMatches(run.stdout)) {
332
+ const match: GrepMatch = {
333
+ path: toWorkdirRelative(raw.path, run.workdir),
334
+ lineNumber: raw.lineNumber,
335
+ line: raw.line,
336
+ }
337
+ all.push(match)
338
+ }
339
+ return { matches: all }
340
+ },
341
+ presentCall: presentGrepCall,
342
+ presentResult: presentGrepResult,
343
+ })
344
+ ctx.tools.register(tool)
345
+
346
+ ctx.on('tools/post-execute', async (exec, result, next) => {
347
+ const decision = await next()
348
+ const value = acceptedDirectCallValue(ctx, tool, exec, result, decision) as { matches: GrepMatch[] } | undefined
349
+ if (value === undefined) return decision
350
+ const matches = value.matches
351
+ if (matches.length <= caps.maxMatches) return decision
352
+ // The spill artifact holds the COMPLETE result: preview each line, but keep
353
+ // every match (no inline cap), so the recovery file is the full search.
354
+ const previewedAll = matches.map(match => ({ ...match, line: previewLine(match.line, caps.maxLineBytes) }))
355
+ const spillRef = await trySaveFormattedResult(
356
+ ctx,
357
+ exec,
358
+ 'grep-results.txt',
359
+ `Found ${matches.length} ${matchNoun(matches.length)}\n\n${formatGrepMatches(previewedAll)}`,
360
+ )
361
+ return {
362
+ kind: 'accept',
363
+ content: [{
364
+ type: 'text',
365
+ text: formatRetainedGrep(retainGrepMatches(matches, caps.maxMatches, caps.maxLineBytes), spillRef),
366
+ }],
367
+ ...decision.additionalContexts !== undefined ? { additionalContexts: decision.additionalContexts } : {},
368
+ }
369
+ })
370
+ }
package/src/index.ts ADDED
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The model-facing filesystem discovery tool suite (`glob`, `grep`) over the
3
+ * packaged ripgrep binary (`@vscode/ripgrep`). This single plugin registers
4
+ * both tools; the binary ships inside the npm dependency, so no system `rg`
5
+ * install and no shell layer is involved.
6
+ *
7
+ * ## Spawn-backed, not a `ctx.fs` provider method
8
+ *
9
+ * Local workspace discovery is a process-backed `rg` workflow, so these tools
10
+ * execute through `ctx.subprocess.spawn()` with fixed ripgrep argv templates —
11
+ * never `ctx.shell`, never `ctx.shell.start()`, never a model-visible background
12
+ * task. The tool layer owns schemas, argument validation, argv construction
13
+ * ({@link module:@deepseek-ai/dsh-tool-fs-search/glob} /
14
+ * {@link module:@deepseek-ai/dsh-tool-fs-search/grep}), result parsing,
15
+ * retention, formatted-result spill, and timeout declaration; the subprocess
16
+ * seam owns spawn execution, process-tree termination, environment scrubbing,
17
+ * and raw output capture. The package injects `tools`, `systemPrompt`, and
18
+ * `subprocess` — deliberately NOT `fs`, and `ctx.spillStore` is read
19
+ * opportunistically with `ctx.get()` because formatted-result spill is optional.
20
+ *
21
+ * Returned paths are displayed relative to the resolved workdir and are
22
+ * follow-up-readable only in co-located deployments where the workdir and the
23
+ * filesystem `read` root are the same workspace — a documented v1 deployment
24
+ * requirement, not runtime-validated.
25
+ *
26
+ * @module @deepseek-ai/dsh-tool-fs-search
27
+ */
28
+
29
+ import type {} from '@deepseek-ai/dsh-working-directory'
30
+ import type { Context } from '@deepseek-ai/cordis'
31
+ import z from '@deepseek-ai/schemastery'
32
+ import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
33
+ import { GLOB_MAX_RESULTS, applyGlobTool } from './glob.ts'
34
+ import { GREP_MAX_LINE_BYTES, GREP_MAX_MATCHES, applyGrepTool } from './grep.ts'
35
+ import { RAW_OUTPUT_MAX_BYTES, SEARCH_GRACE_MS, SEARCH_META_MAX_BYTES, SEARCH_STDERR_MAX_BYTES, SEARCH_TIMEOUT_MS } from './search-core.ts'
36
+
37
+ export { GLOB_MAX_RESULTS, GLOB_VCS_EXCLUDES, applyGlobTool, buildGlobCommand, formatGlobOutput, parseGlobArgs, presentGlobCall, presentGlobResult, sampleAcrossTopLevel } from './glob.ts'
38
+ export type { GlobInput, GlobSample, GlobToolCaps } from './glob.ts'
39
+ export {
40
+ GREP_MAX_LINE_BYTES,
41
+ GREP_MAX_MATCHES,
42
+ applyGrepTool,
43
+ buildGrepCommand,
44
+ formatGrepMatches,
45
+ formatGrepOutput,
46
+ parseGrepArgs,
47
+ parseGrepMatches,
48
+ presentGrepCall,
49
+ presentGrepResult,
50
+ } from './grep.ts'
51
+ export type { GrepInput, GrepToolCaps } from './grep.ts'
52
+ export {
53
+ RAW_OUTPUT_MAX_BYTES,
54
+ SEARCH_GRACE_MS,
55
+ SEARCH_META_MAX_BYTES,
56
+ SEARCH_STDERR_MAX_BYTES,
57
+ SEARCH_TIMEOUT_MS,
58
+ SearchError,
59
+ previewLine,
60
+ resolveRgPath,
61
+ runRipgrep,
62
+ toWorkdirRelative,
63
+ trySaveFormattedResult,
64
+ } from './search-core.ts'
65
+ export type { GrepMatch, RipgrepRun, SearchErrorCode } from './search-core.ts'
66
+
67
+ /** Cordis plugin name used by loader diagnostics. */
68
+ export const name = 'tool-fs-search'
69
+
70
+ /** Services required by the search tool suite (`spillStore` is optional, read via `ctx.get()`). */
71
+ export const inject = ['tools', 'systemPrompt', 'subprocess', 'workingDirectory']
72
+
73
+ /** Plugin config; over-cap glob sampling is an explicit deployment choice and the remaining fields have defaults. */
74
+ export interface Config {
75
+ /** Whether an over-cap `glob` page is sampled across top-level entries instead of taking the modification-time head. */
76
+ sampleOverCapGlobResults: boolean
77
+ /** Max paths one `glob` call retains inline; later paths go to the formatted spill file. */
78
+ globMaxResults?: number
79
+ /** Max flat matches one `grep` call retains inline; later matches go to the formatted spill file. */
80
+ grepMaxMatches?: number
81
+ /** Max bytes retained for one matched-line preview (the cut preserves UTF-8 boundaries). */
82
+ grepMaxLineBytes?: number
83
+ /** Max bytes of one search's serialized `presentationMeta`; trailing groups/paths drop past it so the persisted card stays bounded. */
84
+ searchMetaMaxBytes?: number
85
+ /** Max complete raw `rg` stdout bytes a search will parse; larger raw output fails with `SEARCH_RAW_OUTPUT_OVERFLOW`. */
86
+ rawOutputMaxBytes?: number
87
+ /** Terminate-escalation grace (ms), handed to the subprocess seam and bounded by `MAX_TIMER_DELAY_MS`. */
88
+ graceMs?: number
89
+ /** Max bytes retained for one search's stderr tail; the excerpt is embedded in `SEARCH_*` error messages, never shown on success. */
90
+ stderrMaxBytes?: number
91
+ /**
92
+ * Cooperative tool-call timeout budget (ms) on both tools, enforced by
93
+ * `@deepseek-ai/dsh-tool-call-timeout-policy` through `exec.signal`.
94
+ */
95
+ timeoutMs?: number
96
+ }
97
+
98
+ export const Config: z<Config> = z.object({
99
+ sampleOverCapGlobResults: z.boolean().required(),
100
+ globMaxResults: z.number().default(GLOB_MAX_RESULTS),
101
+ grepMaxMatches: z.number().default(GREP_MAX_MATCHES),
102
+ grepMaxLineBytes: z.number().default(GREP_MAX_LINE_BYTES),
103
+ searchMetaMaxBytes: z.number().default(SEARCH_META_MAX_BYTES),
104
+ rawOutputMaxBytes: z.number().default(RAW_OUTPUT_MAX_BYTES),
105
+ graceMs: z.number().default(SEARCH_GRACE_MS),
106
+ stderrMaxBytes: z.number().default(SEARCH_STDERR_MAX_BYTES),
107
+ timeoutMs: z.number().default(SEARCH_TIMEOUT_MS),
108
+ })
109
+
110
+ /** The shape after schemastery applied the defaults. */
111
+ type ResolvedConfig = Required<Config>
112
+
113
+ /** Every search cap counts items/bytes/milliseconds — a positive integer, or retention and timeout arithmetic misbehaves silently. */
114
+ function assertPositiveInteger(name: string, value: number): void {
115
+ if (!Number.isInteger(value) || value < 1) {
116
+ throw new Error(`tool-fs-search: ${name} must be a positive integer`)
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Register the `glob`/`grep` filesystem discovery tool suite. The packaged
122
+ * ripgrep binary is always available (an npm dependency), so registration is
123
+ * unconditional.
124
+ *
125
+ * @param ctx - plugin context; registrations are effects scoped to this plugin.
126
+ * @param config - resolved plugin configuration from schemastery.
127
+ */
128
+ // oxlint-disable-next-line typescript/require-await -- async keeps a load-time config rejection a rejection, not a synchronous throw
129
+ export async function apply(ctx: Context, config: Config): Promise<void> {
130
+ // schemastery (Config) has already filled every defaulted field.
131
+ const resolved = config as ResolvedConfig
132
+ assertPositiveInteger('globMaxResults', resolved.globMaxResults)
133
+ assertPositiveInteger('grepMaxMatches', resolved.grepMaxMatches)
134
+ assertPositiveInteger('grepMaxLineBytes', resolved.grepMaxLineBytes)
135
+ assertPositiveInteger('searchMetaMaxBytes', resolved.searchMetaMaxBytes)
136
+ assertPositiveInteger('rawOutputMaxBytes', resolved.rawOutputMaxBytes)
137
+ assertPositiveInteger('graceMs', resolved.graceMs)
138
+ if (resolved.graceMs > MAX_TIMER_DELAY_MS) {
139
+ throw new Error(`tool-fs-search: graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`)
140
+ }
141
+ assertPositiveInteger('stderrMaxBytes', resolved.stderrMaxBytes)
142
+ assertPositiveInteger('timeoutMs', resolved.timeoutMs)
143
+ applyGlobTool(ctx, {
144
+ sampleOverCapGlobResults: resolved.sampleOverCapGlobResults,
145
+ maxResults: resolved.globMaxResults,
146
+ maxMetaBytes: resolved.searchMetaMaxBytes,
147
+ rawOutputMaxBytes: resolved.rawOutputMaxBytes,
148
+ graceMs: resolved.graceMs,
149
+ stderrMaxBytes: resolved.stderrMaxBytes,
150
+ timeoutMs: resolved.timeoutMs,
151
+ })
152
+ applyGrepTool(ctx, {
153
+ maxMatches: resolved.grepMaxMatches,
154
+ maxLineBytes: resolved.grepMaxLineBytes,
155
+ maxMetaBytes: resolved.searchMetaMaxBytes,
156
+ rawOutputMaxBytes: resolved.rawOutputMaxBytes,
157
+ graceMs: resolved.graceMs,
158
+ stderrMaxBytes: resolved.stderrMaxBytes,
159
+ timeoutMs: resolved.timeoutMs,
160
+ })
161
+ }