@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.
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Result-time search-card presentation for `grep` and `glob`. Both tools land on
3
+ * one `card: 'search'` render intent ({@link SearchResultView}) with two
4
+ * `shape`-discriminated variants: `grep` projects its matches grouped by file
5
+ * ({@link SearchMatchesResultView}), `glob` projects a flat path list
6
+ * ({@link SearchPathsResultView}). This module owns the value→`presentationMeta`
7
+ * projection each tool declares and the defensive `meta`→view narrowing each
8
+ * tool's `presentResult` reads back on replay.
9
+ *
10
+ * The canonical value never crosses the wire — only the model-facing render text
11
+ * and this JSON `meta` do — so the structured shape a UI renders MUST ride in
12
+ * `meta`. Each projection consumes the SAME retained matches/paths the
13
+ * model-facing render consumes ({@link module:@deepseek-ai/dsh-tool-fs-search/search-core}
14
+ * `retainGrepMatches`/`retainGlobPaths`), so text and card agree about which
15
+ * results survived the inline cap, and reports `total` (every result found) and
16
+ * `truncated`, so a UI never presents a capped result as complete.
17
+ *
18
+ * A second, independent cap bounds the JSON `meta` itself: the retained matches
19
+ * of a broad search (hundreds of long lines) can still serialize to hundreds of
20
+ * kilobytes, and `meta` is persisted with the session log and re-sent on every
21
+ * request. {@link capMetaBytes} drops trailing groups/paths until the serialized
22
+ * `meta` fits `maxMetaBytes` and marks the result `truncated`; a deployment's
23
+ * final output budget (`dsh-spill-policy`) only shrinks `content`, never `meta`,
24
+ * so this projection owns keeping `meta` bounded.
25
+ *
26
+ * @module @deepseek-ai/dsh-tool-fs-search/presentation
27
+ */
28
+
29
+ import type {
30
+ SearchFileMatches,
31
+ SearchLineMatch,
32
+ SearchResultView,
33
+ } from '@deepseek-ai/dsh-tools'
34
+ import type { RetainedItems } from '@deepseek-ai/dsh-output-retention'
35
+ import type { GrepMatch } from './search-core.ts'
36
+
37
+ /**
38
+ * The retention fields a meta projection reads: the retained page, whether the
39
+ * complete result was capped, and the pre-cap total. Both a full
40
+ * {@link RetainedItems} (from `retainGrepMatches`) and `glob`'s sampled page
41
+ * satisfy this structural subset, so a projection consumes either without a fake
42
+ * `kept`/`omitted`.
43
+ */
44
+ type RetainedPage<T> = Pick<RetainedItems<T>, 'items' | 'truncated' | 'seen'>
45
+
46
+ /**
47
+ * The `grep`/`glob` tools' private `tool/result` `meta` payload: the capped,
48
+ * structured search result. Attached opaquely (as `JsonValue`) on the tool result
49
+ * and persisted with the session log, so `presentResult` reproduces the search
50
+ * card on replay. The `matches` shape carries the by-file groups; the `paths`
51
+ * shape carries the flat list. Both carry the pre-cap `total` and the `truncated`
52
+ * flag. The producing tool owns and narrows this opaque shape.
53
+ *
54
+ * The member shapes use object-literal `type` aliases rather than the
55
+ * {@link SearchFileMatches}/{@link SearchLineMatch} interfaces because only a type
56
+ * alias is assignable to the `JsonValue` index signature `presentationMeta`
57
+ * returns; the two are structurally identical, so the projected value still reads
58
+ * back as a {@link SearchResultView}.
59
+ */
60
+ export type SearchMeta =
61
+ | { shape: 'matches'; files: MetaFileMatches[]; truncated: boolean; total: number }
62
+ | { shape: 'paths'; paths: string[]; truncated: boolean; total: number }
63
+
64
+ /** One matched line in {@link SearchMeta} (the JSON-assignable form of {@link SearchLineMatch}). */
65
+ type MetaLineMatch = { lineNumber: number; line: string }
66
+
67
+ /** One file's grouped matches in {@link SearchMeta} (the JSON-assignable form of {@link SearchFileMatches}). */
68
+ type MetaFileMatches = { path: string; matches: MetaLineMatch[] }
69
+
70
+ /**
71
+ * Group flat matches by file (first-seen order) into the structured by-file shape
72
+ * a UI renders as expandable per-file groups. The grouping matches the
73
+ * model-facing text grouping
74
+ * ({@link module:@deepseek-ai/dsh-tool-fs-search/grep} `formatGrepMatches`), so
75
+ * card and text agree about file order and membership.
76
+ *
77
+ * @param matches - the retained matches to group, in output order.
78
+ * @returns one entry per file, in first-seen order.
79
+ */
80
+ export function groupMatchesByFile(matches: GrepMatch[]): MetaFileMatches[] {
81
+ const byFile = new Map<string, MetaLineMatch[]>()
82
+ for (const match of matches) {
83
+ const entry: MetaLineMatch = { lineNumber: match.lineNumber, line: match.line }
84
+ const group = byFile.get(match.path)
85
+ if (group !== undefined) group.push(entry)
86
+ else byFile.set(match.path, [entry])
87
+ }
88
+ return Array.from(byFile, ([path, fileMatches]) => ({ path, matches: fileMatches }))
89
+ }
90
+
91
+ /** The serialized UTF-8 byte size of one meta payload (the size persisted and re-sent). */
92
+ function metaBytes(meta: SearchMeta): number {
93
+ return Buffer.byteLength(JSON.stringify(meta), 'utf8')
94
+ }
95
+
96
+ /**
97
+ * Drop trailing top-level items (file groups or paths) until the serialized meta
98
+ * fits `maxMetaBytes`, marking the result `truncated` when anything was dropped.
99
+ * `total` is preserved (it counts what the search found, not what meta retains).
100
+ * A single item too large to fit on its own is kept: the invariant is a bounded
101
+ * payload wherever droppable, never an empty card that hides a real result.
102
+ *
103
+ * @param meta - the projected meta, already capped to the inline item count.
104
+ * @param maxMetaBytes - the serialized-meta byte budget.
105
+ * @returns the same meta when it fits, else a byte-bounded copy marked `truncated`.
106
+ */
107
+ function capMetaBytes(meta: SearchMeta, maxMetaBytes: number): SearchMeta {
108
+ if (metaBytes(meta) <= maxMetaBytes) return meta
109
+ if (meta.shape === 'matches') {
110
+ const files = [...meta.files]
111
+ while (files.length > 1 && metaBytes({ ...meta, files, truncated: true }) > maxMetaBytes) files.pop()
112
+ return { ...meta, files, truncated: true }
113
+ }
114
+ const paths = [...meta.paths]
115
+ while (paths.length > 1 && metaBytes({ ...meta, paths, truncated: true }) > maxMetaBytes) paths.pop()
116
+ return { ...meta, paths, truncated: true }
117
+ }
118
+
119
+ /**
120
+ * Project the retained `grep` matches into {@link SearchMeta} for the search
121
+ * card. Consumes the same {@link RetainedItems} the model-facing render consumes
122
+ * (preview budget and inline match cap already applied), groups the retained
123
+ * matches by file, reports `total` (every parsed match) and `truncated`, then
124
+ * bounds the serialized meta to `maxMetaBytes`.
125
+ *
126
+ * @param retained - the retention outcome over every parsed match (previewed, capped).
127
+ * @param maxMetaBytes - the serialized-meta byte budget.
128
+ * @returns the `matches`-shaped search metadata.
129
+ */
130
+ export function grepSearchMeta(retained: RetainedPage<GrepMatch>, maxMetaBytes: number): SearchMeta {
131
+ const meta: SearchMeta = {
132
+ shape: 'matches',
133
+ files: groupMatchesByFile(retained.items),
134
+ truncated: retained.truncated,
135
+ total: retained.seen,
136
+ }
137
+ return capMetaBytes(meta, maxMetaBytes)
138
+ }
139
+
140
+ /**
141
+ * Project the retained `glob` paths into {@link SearchMeta} for the search card.
142
+ * Consumes the same {@link RetainedItems} the model-facing render consumes (inline
143
+ * path cap already applied), reports `total` (every discovered path) and
144
+ * `truncated`, then bounds the serialized meta to `maxMetaBytes`.
145
+ *
146
+ * @param retained - the retention outcome over every discovered path (capped).
147
+ * @param maxMetaBytes - the serialized-meta byte budget.
148
+ * @returns the `paths`-shaped search metadata.
149
+ */
150
+ export function globSearchMeta(retained: RetainedPage<string>, maxMetaBytes: number): SearchMeta {
151
+ const meta: SearchMeta = {
152
+ shape: 'paths',
153
+ paths: retained.items,
154
+ truncated: retained.truncated,
155
+ total: retained.seen,
156
+ }
157
+ return capMetaBytes(meta, maxMetaBytes)
158
+ }
159
+
160
+ /** Whether `value` is a valid {@link SearchLineMatch} (defensive narrowing from opaque `meta`). */
161
+ function isSearchLineMatch(value: unknown): value is SearchLineMatch {
162
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
163
+ const { lineNumber, line } = value as Record<string, unknown>
164
+ return typeof lineNumber === 'number' && typeof line === 'string'
165
+ }
166
+
167
+ /** Whether `value` is a valid {@link SearchFileMatches} (defensive narrowing from opaque `meta`). */
168
+ function isSearchFileMatches(value: unknown): value is SearchFileMatches {
169
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
170
+ const { path, matches } = value as Record<string, unknown>
171
+ return typeof path === 'string' && Array.isArray(matches) && matches.every(isSearchLineMatch)
172
+ }
173
+
174
+ /**
175
+ * Narrow opaque live or replayed result metadata to a {@link SearchResultView}.
176
+ * Malformed metadata returns `undefined` so `presentResult` can fall back to the
177
+ * generic card instead of throwing during replay of an older or hand-edited log.
178
+ * The view carries no result text: a UI without a search card falls back to the
179
+ * raw `tool/result` content.
180
+ *
181
+ * A zero-result meta (`files: []` / `paths: []`) narrows to a valid empty card —
182
+ * unlike the mirrored `diffsFromMeta`, which rejects empty diffs, because a
183
+ * zero-match grep is a legitimate result a UI shows as "no matches", not an
184
+ * absent projection.
185
+ *
186
+ * @param meta - result metadata (the {@link SearchMeta} the tool projected).
187
+ * @returns the search view, or `undefined` for absent or malformed metadata.
188
+ */
189
+ export function searchViewFromMeta(meta: unknown): SearchResultView | undefined {
190
+ if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) return undefined
191
+ const record = meta as Record<string, unknown>
192
+ const { truncated, total } = record
193
+ if (typeof truncated !== 'boolean' || typeof total !== 'number') return undefined
194
+ if (record.shape === 'matches') {
195
+ const { files } = record
196
+ if (!Array.isArray(files) || !files.every(isSearchFileMatches)) return undefined
197
+ return { card: 'search', shape: 'matches', files: files, truncated, total }
198
+ }
199
+ if (record.shape === 'paths') {
200
+ const { paths } = record
201
+ if (!Array.isArray(paths) || !paths.every((path): path is string => typeof path === 'string')) return undefined
202
+ return { card: 'search', shape: 'paths', paths, truncated, total }
203
+ }
204
+ return undefined
205
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Minimal type surface for the `@vscode/ripgrep` package: an ESM module that
3
+ * resolves the platform ripgrep binary (`@vscode/ripgrep-<platform>-<arch>`
4
+ * optional dependency) and exports its absolute path as the named export
5
+ * `rgPath` (no bundled type declarations).
6
+ * @module @deepseek-ai/dsh-tool-fs-search/ripgrep-types
7
+ */
8
+
9
+ declare module '@vscode/ripgrep' {
10
+ /** Absolute path to the packaged ripgrep executable for the current platform. */
11
+ export const rgPath: string
12
+ }
@@ -0,0 +1,385 @@
1
+ /**
2
+ * Shared execution plumbing for the `glob` / `grep` search tools: the
3
+ * package-owned `SEARCH_*` error vocabulary, one spawn helper that runs the
4
+ * PACKAGED ripgrep binary (`@vscode/ripgrep`) with a plain argv vector and
5
+ * returns complete raw stdout, the best-effort formatted-result spill handoff,
6
+ * and workdir-relative path display.
7
+ *
8
+ * Both tools execute as ordinary foreground spawns through `ctx.subprocess` —
9
+ * never `ctx.shell`, never `ctx.shell.start()`, never a model-visible background
10
+ * task. The ripgrep binary ships inside the npm package, so no system `rg`
11
+ * install is required, and no shell layer exists between the argv vector and
12
+ * ripgrep, so no shell quoting is involved. Raw `rg` stdout is an internal
13
+ * transport detail: the tools request a per-run stdout capture budget from the
14
+ * subprocess seam, parse only complete in-memory stdout within
15
+ * `rawOutputMaxBytes`, and never read spill files. The model-facing recovery
16
+ * artifact is the formatted result saved through `ctx.spillStore.saveText()`
17
+ * ({@link trySaveFormattedResult}).
18
+ *
19
+ * @module @deepseek-ai/dsh-tool-fs-search/search-core
20
+ */
21
+
22
+ import { isAbsolute, relative, sep } from 'node:path'
23
+ import type { Context } from '@deepseek-ai/cordis'
24
+ import { spawnRipgrep } from '@deepseek-ai/dsh-util-ripgrep'
25
+ export { resolveRgPath } from '@deepseek-ai/dsh-util-ripgrep'
26
+ import { HarnessError } from '@deepseek-ai/dsh-llm'
27
+ import { ItemRetainer, TextRetainer } from '@deepseek-ai/dsh-output-retention'
28
+ import type { RetainedItems } from '@deepseek-ai/dsh-output-retention'
29
+ import type { SubprocessHandle, SubprocessOutcome, SubprocessOutputRead, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess'
30
+ import type { SaveTextSpill, SpillRef } from '@deepseek-ai/dsh-spill'
31
+ import type { ToolExecution } from '@deepseek-ai/dsh-tools'
32
+
33
+ /**
34
+ * Default cap on the complete raw `rg` stdout the tools will parse (the
35
+ * `rawOutputMaxBytes` config), matching Claude Code's ripgrep raw buffer.
36
+ */
37
+ export const RAW_OUTPUT_MAX_BYTES = 20_000_000
38
+
39
+ /**
40
+ * Default cooperative tool-call timeout budget in milliseconds (the `timeoutMs`
41
+ * config), attached to both tool definitions for
42
+ * `@deepseek-ai/dsh-tool-call-timeout-policy` to enforce through `exec.signal`.
43
+ */
44
+ export const SEARCH_TIMEOUT_MS = 30_000
45
+
46
+ /**
47
+ * Default cap in bytes on the retained stderr tail of one search run — a
48
+ * diagnostic excerpt only (the tool never reads a stderr spill path, and the
49
+ * collect disposition requests none).
50
+ */
51
+ export const SEARCH_STDERR_MAX_BYTES = 64 * 1024
52
+
53
+ /** Default terminate grace period for a search process (ms). */
54
+ export const SEARCH_GRACE_MS = 3_000
55
+
56
+ /**
57
+ * Default cap in bytes on one search's serialized `presentationMeta` (the
58
+ * `searchMetaMaxBytes` config). The inline match/path caps already bound the item
59
+ * COUNT, but retained matches of a broad search (many long lines) can still
60
+ * serialize to hundreds of kilobytes, and `meta` is persisted with the session
61
+ * log and re-sent on every request. A deployment's final output budget
62
+ * (`dsh-spill-policy`) only shrinks a result's `content`, never its `meta`, so the
63
+ * projection owns this cap. 64 KiB holds the full default-capped result of a
64
+ * typical search while bounding the pathological one.
65
+ */
66
+ export const SEARCH_META_MAX_BYTES = 65_536
67
+
68
+ /**
69
+ * Stable, machine-routable codes for search failures. Package-owned (not
70
+ * `FsErrorCode`) because these tools are spawn-backed discovery, not `ctx.fs`
71
+ * provider operations: `SEARCH_INVALID_PATTERN` — ripgrep rejected the regex or
72
+ * glob; `SEARCH_FAILED` — the search could not run or its output could not be
73
+ * parsed (a failed `rg` launch, inaccessible target, signal kill, malformed
74
+ * `--json`); `SEARCH_RAW_OUTPUT_OVERFLOW` — raw `rg` output exceeded
75
+ * `rawOutputMaxBytes` or stayed truncated after that requested stdout budget;
76
+ * `SEARCH_ABORTED` — the cooperative tool timeout or caller cancellation cut
77
+ * the search short.
78
+ */
79
+ export type SearchErrorCode =
80
+ | 'SEARCH_INVALID_PATTERN'
81
+ | 'SEARCH_FAILED'
82
+ | 'SEARCH_RAW_OUTPUT_OVERFLOW'
83
+ | 'SEARCH_ABORTED'
84
+
85
+ /**
86
+ * Typed search failure. Extends {@link HarnessError} so it carries a stable
87
+ * {@link SearchErrorCode} and chains `cause`; the tool registry exposes
88
+ * `{ name, code }` on `isError` results so retry/permission/UI layers can
89
+ * branch without parsing messages.
90
+ */
91
+ export class SearchError extends HarnessError {
92
+ override readonly code: SearchErrorCode
93
+
94
+ constructor(message: string, code: SearchErrorCode, options?: ErrorOptions) {
95
+ super(message, code, options)
96
+ this.code = code
97
+ }
98
+ }
99
+
100
+ /** The completed acquisition of one `rg` run: complete stdout plus the resolved workdir. */
101
+ export interface RipgrepRun {
102
+ /** Complete raw stdout retained by the subprocess seam within the requested cap. */
103
+ stdout: string
104
+ /** True when ripgrep exited 1: a successful search with zero results. */
105
+ noMatches: boolean
106
+ /** The resolved working directory the command ran in (the display-relativization base). */
107
+ workdir: string
108
+ }
109
+
110
+ /**
111
+ * The retained stderr tail as a diagnostic excerpt, with a truncation note when
112
+ * the subprocess seam dropped bytes.
113
+ */
114
+ function stderrExcerpt(stderrText: string, truncated: boolean): string {
115
+ const text = stderrText.trim()
116
+ if (text.length === 0) return ''
117
+ return truncated ? `${text} [stderr truncated]` : text
118
+ }
119
+
120
+ /**
121
+ * Classify a nonzero-exit `rg` run into the search error vocabulary. There is
122
+ * no shell layer, so an exit 127 or shell "command not found" text cannot
123
+ * occur — a launch failure rejects at spawn (see {@link runRipgrep}).
124
+ */
125
+ function classifyRunFailure(toolName: string, exitCode: number, stderrText: string, stderrTruncated: boolean): SearchError {
126
+ const stderr = stderrExcerpt(stderrText, stderrTruncated)
127
+ if (/regex parse error|error parsing glob/i.test(stderr)) {
128
+ return new SearchError(`${toolName} pattern rejected by ripgrep: ${stderr}`, 'SEARCH_INVALID_PATTERN')
129
+ }
130
+ return new SearchError(`${toolName} search failed (exit ${exitCode})${stderr.length > 0 ? `: ${stderr}` : ''}`, 'SEARCH_FAILED')
131
+ }
132
+
133
+ /**
134
+ * Acquire the COMPLETE raw stdout of a finished run, enforcing
135
+ * `rawOutputMaxBytes` on the in-memory transport. A truncated result means the
136
+ * subprocess seam could not retain complete stdout within the requested
137
+ * budget, so the tool fails clearly instead of parsing a silently-partial
138
+ * stream.
139
+ */
140
+ function completeStdout(toolName: string, stdout: SubprocessOutputRead, rawOutputMaxBytes: number): string {
141
+ const narrow = 'narrow pattern, path, or include and retry'
142
+ if (!stdout.lossy) {
143
+ const inlineBytes = Buffer.byteLength(stdout.text, 'utf8')
144
+ if (inlineBytes > rawOutputMaxBytes) {
145
+ throw new SearchError(
146
+ `${toolName} produced ${inlineBytes} bytes of raw output, over the ${rawOutputMaxBytes}-byte cap; ${narrow}`,
147
+ 'SEARCH_RAW_OUTPUT_OVERFLOW',
148
+ )
149
+ }
150
+ return stdout.text
151
+ }
152
+ throw new SearchError(
153
+ `${toolName} produced more raw output than the subprocess seam retained within the ${rawOutputMaxBytes}-byte cap; ${narrow}`,
154
+ 'SEARCH_RAW_OUTPUT_OVERFLOW',
155
+ )
156
+ }
157
+
158
+ /**
159
+ * Run the packaged ripgrep binary with a plain argv vector and return its
160
+ * complete raw stdout. The working directory is the calling agent's session
161
+ * current directory when available, else
162
+ * `process.cwd()`. `exec.signal` is forwarded so the cooperative tool timeout
163
+ * (`@deepseek-ai/dsh-tool-call-timeout-policy`) and caller cancellation terminate the
164
+ * process tree.
165
+ *
166
+ * The spawn is unconfined (a plain `ctx.subprocess` call), so `--no-config`
167
+ * is prepended: a host `RIPGREP_CONFIG_PATH` (or `rg.conf` next to the
168
+ * binary) can otherwise inject `--pre` and make ripgrep execute an arbitrary
169
+ * preprocessor for every matched file. The collect dispositions are the
170
+ * seam's diagnostic-tail shape (no spill files): the tools never read a raw
171
+ * spill path, and truncated stdout fails as `SEARCH_RAW_OUTPUT_OVERFLOW`.
172
+ *
173
+ * Exit semantics are tool-owned: exit 0 is success with results, exit 1 is
174
+ * success with zero results (`noMatches`), anything else throws a
175
+ * {@link SearchError} (abort/timeout → `SEARCH_ABORTED`, invalid pattern →
176
+ * `SEARCH_INVALID_PATTERN`, the rest → `SEARCH_FAILED` /
177
+ * `SEARCH_RAW_OUTPUT_OVERFLOW`). Both launch-time failure domains are
178
+ * classified: a synchronous throw at spawn CREATION (a NUL in argv, an abort
179
+ * racing the pre-check, a rejected `@vscode/ripgrep` resolution) reports that
180
+ * the command could not start, while a rejection of `handle.done` reports a
181
+ * provider failure without claiming whether execution began. Both become
182
+ * `SEARCH_FAILED` with the original as `cause`; an abort already observed by
183
+ * creation time becomes `SEARCH_ABORTED` instead.
184
+ *
185
+ * @param ctx - the plugin context; execution uses its `subprocess` service.
186
+ * @param exec - the tool-execution context; supplies the owning Agent and the abort signal.
187
+ * @param toolName - `glob` or `grep`, used in error messages.
188
+ * @param argv - the ripgrep arguments (every model value an unquoted argv element; no shell layer exists).
189
+ * @param rawOutputMaxBytes - cap on the complete raw stdout the tool will parse.
190
+ * @param graceMs - the seam's terminate-escalation grace period.
191
+ * @param stderrMaxBytes - cap on the retained stderr diagnostic tail.
192
+ * @returns the complete stdout, the zero-result flag, and the resolved workdir.
193
+ */
194
+ export async function runRipgrep(
195
+ ctx: Context,
196
+ exec: ToolExecution,
197
+ toolName: string,
198
+ argv: readonly string[],
199
+ rawOutputMaxBytes: number,
200
+ graceMs: number,
201
+ stderrMaxBytes: number,
202
+ ): Promise<RipgrepRun> {
203
+ if (exec.signal.aborted) {
204
+ throw new SearchError(`${toolName} was aborted before completion (tool timeout or caller cancellation)`, 'SEARCH_ABORTED')
205
+ }
206
+ const workdir = exec.agent === undefined
207
+ ? process.cwd()
208
+ : await ctx.workingDirectory.ensure(exec.agent, exec.signal)
209
+ let handle: SubprocessHandle
210
+ try {
211
+ handle = await spawnRipgrep(ctx.subprocess, {
212
+ argv,
213
+ cwd: workdir,
214
+ stdio: {
215
+ stdin: 'ignore',
216
+ stdout: { maxBytes: rawOutputMaxBytes },
217
+ stderr: { maxBytes: stderrMaxBytes },
218
+ },
219
+ graceMs,
220
+ signal: exec.signal,
221
+ } satisfies SubprocessSpawnSpec)
222
+ } catch (error: unknown) {
223
+ // Node's spawn() throws synchronously for a NUL in argv, and the local
224
+ // impl can throw synchronously when the signal aborts between the check
225
+ // above and this call (or when the platform-package resolution rejects).
226
+ // The static narrowing that proves this re-check "always false" cannot
227
+ // see AbortSignal state changes.
228
+ // oxlint-disable-next-line typescript/no-unnecessary-condition
229
+ if (exec.signal.aborted) {
230
+ throw new SearchError(`${toolName} was aborted before completion (tool timeout or caller cancellation)`, 'SEARCH_ABORTED')
231
+ }
232
+ throw new SearchError(`${toolName} could not start its search command (ripgrep launch failed)`, 'SEARCH_FAILED', { cause: error })
233
+ }
234
+ let outcome: SubprocessOutcome
235
+ try {
236
+ outcome = await handle.done
237
+ } catch (error: unknown) {
238
+ throw new SearchError(`${toolName} subprocess failed before reporting an outcome (ripgrep provider failure)`, 'SEARCH_FAILED', { cause: error })
239
+ }
240
+ const stdout = handle.collected.stdout?.readFrom(0)
241
+ const stderr = handle.collected.stderr?.readFrom(0)
242
+ if (stdout === undefined || stderr === undefined) {
243
+ throw new SearchError(`${toolName} search command produced no collected output streams`, 'SEARCH_FAILED')
244
+ }
245
+ // The signal can abort while the spawn is awaited; the static narrowing that
246
+ // proves this re-check "always false" cannot see AbortSignal state changes.
247
+ // oxlint-disable-next-line typescript/no-unnecessary-condition
248
+ if (exec.signal.aborted) {
249
+ throw new SearchError(`${toolName} was aborted before completion (tool timeout or caller cancellation)`, 'SEARCH_ABORTED')
250
+ }
251
+ if (outcome.signal !== null || outcome.exitCode === null) {
252
+ throw new SearchError(`${toolName} search command was killed by signal ${outcome.signal ?? '(unknown)'}`, 'SEARCH_FAILED')
253
+ }
254
+ if (outcome.exitCode !== 0 && outcome.exitCode !== 1) {
255
+ throw classifyRunFailure(toolName, outcome.exitCode, stderr.text, stderr.lossy)
256
+ }
257
+ const text = completeStdout(toolName, stdout, rawOutputMaxBytes)
258
+ return { stdout: text, noMatches: outcome.exitCode === 1, workdir }
259
+ }
260
+
261
+ /**
262
+ * Map an `rg` output path to its display form: absolute paths inside the
263
+ * resolved workdir become workdir-relative; everything else (relative output,
264
+ * paths outside the workdir) passes through unchanged. Display-only —
265
+ * returned paths are follow-up-readable in co-located workdir/filesystem
266
+ * deployments where both resolve the same workspace (the documented v1
267
+ * deployment requirement).
268
+ *
269
+ * @param path - one path as ripgrep printed it.
270
+ * @param workdir - the resolved workdir the command ran in.
271
+ * @returns the workdir-relative display path when possible, else `path` unchanged.
272
+ */
273
+ export function toWorkdirRelative(path: string, workdir: string): string {
274
+ if (!isAbsolute(path)) return path
275
+ const rel = relative(workdir, path)
276
+ if (rel.length === 0) return '.'
277
+ if (rel === '..' || rel.startsWith(`..${sep}`)) return path
278
+ return rel
279
+ }
280
+
281
+ /** One parsed match: the file, the 1-based line number, and the (possibly previewed) line text. */
282
+ export interface GrepMatch {
283
+ path: string
284
+ lineNumber: number
285
+ line: string
286
+ }
287
+
288
+ /**
289
+ * Bound one matched-line preview to `maxBytes` (UTF-8 boundary preserved) and
290
+ * mark the cut. The cap is a per-line budget fact; the complete line stays in
291
+ * the searched file for `read`.
292
+ *
293
+ * @param line - the matched line text (trailing newline already stripped).
294
+ * @param maxBytes - the preview budget in bytes.
295
+ * @returns the preview, suffixed with ` (line truncated)` when bytes were cut.
296
+ */
297
+ export function previewLine(line: string, maxBytes: number): string {
298
+ const retainer = new TextRetainer({ kind: 'head', maxBytes })
299
+ retainer.push(line)
300
+ const kept = retainer.finish()
301
+ return kept.truncated ? `${kept.text} (line truncated)` : kept.text
302
+ }
303
+
304
+ /**
305
+ * Apply the shared inline cap to a canonical `grep` match list: preview each
306
+ * retained line to `maxLineBytes` and keep the first `maxMatches`. The single
307
+ * retention pass both the model-facing render ({@link module:@deepseek-ai/dsh-tool-fs-search/grep}
308
+ * `formatGrepOutput`) and the search-card projection
309
+ * ({@link module:@deepseek-ai/dsh-tool-fs-search/presentation} `grepSearchMeta`)
310
+ * consume, so text and card never disagree about which matches survived.
311
+ *
312
+ * @param matches - every match the search parsed (the canonical value's matches).
313
+ * @param maxMatches - the inline match cap (the `grepMaxMatches` config).
314
+ * @param maxLineBytes - the per-matched-line preview budget in bytes.
315
+ * @returns the retention outcome over the previewed matches.
316
+ */
317
+ export function retainGrepMatches(matches: GrepMatch[], maxMatches: number, maxLineBytes: number): RetainedItems<GrepMatch> {
318
+ const retainer = new ItemRetainer<GrepMatch>({ kind: 'head', maxItems: maxMatches })
319
+ for (const match of matches) retainer.push({ ...match, line: previewLine(match.line, maxLineBytes) })
320
+ return retainer.finish()
321
+ }
322
+
323
+ /**
324
+ * Apply the shared inline cap to a canonical `glob` path list: keep the first
325
+ * `maxResults`. The single retention pass both the model-facing render and the
326
+ * search-card projection consume.
327
+ *
328
+ * @param paths - every path the search discovered (the canonical value's paths).
329
+ * @param maxResults - the inline path cap (the `globMaxResults` config).
330
+ * @returns the retention outcome over the paths.
331
+ */
332
+ export function retainGlobPaths(paths: string[], maxResults: number): RetainedItems<string> {
333
+ const retainer = new ItemRetainer<string>({ kind: 'head', maxItems: maxResults })
334
+ for (const path of paths) retainer.push(path)
335
+ return retainer.finish()
336
+ }
337
+
338
+ /**
339
+ * Best-effort save of one COMPLETE formatted search result through
340
+ * `ctx.spillStore.saveText()` — the model-facing recovery path for a capped
341
+ * result. `spillStore` is read with `ctx.get()` (not static inject) because
342
+ * formatted-result spill is optional; the spill owner is the calling agent's
343
+ * session header id and the source is the tool execution identity. A missing
344
+ * backend, a call with no session owner, or a `saveText()` rejection logs a
345
+ * warning and returns `undefined` — the caller keeps the inline result and
346
+ * reports that the complete result could not be saved; search success never
347
+ * turns into `isError` because spill storage is unavailable.
348
+ *
349
+ * @param ctx - the plugin context; `spillStore` is looked up opportunistically.
350
+ * @param exec - the tool-execution context; supplies the owning session, tool name, and call id.
351
+ * @param suggestedName - the backend-sanitized filename hint (e.g. `grep-results.txt`).
352
+ * @param content - the complete formatted result to persist.
353
+ * @returns the saved spill reference, or `undefined` when the result could not be saved.
354
+ */
355
+ export async function trySaveFormattedResult(
356
+ ctx: Context,
357
+ exec: ToolExecution,
358
+ suggestedName: string,
359
+ content: string,
360
+ ): Promise<SpillRef | undefined> {
361
+ const sessionId = exec.agent?.session.header.id
362
+ if (sessionId === undefined) {
363
+ ctx.logger.warn(`tool-fs-search: no session owner for ${exec.name} result; complete result not saved`)
364
+ return undefined
365
+ }
366
+ const spillStore = ctx.get('spillStore')
367
+ if (!spillStore) {
368
+ ctx.logger.warn(`tool-fs-search: no ctx.spillStore backend loaded; complete ${exec.name} result not saved`)
369
+ return undefined
370
+ }
371
+ const save: SaveTextSpill = {
372
+ owner: { sessionId },
373
+ source: { kind: 'tool', toolName: exec.name, callId: exec.callId, label: 'result' },
374
+ suggestedName,
375
+ content,
376
+ }
377
+ try {
378
+ return await spillStore.saveText(save)
379
+ } catch (error: unknown) {
380
+ // Best-effort: a storage failure must never fail the search or hide the
381
+ // inline result — the footer reports the unsaved remainder instead.
382
+ ctx.logger.warn(`tool-fs-search: saveText failed for ${exec.name}: ${String(error)}; complete result not saved`)
383
+ return undefined
384
+ }
385
+ }