@qmediat.io/gemini-code-context-mcp 1.4.0 → 1.5.0

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +36 -3
  3. package/dist/config.d.ts +23 -0
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/config.js +9 -0
  6. package/dist/config.js.map +1 -1
  7. package/dist/indexer/globs.d.ts +106 -0
  8. package/dist/indexer/globs.d.ts.map +1 -1
  9. package/dist/indexer/globs.js +151 -11
  10. package/dist/indexer/globs.js.map +1 -1
  11. package/dist/tools/agentic/sandbox.d.ts +55 -0
  12. package/dist/tools/agentic/sandbox.d.ts.map +1 -0
  13. package/dist/tools/agentic/sandbox.js +272 -0
  14. package/dist/tools/agentic/sandbox.js.map +1 -0
  15. package/dist/tools/agentic/workspace-tools.d.ts +104 -0
  16. package/dist/tools/agentic/workspace-tools.d.ts.map +1 -0
  17. package/dist/tools/agentic/workspace-tools.js +518 -0
  18. package/dist/tools/agentic/workspace-tools.js.map +1 -0
  19. package/dist/tools/ask-agentic.tool.d.ts +85 -0
  20. package/dist/tools/ask-agentic.tool.d.ts.map +1 -0
  21. package/dist/tools/ask-agentic.tool.js +727 -0
  22. package/dist/tools/ask-agentic.tool.js.map +1 -0
  23. package/dist/tools/ask.tool.d.ts +12 -12
  24. package/dist/tools/ask.tool.d.ts.map +1 -1
  25. package/dist/tools/ask.tool.js +522 -477
  26. package/dist/tools/ask.tool.js.map +1 -1
  27. package/dist/tools/code.tool.d.ts +8 -8
  28. package/dist/tools/code.tool.d.ts.map +1 -1
  29. package/dist/tools/code.tool.js +457 -423
  30. package/dist/tools/code.tool.js.map +1 -1
  31. package/dist/tools/index.d.ts.map +1 -1
  32. package/dist/tools/index.js +2 -0
  33. package/dist/tools/index.js.map +1 -1
  34. package/dist/tools/registry.d.ts +1 -1
  35. package/dist/tools/registry.d.ts.map +1 -1
  36. package/dist/tools/registry.js +8 -2
  37. package/dist/tools/registry.js.map +1 -1
  38. package/package.json +2 -2
@@ -0,0 +1,518 @@
1
+ /**
2
+ * Executor functions for the four Gemini function-call tools used by
3
+ * `ask_agentic`. Each executor takes a workspace-rooted sandbox (from
4
+ * `./sandbox.ts`) and returns a JSON-serialisable result payload, or
5
+ * throws `SandboxError` on security violations / missing files.
6
+ *
7
+ * Hard size limits applied unconditionally (Codex PR2 review critical):
8
+ * - `read_file` per-file: ≤ 200 000 bytes returned (files over that
9
+ * get head-truncated and the response carries `truncated: true` + size
10
+ * metadata so the model can reason about the gap).
11
+ * - `grep` per-call response: ≤ 500 000 bytes of JSON body (matches
12
+ * truncated to fit, response carries `truncated: true`).
13
+ * - `list_directory` / `find_files`: capped by entry count (`MAX_LIST_ENTRIES`
14
+ * / `MAX_FIND_MATCHES`, both small integers) rather than a byte budget —
15
+ * each entry is a short record so the resulting JSON is bounded well
16
+ * under any per-call ceiling.
17
+ *
18
+ * Together these protect the per-iteration token budget from a single
19
+ * minified bundle or a massive listing burning output tokens on one call.
20
+ */
21
+ import { readFile, readdir, realpath, stat } from 'node:fs/promises';
22
+ import { join } from 'node:path';
23
+ import { DEFAULT_EXCLUDE_DIRS_LOWER, DEFAULT_EXCLUDE_FILE_NAMES_LOWER, DEFAULT_INCLUDE_EXTENSIONS, } from '../../indexer/globs.js';
24
+ import { SandboxError, resolveInsideWorkspace } from './sandbox.js';
25
+ /** Hard upper bound on any single `read_file` response body. Bigger files
26
+ * get head-truncated + flagged — never fully expanded into the iteration.
27
+ *
28
+ * 200k bytes ≈ 50k tokens on source code — roughly 5% of a 1M context
29
+ * window, i.e. small enough that one errant read won't derail a 20-
30
+ * iteration budget, but large enough for practically every real source
31
+ * file (the handful of exceptions are generated bundles we already
32
+ * exclude via extension / default denylist). Adjustable via env if a
33
+ * repo has legitimately massive generated code.
34
+ */
35
+ const MAX_READ_BYTES = 200_000;
36
+ /** Hard upper bound on any single tool response JSON. Bounds what comes
37
+ * back from `list_directory` / `find_files` / `grep`. 500k bytes is ~125k
38
+ * tokens worst-case — still a lot, but keeps one bad response from
39
+ * blowing the iteration budget. */
40
+ const MAX_RESPONSE_BYTES = 500_000;
41
+ /** Max lines returned in one `read_file` when no explicit slice — forces
42
+ * the model to paginate very large source files. Used in addition to
43
+ * `MAX_READ_BYTES`: whichever limit hits first wins. */
44
+ const DEFAULT_READ_LINE_LIMIT = 500;
45
+ /** Cap on per-call `grep` matches. More = ask again with narrower pattern. */
46
+ const MAX_GREP_MATCHES = 100;
47
+ /** Cap on directory entries returned by `list_directory` per call. */
48
+ const MAX_LIST_ENTRIES = 200;
49
+ /** Cap on `find_files` matches per call. */
50
+ const MAX_FIND_MATCHES = 200;
51
+ /**
52
+ * Max recursion depth in `find_files` / `grep` walks. Protects against
53
+ * call-stack overflow on deep directory trees (generated code, malformed
54
+ * symlink loops) and bounds worst-case wall time. 20 levels comfortably
55
+ * covers real source repos (typical max depth 7-10) without false
56
+ * positives. Reported in PR #24 review by Grok.
57
+ */
58
+ const MAX_WALK_DEPTH = 20;
59
+ // ---------------------------------------------------------------------------
60
+ // Small glob → RegExp converter.
61
+ // Supports `*` (any-except-slash), `**/` (zero-or-more dirs), and `**` (any
62
+ // incl. slash). No `?`, no character classes, no `{a,b}` yet — matches the
63
+ // claim in the tool schema description so the model doesn't burn iterations
64
+ // on unsupported patterns.
65
+ //
66
+ // Implementation uses Private-Use-Area sentinel characters (\uE000 / \uE001)
67
+ // to separate the `**`/`**\/` replacement from the single-`*` replacement,
68
+ // avoiding the lookbehind approach that v1.5.0 initially shipped with. That
69
+ // earlier version used `(?<!\.)\*` to "protect" escaped dots, but inadvertently
70
+ // blocked the `*` replacement whenever it was preceded by ANY escaped dot
71
+ // in the pattern — so `index.*`, `README.*`, `src/**/index.*` silently
72
+ // matched nothing. Sentinel-based transform was empirically verified
73
+ // against all affected patterns during PR #24 round-2 review (Grok P0,
74
+ // GPT P1, Gemini P1, Copilot P1, self-review P0).
75
+ //
76
+ // PUA codepoints are chosen over ASCII control chars (\u0001/\u0002) so the
77
+ // Biome `noControlCharactersInRegex` lint stays happy; they're equivalently
78
+ // safe because glob input from the Gemini tool-call arguments is plain text
79
+ // and can't contain these codepoints organically.
80
+ //
81
+ // Also handles `**/` specifically so that `**/*.ts` matches BOTH
82
+ // `index.ts` (root) and `src/index.ts` (nested). The earlier version's
83
+ // `**` → `.*` transform required at least one separator, silently
84
+ // skipping root-level matches.
85
+ // ---------------------------------------------------------------------------
86
+ function globToRegExp(glob) {
87
+ const escaped = glob.replace(/[.+^$()|[\]{}\\]/g, '\\$&');
88
+ const pattern = escaped
89
+ .replace(/\*\*\//g, '\uE000') // sentinel: `**/` → zero-or-more dirs
90
+ .replace(/\*\*/g, '\uE001') // sentinel: bare `**` → any incl. slash
91
+ .replace(/\*/g, '[^/]*') // single `*` → no-slash segment
92
+ .replace(/\uE000/g, '(?:.*/)?') // dir-boundary expansion
93
+ .replace(/\uE001/g, '.*'); // bare globstar
94
+ // `i` flag: macOS (APFS) and Windows (NTFS) default to case-insensitive
95
+ // filesystems — so `App.TS` and `app.ts` refer to the same inode. The
96
+ // extension-gate lowercasing (above) handles the include-ext check, but
97
+ // the user-supplied pattern still needs case-insensitive matching here,
98
+ // otherwise `**/*.ts` skips `App.TS` even though `read_file` would allow
99
+ // it (PR #24 round-4, Gemini P2 — true parity with readFileExecutor).
100
+ return new RegExp(`^${pattern}$`, 'i');
101
+ }
102
+ /**
103
+ * List immediate children of `relPath` (non-recursive). Default-excluded
104
+ * dirs and denylisted filenames are silently omitted; the model sees only
105
+ * paths it is allowed to ask for via `read_file` / `grep`.
106
+ */
107
+ export async function listDirectoryExecutor(workspaceRoot, relPath) {
108
+ const target = await resolveInsideWorkspace(workspaceRoot, relPath);
109
+ let rawEntries;
110
+ try {
111
+ rawEntries = await readdir(target.absolutePath, { withFileTypes: true, encoding: 'utf8' });
112
+ }
113
+ catch (err) {
114
+ // Distinguish "path exists but is a file" from "path missing" — same
115
+ // taxonomy grep's `pathPrefix` already uses. Blanket NOT_FOUND here
116
+ // misled the model into retrying a non-existent alias when the real
117
+ // fix was calling `read_file`. PR #24 round-4 review (Copilot P1).
118
+ const code = typeof err === 'object' && err !== null && 'code' in err
119
+ ? String(err.code)
120
+ : undefined;
121
+ if (code === 'ENOTDIR') {
122
+ throw new SandboxError('NOT_A_DIRECTORY', `${target.relpath || '.'} is a file, not a directory — use read_file instead`, relPath);
123
+ }
124
+ throw new SandboxError('NOT_FOUND', `cannot list: ${String(err)}`, relPath);
125
+ }
126
+ const entries = [];
127
+ let totalEntries = 0;
128
+ for (const entry of rawEntries) {
129
+ const isFile = entry.isFile();
130
+ const isDir = entry.isDirectory();
131
+ if (!isFile && !isDir)
132
+ continue; // skip symlinks / sockets / fifos / etc.
133
+ // Skip excluded directories (user never gets to recurse into them).
134
+ if (isDir && DEFAULT_EXCLUDE_DIRS_LOWER.has(entry.name.toLowerCase()))
135
+ continue;
136
+ // Skip denylisted filenames.
137
+ if (isFile && DEFAULT_EXCLUDE_FILE_NAMES_LOWER.has(entry.name.toLowerCase()))
138
+ continue;
139
+ totalEntries += 1;
140
+ if (entries.length >= MAX_LIST_ENTRIES)
141
+ continue; // count but don't push
142
+ const child = {
143
+ relpath: target.relpath ? `${target.relpath}/${entry.name}` : entry.name,
144
+ type: isDir ? 'dir' : 'file',
145
+ };
146
+ if (isFile) {
147
+ try {
148
+ const s = await stat(join(target.absolutePath, entry.name));
149
+ child.size = s.size;
150
+ }
151
+ catch {
152
+ /* stat failure — omit size, still include entry */
153
+ }
154
+ }
155
+ entries.push(child);
156
+ }
157
+ return {
158
+ path: target.relpath || '.',
159
+ entries,
160
+ truncated: totalEntries > entries.length,
161
+ totalEntries,
162
+ };
163
+ }
164
+ /**
165
+ * Recursive glob search inside the workspace. Respects default excludes +
166
+ * extension gating (same rules as the eager scanner, so the model never
167
+ * sees paths it couldn't `read_file` on anyway — avoids a foot-gun where
168
+ * the model tries to open a secret it saw in a `find_files` response).
169
+ */
170
+ export async function findFilesExecutor(workspaceRoot, pattern) {
171
+ if (typeof pattern !== 'string' || pattern.trim().length === 0) {
172
+ throw new SandboxError('INVALID_INPUT', 'pattern is empty', pattern);
173
+ }
174
+ const regex = globToRegExp(pattern.trim());
175
+ const matches = [];
176
+ let totalMatches = 0;
177
+ // Track real (symlink-resolved) paths we've walked so a directory loop
178
+ // (e.g. `dir/self -> dir`) does not cause infinite recursion.
179
+ const seenReal = new Set();
180
+ let depthExceeded = false;
181
+ async function walk(currentAbs, currentRel, depth) {
182
+ if (depth > MAX_WALK_DEPTH) {
183
+ depthExceeded = true;
184
+ return;
185
+ }
186
+ // Guard against symlink loops via realpath memoisation.
187
+ try {
188
+ const real = await realpath(currentAbs);
189
+ if (seenReal.has(real))
190
+ return;
191
+ seenReal.add(real);
192
+ }
193
+ catch {
194
+ // Unreadable parent — nothing to walk into.
195
+ return;
196
+ }
197
+ let entries;
198
+ try {
199
+ entries = await readdir(currentAbs, { withFileTypes: true, encoding: 'utf8' });
200
+ }
201
+ catch {
202
+ return;
203
+ }
204
+ for (const entry of entries) {
205
+ if (entry.isDirectory()) {
206
+ if (DEFAULT_EXCLUDE_DIRS_LOWER.has(entry.name.toLowerCase()))
207
+ continue;
208
+ await walk(join(currentAbs, entry.name), currentRel ? `${currentRel}/${entry.name}` : entry.name, depth + 1);
209
+ continue;
210
+ }
211
+ if (!entry.isFile())
212
+ continue;
213
+ if (DEFAULT_EXCLUDE_FILE_NAMES_LOWER.has(entry.name.toLowerCase()))
214
+ continue;
215
+ const rel = currentRel ? `${currentRel}/${entry.name}` : entry.name;
216
+ // Only surface paths with at least one include-ext match — otherwise
217
+ // binary / generated files slip through find_files into the model's
218
+ // conversation even though `read_file` would reject them.
219
+ //
220
+ // Case-insensitive to mirror `readFileExecutor` (PR #24 round-4
221
+ // review by Gemini P2): otherwise `App.TS` / `Page.JSX` are readable
222
+ // but hidden from find_files/grep, leaving the model with an
223
+ // inconsistent view of the workspace.
224
+ const lowerName = entry.name.toLowerCase();
225
+ const hasIncludeExt = DEFAULT_INCLUDE_EXTENSIONS.some((ext) => {
226
+ if (ext.startsWith('.'))
227
+ return lowerName.endsWith(ext);
228
+ return lowerName === ext;
229
+ });
230
+ if (!hasIncludeExt)
231
+ continue;
232
+ if (!regex.test(rel))
233
+ continue;
234
+ totalMatches += 1;
235
+ if (matches.length < MAX_FIND_MATCHES)
236
+ matches.push(rel);
237
+ }
238
+ }
239
+ await walk(workspaceRoot, '', 0);
240
+ return {
241
+ pattern,
242
+ matches,
243
+ truncated: totalMatches > matches.length || depthExceeded,
244
+ totalMatches,
245
+ };
246
+ }
247
+ /**
248
+ * Read a file with bounded bytes + lines. Every response includes enough
249
+ * metadata (`totalLines`, `totalBytes`, `truncated`, `truncationReason`) for
250
+ * the model to request the next slice intelligently.
251
+ *
252
+ * Slicing semantics:
253
+ * - `startLine` / `endLine` are 1-indexed inclusive ranges when given.
254
+ * - Omit both → return the first `DEFAULT_READ_LINE_LIMIT` lines, up to
255
+ * `MAX_READ_BYTES`, whichever hits first.
256
+ */
257
+ export async function readFileExecutor(workspaceRoot, relPath, startLine, endLine) {
258
+ const target = await resolveInsideWorkspace(workspaceRoot, relPath);
259
+ // Extension gate — mirror of `DEFAULT_INCLUDE_EXTENSIONS` + block things
260
+ // that clearly aren't analyzable text. Avoid leaking binary blobs.
261
+ const lowerBase = target.relpath.toLowerCase();
262
+ const nameOnly = lowerBase.substring(lowerBase.lastIndexOf('/') + 1);
263
+ const looksLikeSource = DEFAULT_INCLUDE_EXTENSIONS.some((ext) => {
264
+ if (ext.startsWith('.'))
265
+ return lowerBase.endsWith(ext);
266
+ return nameOnly === ext.toLowerCase();
267
+ });
268
+ if (!looksLikeSource) {
269
+ throw new SandboxError('NON_SOURCE_FILE', `file extension not in allowed source set: ${target.relpath}`, relPath);
270
+ }
271
+ // Stat first so we never allocate a >200MB Buffer for a minified bundle.
272
+ // Files larger than 5× MAX_READ_BYTES (1MB) get rejected with a
273
+ // metadata-only response so the model can skip them instead of DOSing
274
+ // the process. Reported in PR #24 review by GPT.
275
+ let totalBytes;
276
+ try {
277
+ totalBytes = (await stat(target.absolutePath)).size;
278
+ }
279
+ catch (err) {
280
+ throw new SandboxError('NOT_FOUND', `stat failed: ${String(err)}`, relPath);
281
+ }
282
+ const HARD_FILE_SIZE_LIMIT = 5 * MAX_READ_BYTES; // 1MB
283
+ if (totalBytes > HARD_FILE_SIZE_LIMIT) {
284
+ // NOTE: the startLine/endLine slicing logic further below is gated on
285
+ // a successful `readFile` of the full content. For files over this
286
+ // hard cap we can't safely load the buffer at all (OOM risk), so we
287
+ // DON'T offer slicing as a workaround here — the message explicitly
288
+ // steers the model toward `grep` (which has its own streaming path)
289
+ // or skipping the file. Honest message vs. pre-round-3 wording that
290
+ // suggested slicing but never delivered. Reported in PR #24 round-3
291
+ // review by GPT.
292
+ return {
293
+ relpath: target.relpath,
294
+ content: `[file too large to inline: ${totalBytes} bytes > ${HARD_FILE_SIZE_LIMIT} byte cap. Use \`grep\` with a narrow pattern, or skip this file. Slicing via startLine/endLine is not supported at this size.]`,
295
+ startLine: 1,
296
+ endLine: 0,
297
+ totalLines: 0,
298
+ truncated: true,
299
+ truncationReason: 'max_bytes',
300
+ totalBytes,
301
+ };
302
+ }
303
+ let buffer;
304
+ try {
305
+ buffer = await readFile(target.absolutePath);
306
+ }
307
+ catch (err) {
308
+ throw new SandboxError('NOT_FOUND', `read failed: ${String(err)}`, relPath);
309
+ }
310
+ const fullText = buffer.toString('utf8');
311
+ const allLines = fullText.split('\n');
312
+ const totalLines = allLines.length;
313
+ // Clamp slice bounds defensively. Accept only finite positive ints.
314
+ const sliceStart = typeof startLine === 'number' && Number.isFinite(startLine) && startLine >= 1
315
+ ? Math.floor(startLine)
316
+ : 1;
317
+ const rawEnd = typeof endLine === 'number' && Number.isFinite(endLine) && endLine >= sliceStart
318
+ ? Math.floor(endLine)
319
+ : sliceStart + DEFAULT_READ_LINE_LIMIT - 1;
320
+ const sliceEnd = Math.min(totalLines, rawEnd);
321
+ const slice = allLines.slice(sliceStart - 1, sliceEnd);
322
+ let content = slice.join('\n');
323
+ let truncated = sliceEnd < totalLines;
324
+ let truncationReason = truncated
325
+ ? 'max_lines'
326
+ : undefined;
327
+ if (Buffer.byteLength(content, 'utf8') > MAX_READ_BYTES) {
328
+ // Byte-cap kicks in — trim the tail. Slice bytes, not characters, to
329
+ // match the limit exactly; then re-decode with `TextDecoder` using
330
+ // `ignoreBOM` + `fatal: false` so a mid-rune cut produces a single
331
+ // replacement character instead of a malformed string. Back off to
332
+ // the last newline to avoid emitting a partial line — that naturally
333
+ // chops any trailing replacement char as well. Reported in PR #24
334
+ // review by Gemini and Grok.
335
+ const cappedBuf = Buffer.from(content, 'utf8').subarray(0, MAX_READ_BYTES);
336
+ const decoder = new TextDecoder('utf-8', { fatal: false, ignoreBOM: true });
337
+ const cappedText = decoder.decode(cappedBuf);
338
+ const lastNewline = cappedText.lastIndexOf('\n');
339
+ // Two truncation paths:
340
+ // - If there's a newline in the capped region, drop everything after
341
+ // the last newline — that naturally trims any mid-rune replacement
342
+ // character that landed on the tail.
343
+ // - If there's NO newline (realistic for single-line minified
344
+ // content at 200 KB), the fallback used to keep the raw decoded
345
+ // text including a trailing U+FFFD. Strip trailing replacements
346
+ // explicitly. Reported in PR #24 round-3 review by Gemini +
347
+ // self-review.
348
+ content =
349
+ lastNewline > 0 ? cappedText.slice(0, lastNewline) : cappedText.replace(/\uFFFD+$/, '');
350
+ truncated = true;
351
+ truncationReason = 'max_bytes';
352
+ }
353
+ return {
354
+ relpath: target.relpath,
355
+ content,
356
+ startLine: sliceStart,
357
+ endLine: sliceStart + content.split('\n').length - 1,
358
+ totalLines,
359
+ truncated,
360
+ ...(truncationReason ? { truncationReason } : {}),
361
+ totalBytes,
362
+ };
363
+ }
364
+ /**
365
+ * Recursive regex search. Supports a basic anchored `pathPrefix` so the
366
+ * model can scope to a subtree. Pattern is compiled as JS RegExp — the
367
+ * model can use standard metacharacters.
368
+ *
369
+ * Hard caps:
370
+ * - `MAX_GREP_MATCHES` matches returned
371
+ * - each match line truncated to 500 chars (guard against minified
372
+ * lines flooding the payload)
373
+ */
374
+ export async function grepExecutor(workspaceRoot, pattern, pathPrefix) {
375
+ if (typeof pattern !== 'string' || pattern.length === 0) {
376
+ throw new SandboxError('INVALID_INPUT', 'grep pattern is empty', pattern);
377
+ }
378
+ let regex;
379
+ try {
380
+ regex = new RegExp(pattern);
381
+ }
382
+ catch (err) {
383
+ throw new SandboxError('INVALID_INPUT', `invalid regex: ${String(err)}`, pattern);
384
+ }
385
+ const matches = [];
386
+ let totalMatches = 0;
387
+ let respBytes = 0;
388
+ // Determine starting directory. When `pathPrefix` is given, validate it
389
+ // sits inside the workspace (reuse same sandbox logic as read_file), AND
390
+ // ensure it's a directory — grep'ing a single file via `pathPrefix`
391
+ // would silently return zero matches (readdir throws ENOTDIR, caught by
392
+ // the walk) which misleads the model. Reported in PR #24 review by Gemini.
393
+ let startAbs = workspaceRoot;
394
+ let startRel = '';
395
+ if (typeof pathPrefix === 'string' && pathPrefix.trim().length > 0) {
396
+ const resolved = await resolveInsideWorkspace(workspaceRoot, pathPrefix);
397
+ try {
398
+ const s = await stat(resolved.absolutePath);
399
+ if (!s.isDirectory()) {
400
+ throw new SandboxError('NOT_A_DIRECTORY', `pathPrefix must be a directory, got a file: ${resolved.relpath}. To search a single file, use read_file instead.`, pathPrefix);
401
+ }
402
+ }
403
+ catch (err) {
404
+ if (err instanceof SandboxError)
405
+ throw err;
406
+ throw new SandboxError('NOT_FOUND', `pathPrefix cannot be stat'd: ${String(err)}`, pathPrefix);
407
+ }
408
+ startAbs = resolved.absolutePath;
409
+ startRel = resolved.relpath;
410
+ }
411
+ const seenReal = new Set();
412
+ let depthExceeded = false;
413
+ async function walk(currentAbs, currentRel, depth) {
414
+ if (respBytes >= MAX_RESPONSE_BYTES)
415
+ return;
416
+ if (depth > MAX_WALK_DEPTH) {
417
+ depthExceeded = true;
418
+ return;
419
+ }
420
+ try {
421
+ const real = await realpath(currentAbs);
422
+ if (seenReal.has(real))
423
+ return;
424
+ seenReal.add(real);
425
+ }
426
+ catch {
427
+ return;
428
+ }
429
+ let entries;
430
+ try {
431
+ entries = await readdir(currentAbs, { withFileTypes: true, encoding: 'utf8' });
432
+ }
433
+ catch {
434
+ return;
435
+ }
436
+ for (const entry of entries) {
437
+ if (respBytes >= MAX_RESPONSE_BYTES)
438
+ return;
439
+ if (entry.isDirectory()) {
440
+ if (DEFAULT_EXCLUDE_DIRS_LOWER.has(entry.name.toLowerCase()))
441
+ continue;
442
+ await walk(join(currentAbs, entry.name), currentRel ? `${currentRel}/${entry.name}` : entry.name, depth + 1);
443
+ continue;
444
+ }
445
+ if (!entry.isFile())
446
+ continue;
447
+ if (DEFAULT_EXCLUDE_FILE_NAMES_LOWER.has(entry.name.toLowerCase()))
448
+ continue;
449
+ const rel = currentRel ? `${currentRel}/${entry.name}` : entry.name;
450
+ // Case-insensitive ext gating — same rationale as findFilesExecutor.
451
+ const lowerName = entry.name.toLowerCase();
452
+ const hasIncludeExt = DEFAULT_INCLUDE_EXTENSIONS.some((ext) => {
453
+ if (ext.startsWith('.'))
454
+ return lowerName.endsWith(ext);
455
+ return lowerName === ext;
456
+ });
457
+ if (!hasIncludeExt)
458
+ continue;
459
+ // Read full file (bounded by MAX_READ_BYTES via soft stat check).
460
+ const absFile = join(currentAbs, entry.name);
461
+ let fileSize = 0;
462
+ try {
463
+ fileSize = (await stat(absFile)).size;
464
+ }
465
+ catch {
466
+ continue;
467
+ }
468
+ if (fileSize > 5 * MAX_READ_BYTES)
469
+ continue; // skip large files in grep
470
+ let text;
471
+ try {
472
+ text = await readFile(absFile, 'utf8');
473
+ }
474
+ catch {
475
+ continue;
476
+ }
477
+ const lines = text.split('\n');
478
+ for (let i = 0; i < lines.length; i++) {
479
+ const line = lines[i];
480
+ if (line === undefined)
481
+ continue;
482
+ if (!regex.test(line))
483
+ continue;
484
+ totalMatches += 1;
485
+ if (matches.length >= MAX_GREP_MATCHES)
486
+ continue;
487
+ // Cap line length in the payload to 500 chars — minified files
488
+ // can have multi-megabyte single lines.
489
+ const trimmed = line.length > 500 ? `${line.slice(0, 500)}…` : line;
490
+ const match = { relpath: rel, line: i + 1, text: trimmed };
491
+ matches.push(match);
492
+ // Use UTF-8 byte length (not .length which is UTF-16 code units)
493
+ // so the 500k cap holds on CJK / emoji-heavy matches. `+32` is
494
+ // the envelope overhead (JSON keys, quotes, line-number int).
495
+ respBytes +=
496
+ Buffer.byteLength(match.text, 'utf8') + Buffer.byteLength(match.relpath, 'utf8') + 32;
497
+ }
498
+ }
499
+ }
500
+ await walk(startAbs, startRel, 0);
501
+ return {
502
+ pattern,
503
+ pathPrefix: pathPrefix ?? null,
504
+ matches,
505
+ truncated: totalMatches > matches.length || respBytes >= MAX_RESPONSE_BYTES || depthExceeded,
506
+ totalMatches,
507
+ };
508
+ }
509
+ /** Export knobs for tests to reference without re-declaring numeric values. */
510
+ export const AGENTIC_LIMITS = Object.freeze({
511
+ MAX_READ_BYTES,
512
+ MAX_RESPONSE_BYTES,
513
+ DEFAULT_READ_LINE_LIMIT,
514
+ MAX_GREP_MATCHES,
515
+ MAX_LIST_ENTRIES,
516
+ MAX_FIND_MATCHES,
517
+ });
518
+ //# sourceMappingURL=workspace-tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspace-tools.js","sourceRoot":"","sources":["../../../src/tools/agentic/workspace-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAGH,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACL,0BAA0B,EAC1B,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,YAAY,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAEpE;;;;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ask_agentic` tool — answers workspace questions without eager repo upload.
3
+ *
4
+ * Design — contrast with the eager `ask` tool:
5
+ * - `ask` : uploads workspace → Context Cache → single generateContent.
6
+ * Great for repeat queries on a cached repo; fails when
7
+ * the workspace tokens exceed `inputTokenLimit * guardRatio`.
8
+ * - `ask_agentic` : sends only the user's prompt + function-call tool
9
+ * declarations. Gemini decides which files to read via
10
+ * `list_directory` / `find_files` / `read_file` / `grep`.
11
+ * Loop runs until the model emits a text-only response
12
+ * (no more function calls), or until a guard trips
13
+ * (max iterations, token budget, no-progress loop).
14
+ *
15
+ * This path scales to any repo size — the model reads only what it needs
16
+ * for the specific question. Cost profile is different from `ask`: more
17
+ * API round trips, but total tokens usually much smaller on big repos
18
+ * (because you never upload files the question doesn't need).
19
+ *
20
+ * Codex PR consultation (gpt-5.3-codex, 2026-04-21) fed into the design:
21
+ * - Hard byte limits on tool responses (executors enforce)
22
+ * - `realpath` + root jail (sandbox module)
23
+ * - Prompt-injection defence in `systemInstruction`
24
+ * - No-progress detection (same call signature 3× → partial answer)
25
+ * - Parallel tool execution with concurrency cap
26
+ * - Recoverable-error via `functionResponse.error`; hard-fail for
27
+ * security / budget / timeouts
28
+ * - `notifications/progress` per iteration for UX
29
+ */
30
+ import { z } from 'zod';
31
+ import { type ToolDefinition } from './registry.js';
32
+ export declare const askAgenticInputSchema: z.ZodEffects<z.ZodObject<{
33
+ prompt: z.ZodString;
34
+ workspace: z.ZodOptional<z.ZodString>;
35
+ model: z.ZodOptional<z.ZodString>;
36
+ thinkingBudget: z.ZodOptional<z.ZodNumber>;
37
+ thinkingLevel: z.ZodOptional<z.ZodEnum<["MINIMAL", "LOW", "MEDIUM", "HIGH"]>>;
38
+ maxOutputTokens: z.ZodOptional<z.ZodNumber>;
39
+ maxIterations: z.ZodOptional<z.ZodNumber>;
40
+ maxTotalInputTokens: z.ZodOptional<z.ZodNumber>;
41
+ maxFilesRead: z.ZodOptional<z.ZodNumber>;
42
+ }, "strip", z.ZodTypeAny, {
43
+ prompt: string;
44
+ model?: string | undefined;
45
+ workspace?: string | undefined;
46
+ thinkingBudget?: number | undefined;
47
+ thinkingLevel?: "MINIMAL" | "LOW" | "MEDIUM" | "HIGH" | undefined;
48
+ maxOutputTokens?: number | undefined;
49
+ maxIterations?: number | undefined;
50
+ maxTotalInputTokens?: number | undefined;
51
+ maxFilesRead?: number | undefined;
52
+ }, {
53
+ prompt: string;
54
+ model?: string | undefined;
55
+ workspace?: string | undefined;
56
+ thinkingBudget?: number | undefined;
57
+ thinkingLevel?: "MINIMAL" | "LOW" | "MEDIUM" | "HIGH" | undefined;
58
+ maxOutputTokens?: number | undefined;
59
+ maxIterations?: number | undefined;
60
+ maxTotalInputTokens?: number | undefined;
61
+ maxFilesRead?: number | undefined;
62
+ }>, {
63
+ prompt: string;
64
+ model?: string | undefined;
65
+ workspace?: string | undefined;
66
+ thinkingBudget?: number | undefined;
67
+ thinkingLevel?: "MINIMAL" | "LOW" | "MEDIUM" | "HIGH" | undefined;
68
+ maxOutputTokens?: number | undefined;
69
+ maxIterations?: number | undefined;
70
+ maxTotalInputTokens?: number | undefined;
71
+ maxFilesRead?: number | undefined;
72
+ }, {
73
+ prompt: string;
74
+ model?: string | undefined;
75
+ workspace?: string | undefined;
76
+ thinkingBudget?: number | undefined;
77
+ thinkingLevel?: "MINIMAL" | "LOW" | "MEDIUM" | "HIGH" | undefined;
78
+ maxOutputTokens?: number | undefined;
79
+ maxIterations?: number | undefined;
80
+ maxTotalInputTokens?: number | undefined;
81
+ maxFilesRead?: number | undefined;
82
+ }>;
83
+ export type AskAgenticInput = z.infer<typeof askAgenticInputSchema>;
84
+ export declare const askAgenticTool: ToolDefinition<AskAgenticInput>;
85
+ //# sourceMappingURL=ask-agentic.tool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ask-agentic.tool.d.ts","sourceRoot":"","sources":["../../src/tools/ask-agentic.tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAaH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAgBxB,OAAO,EAAE,KAAK,cAAc,EAA2B,MAAM,eAAe,CAAC;AAO7E,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+C9B,CAAC;AAEL,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAsPpE,eAAO,MAAM,cAAc,EAAE,cAAc,CAAC,eAAe,CAa1D,CAAC"}