ceulen 0.5.1 → 0.7.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.
- package/CHANGELOG.md +317 -12
- package/README.md +87 -91
- package/extensions/lib/advisor-marker.ts +33 -0
- package/extensions/lib/panel.ts +25 -2
- package/extensions/lib/rate.ts +24 -0
- package/extensions/lib/registry.ts +93 -7
- package/extensions/lib/tools.ts +47 -0
- package/extensions/lib/usage-store.ts +33 -0
- package/extensions/modules/advisor/commands/advisor.ts +244 -0
- package/extensions/modules/advisor/configPanel.ts +194 -0
- package/extensions/modules/advisor/index.ts +217 -0
- package/extensions/modules/advisor/lib/config.ts +248 -0
- package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
- package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
- package/extensions/modules/advisor/lib/model-picker.ts +47 -0
- package/extensions/modules/advisor/lib/watcher.ts +286 -0
- package/extensions/modules/advisor/test/compliance.test.ts +125 -0
- package/extensions/modules/advisor/test/config.test.ts +202 -0
- package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
- package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
- package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
- package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
- package/extensions/modules/advisor/test/module.test.ts +586 -0
- package/extensions/modules/advisor/test/watcher.test.ts +478 -0
- package/extensions/modules/classifier/configPanel.ts +104 -0
- package/extensions/modules/classifier/index.ts +297 -0
- package/extensions/modules/classifier/lib/settings.ts +95 -0
- package/extensions/modules/classifier/test/classifier.test.ts +475 -0
- package/extensions/modules/composer/index.ts +152 -3
- package/extensions/modules/composer/lib/footer.ts +119 -0
- package/extensions/modules/composer/lib/shapes.ts +265 -26
- package/extensions/modules/composer/test/editor.test.ts +1 -1
- package/extensions/modules/composer/test/footer.test.ts +96 -0
- package/extensions/modules/composer/test/module.test.ts +113 -11
- package/extensions/modules/composer/test/screen.test.ts +29 -1
- package/extensions/modules/composer/test/shapes.test.ts +224 -8
- package/extensions/modules/config/defaultTools.ts +96 -0
- package/extensions/modules/config/index.ts +147 -7
- package/extensions/modules/config/piSettings.ts +254 -69
- package/extensions/modules/config/test/defaultTools.test.ts +122 -0
- package/extensions/modules/config/test/menu.test.ts +64 -0
- package/extensions/modules/config/test/panel.test.ts +38 -23
- package/extensions/modules/config/test/piSettings.test.ts +130 -3
- package/extensions/modules/config/test/renderTools.test.ts +71 -0
- package/extensions/modules/config/test/tools.test.ts +146 -0
- package/extensions/modules/fff/index.ts +2094 -0
- package/extensions/modules/fff/lib/query.ts +129 -0
- package/extensions/modules/fff/test/index.test.ts +607 -0
- package/extensions/modules/fff/test/query.test.ts +71 -0
- package/extensions/modules/munin/configPanel.ts +105 -0
- package/extensions/modules/munin/index.ts +641 -0
- package/extensions/modules/munin/lib/helpers.ts +471 -0
- package/extensions/modules/munin/lib/retry.ts +20 -0
- package/extensions/modules/munin/lib/sdk.ts +218 -0
- package/extensions/modules/munin/test/config.test.ts +168 -0
- package/extensions/modules/munin/test/configPanel.test.ts +161 -0
- package/extensions/modules/munin/test/extension.test.ts +224 -0
- package/extensions/modules/munin/test/helpers.test.ts +523 -0
- package/extensions/modules/munin/test/retry.test.ts +145 -0
- package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
- package/extensions/modules/plan/configPanel.ts +152 -0
- package/extensions/modules/plan/index.ts +917 -0
- package/extensions/modules/plan/lib/plan-tools.ts +72 -0
- package/extensions/modules/plan/lib/prompt.ts +65 -0
- package/extensions/modules/plan/lib/settings.ts +166 -0
- package/extensions/modules/plan/lib/shell-gate.ts +200 -0
- package/extensions/modules/plan/test/configPanel.test.ts +96 -0
- package/extensions/modules/plan/test/harness.ts +133 -0
- package/extensions/modules/plan/test/module.test.ts +305 -0
- package/extensions/modules/plan/test/settings.test.ts +114 -0
- package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
- package/extensions/modules/ponytail/index.ts +23 -73
- package/extensions/modules/ponytail/lib/config.ts +1 -6
- package/extensions/modules/ponytail/test/extension.test.ts +1 -85
- package/extensions/modules/repair/configPanel.ts +96 -0
- package/extensions/modules/repair/index.ts +414 -0
- package/extensions/modules/repair/lib/auto-bg.ts +333 -0
- package/extensions/modules/repair/lib/edit-repair.ts +155 -0
- package/extensions/modules/repair/lib/editor.ts +251 -0
- package/extensions/modules/repair/lib/guards.ts +34 -0
- package/extensions/modules/repair/lib/input-repair.ts +324 -0
- package/extensions/modules/repair/lib/patch.ts +481 -0
- package/extensions/modules/repair/lib/settings.ts +114 -0
- package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
- package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
- package/extensions/modules/repair/test/editor.test.ts +141 -0
- package/extensions/modules/repair/test/guards.test.ts +64 -0
- package/extensions/modules/repair/test/input-repair.test.ts +231 -0
- package/extensions/modules/repair/test/patch.test.ts +563 -0
- package/extensions/modules/repair/test/settings.test.ts +167 -0
- package/extensions/modules/repair/test/wrapper.test.ts +210 -0
- package/extensions/modules/router/commands/commands.ts +4 -0
- package/extensions/modules/router/lib/client.ts +61 -0
- package/extensions/modules/router/lib/provider.ts +34 -13
- package/extensions/modules/router/lib/systemone.ts +152 -0
- package/extensions/modules/router/test/unit.test.ts +179 -0
- package/extensions/modules/rtk/findFallback.js +68 -0
- package/extensions/modules/rtk/index.ts +248 -0
- package/extensions/modules/rtk/safe-rewrite.js +74 -0
- package/extensions/modules/rtk/test/findFallback.test.js +66 -0
- package/extensions/modules/rtk/test/index.test.js +131 -0
- package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
- package/extensions/modules/rtk/version-gate.js +34 -0
- package/extensions/modules/serena/index.ts +629 -0
- package/extensions/modules/serena/lib/detect.ts +73 -0
- package/extensions/modules/serena/lib/env.ts +76 -0
- package/extensions/modules/serena/lib/guidance.ts +26 -0
- package/extensions/modules/serena/lib/normalize.ts +27 -0
- package/extensions/modules/serena/lib/symbol-key.ts +20 -0
- package/extensions/modules/serena/lib/truncate.ts +20 -0
- package/extensions/modules/serena/test/env.test.ts +122 -0
- package/extensions/modules/serena/test/index.test.ts +347 -0
- package/extensions/modules/serena/test/worker.test.ts +562 -0
- package/extensions/modules/serena/worker.ts +858 -0
- package/extensions/modules/steering/configPanel.ts +122 -0
- package/extensions/modules/steering/index.ts +616 -0
- package/extensions/modules/steering/lib/anchor.ts +175 -0
- package/extensions/modules/steering/lib/errors.ts +253 -0
- package/extensions/modules/steering/lib/family.ts +33 -0
- package/extensions/modules/steering/lib/guidance.ts +172 -0
- package/extensions/modules/steering/lib/history.ts +170 -0
- package/extensions/modules/steering/lib/settings.ts +127 -0
- package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
- package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
- package/extensions/modules/steering/test/anchor.test.ts +160 -0
- package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
- package/extensions/modules/steering/test/errors.test.ts +309 -0
- package/extensions/modules/steering/test/family.test.ts +43 -0
- package/extensions/modules/steering/test/guidance.test.ts +357 -0
- package/extensions/modules/steering/test/harness.ts +93 -0
- package/extensions/modules/steering/test/history.test.ts +118 -0
- package/extensions/modules/steering/test/settings.test.ts +182 -0
- package/extensions/modules/steering/test/status.test.ts +71 -0
- package/extensions/modules/steering/test/toolCall.test.ts +99 -0
- package/extensions/modules/subagent/agents/planner.md +14 -0
- package/extensions/modules/subagent/agents/reviewer.md +42 -0
- package/extensions/modules/subagent/agents/scout.md +47 -0
- package/extensions/modules/subagent/agents/tester.md +12 -0
- package/extensions/modules/subagent/agents/worker.md +18 -0
- package/extensions/modules/subagent/configPanel.ts +219 -0
- package/extensions/modules/subagent/index.ts +2451 -0
- package/extensions/modules/subagent/lib/agents.ts +408 -0
- package/extensions/modules/subagent/lib/background.ts +383 -0
- package/extensions/modules/subagent/lib/herdr.ts +1019 -0
- package/extensions/modules/subagent/lib/history.ts +126 -0
- package/extensions/modules/subagent/lib/model.ts +156 -0
- package/extensions/modules/subagent/lib/render.ts +335 -0
- package/extensions/modules/subagent/lib/result.ts +110 -0
- package/extensions/modules/subagent/lib/roles.ts +296 -0
- package/extensions/modules/subagent/lib/routing.ts +223 -0
- package/extensions/modules/subagent/lib/runner.ts +559 -0
- package/extensions/modules/subagent/lib/schema.ts +21 -0
- package/extensions/modules/subagent/lib/security.ts +752 -0
- package/extensions/modules/subagent/lib/settings.ts +159 -0
- package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
- package/extensions/modules/subagent/lib/threads.ts +135 -0
- package/extensions/modules/subagent/lib/types.ts +18 -0
- package/extensions/modules/subagent/lib/widget.ts +475 -0
- package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
- package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
- package/extensions/modules/subagent/test/routing.test.ts +350 -0
- package/extensions/modules/subagent/test/widget.test.ts +208 -0
- package/extensions/modules/usage/index.ts +59 -16
- package/extensions/modules/usage/test/genrate.test.ts +70 -0
- package/extensions/modules/usage/test/parsers.test.ts +13 -0
- package/extensions/modules/ux/UPSTREAM +24 -0
- package/extensions/modules/ux/index.ts +393 -0
- package/extensions/modules/ux/lib/audit.ts +562 -0
- package/extensions/modules/ux/lib/config.ts +136 -0
- package/extensions/modules/ux/lib/instructions.ts +77 -0
- package/extensions/modules/ux/test/audit.test.ts +756 -0
- package/extensions/modules/ux/test/extension.test.ts +394 -0
- package/extensions/modules/ux/test/instructions.test.ts +19 -0
- package/extensions/modules/web/configPanel.ts +193 -0
- package/extensions/modules/web/index.ts +978 -0
- package/extensions/modules/web/lib/agy.ts +209 -0
- package/extensions/modules/web/lib/brave.ts +42 -0
- package/extensions/modules/web/lib/cdp.ts +686 -0
- package/extensions/modules/web/lib/chatapi.ts +101 -0
- package/extensions/modules/web/lib/chatgpt.ts +796 -0
- package/extensions/modules/web/lib/chrome.ts +328 -0
- package/extensions/modules/web/lib/config.ts +136 -0
- package/extensions/modules/web/lib/content.ts +99 -0
- package/extensions/modules/web/lib/crawl4ai.ts +172 -0
- package/extensions/modules/web/lib/extract.ts +235 -0
- package/extensions/modules/web/lib/firecrawl.ts +56 -0
- package/extensions/modules/web/lib/format.ts +197 -0
- package/extensions/modules/web/lib/gemini-auth.ts +286 -0
- package/extensions/modules/web/lib/gemini-dr.ts +338 -0
- package/extensions/modules/web/lib/gemini.ts +551 -0
- package/extensions/modules/web/lib/imageapi.ts +559 -0
- package/extensions/modules/web/lib/retry.ts +71 -0
- package/extensions/modules/web/lib/search.ts +237 -0
- package/extensions/modules/web/lib/searxng.ts +69 -0
- package/extensions/modules/web/lib/settings.ts +148 -0
- package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
- package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
- package/extensions/modules/web/test/agy.test.ts +383 -0
- package/extensions/modules/web/test/cdp.test.ts +717 -0
- package/extensions/modules/web/test/chat.test.ts +171 -0
- package/extensions/modules/web/test/chatgpt.test.ts +633 -0
- package/extensions/modules/web/test/chrome.test.ts +282 -0
- package/extensions/modules/web/test/config.test.ts +218 -0
- package/extensions/modules/web/test/configPanel.test.ts +132 -0
- package/extensions/modules/web/test/crawl.test.ts +134 -0
- package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
- package/extensions/modules/web/test/extension.test.ts +118 -0
- package/extensions/modules/web/test/extract.test.ts +436 -0
- package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
- package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
- package/extensions/modules/web/test/fixtures/interaction.html +31 -0
- package/extensions/modules/web/test/format.test.ts +230 -0
- package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
- package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
- package/extensions/modules/web/test/gemini.test.ts +472 -0
- package/extensions/modules/web/test/hook.test.ts +101 -0
- package/extensions/modules/web/test/image.test.ts +1089 -0
- package/extensions/modules/web/test/retry.test.ts +119 -0
- package/extensions/modules/web/test/screenshot.test.ts +109 -0
- package/extensions/modules/web/test/search.test.ts +210 -0
- package/extensions/modules/web/test/settings.test.ts +165 -0
- package/extensions/modules/web/test/skill.test.ts +72 -0
- package/extensions/modules/web/types.d.ts +3 -0
- package/extensions/modules/web/vendor/package.json +1 -0
- package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
- package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
- package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
- package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
- package/extensions/modules/web/vendor/readability/index.js +9 -0
- package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
- package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
- package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
- package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
- package/extensions/modules/zai/configPanel.ts +151 -0
- package/extensions/modules/zai/index.ts +186 -0
- package/extensions/modules/zai/lib/anthropic.ts +159 -0
- package/extensions/modules/zai/lib/settings.ts +198 -0
- package/extensions/modules/zai/lib/signing.ts +718 -0
- package/extensions/modules/zai/lib/throttle.ts +198 -0
- package/extensions/modules/zai/test/anthropic.test.ts +132 -0
- package/extensions/modules/zai/test/configPanel.test.ts +207 -0
- package/extensions/modules/zai/test/extension.test.ts +249 -0
- package/extensions/modules/zai/test/settings.test.ts +183 -0
- package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
- package/extensions/modules/zai/test/signing.test.ts +345 -0
- package/extensions/modules/zai/test/throttle.test.ts +329 -0
- package/package.json +19 -4
- package/scripts/validate-themes.mjs +75 -0
- package/skills/munin/SKILL.md +117 -0
- package/skills/ux-capture/SKILL.md +202 -0
- package/skills/ux-design/SKILL.md +279 -0
- package/skills/ux-presets/SKILL.md +484 -0
- package/skills/ux-routing/SKILL.md +46 -0
- package/skills/web/SKILL.md +153 -0
- package/themes/alabaster.json +93 -0
- package/themes/amethyst.json +96 -0
- package/themes/anthracite.json +93 -0
- package/themes/basalt.json +91 -0
- package/themes/birch.json +95 -0
- package/themes/catppuccin-mocha.json +91 -0
- package/themes/dark-abyss.json +91 -0
- package/themes/dark-arctic.json +104 -0
- package/themes/dark-aurora.json +95 -0
- package/themes/dark-catppuccin.json +107 -0
- package/themes/dark-cavern.json +91 -0
- package/themes/dark-celestial.json +106 -0
- package/themes/dark-copper.json +95 -0
- package/themes/dark-cosmos.json +90 -0
- package/themes/dark-cyberpunk.json +102 -0
- package/themes/dark-dracula.json +98 -0
- package/themes/dark-eclipse.json +91 -0
- package/themes/dark-ember.json +95 -0
- package/themes/dark-equinox.json +90 -0
- package/themes/dark-forest.json +96 -0
- package/themes/dark-github.json +105 -0
- package/themes/dark-gruvbox.json +112 -0
- package/themes/dark-lavender.json +95 -0
- package/themes/dark-lunar.json +89 -0
- package/themes/dark-midnight.json +95 -0
- package/themes/dark-monochrome.json +94 -0
- package/themes/dark-monokai.json +98 -0
- package/themes/dark-nebula.json +90 -0
- package/themes/dark-neon-noir.json +100 -0
- package/themes/dark-nord.json +98 -0
- package/themes/dark-ocean.json +101 -0
- package/themes/dark-one.json +100 -0
- package/themes/dark-poimandres.json +115 -0
- package/themes/dark-rainforest.json +91 -0
- package/themes/dark-reef.json +91 -0
- package/themes/dark-retro.json +92 -0
- package/themes/dark-rose-pine.json +96 -0
- package/themes/dark-sakura.json +95 -0
- package/themes/dark-slate.json +95 -0
- package/themes/dark-solarized.json +97 -0
- package/themes/dark-solstice.json +90 -0
- package/themes/dark-starfall.json +91 -0
- package/themes/dark-sunset.json +99 -0
- package/themes/dark-swamp.json +90 -0
- package/themes/dark-synthwave.json +103 -0
- package/themes/dark-taiga.json +91 -0
- package/themes/dark-terminal.json +95 -0
- package/themes/dark-tokyo-night.json +101 -0
- package/themes/dark-tundra.json +91 -0
- package/themes/dark-twilight.json +91 -0
- package/themes/dark-volcanic.json +91 -0
- package/themes/dark.json +80 -0
- package/themes/graphite.json +92 -0
- package/themes/light-arctic.json +107 -0
- package/themes/light-aurora-day.json +91 -0
- package/themes/light-canyon.json +91 -0
- package/themes/light-catppuccin.json +106 -0
- package/themes/light-cirrus.json +90 -0
- package/themes/light-coral.json +95 -0
- package/themes/light-cyberpunk.json +96 -0
- package/themes/light-dawn.json +90 -0
- package/themes/light-dunes.json +91 -0
- package/themes/light-eucalyptus.json +95 -0
- package/themes/light-forest.json +100 -0
- package/themes/light-frost.json +95 -0
- package/themes/light-github.json +115 -0
- package/themes/light-glacier.json +91 -0
- package/themes/light-gruvbox.json +108 -0
- package/themes/light-haze.json +90 -0
- package/themes/light-honeycomb.json +95 -0
- package/themes/light-lagoon.json +91 -0
- package/themes/light-lavender.json +95 -0
- package/themes/light-meadow.json +91 -0
- package/themes/light-mint.json +95 -0
- package/themes/light-monochrome.json +101 -0
- package/themes/light-ocean.json +99 -0
- package/themes/light-one.json +99 -0
- package/themes/light-opal.json +91 -0
- package/themes/light-orchard.json +91 -0
- package/themes/light-paper.json +95 -0
- package/themes/light-poimandres.json +115 -0
- package/themes/light-prism.json +90 -0
- package/themes/light-retro.json +98 -0
- package/themes/light-sand.json +95 -0
- package/themes/light-savanna.json +91 -0
- package/themes/light-solarized.json +102 -0
- package/themes/light-soleil.json +90 -0
- package/themes/light-sunset.json +99 -0
- package/themes/light-synthwave.json +98 -0
- package/themes/light-tokyo-night.json +111 -0
- package/themes/light-wetland.json +91 -0
- package/themes/light-zenith.json +89 -0
- package/themes/light.json +80 -0
- package/themes/limestone.json +94 -0
- package/themes/mahogany.json +97 -0
- package/themes/marble.json +93 -0
- package/themes/mirage.json +79 -0
- package/themes/obsidian.json +91 -0
- package/themes/onyx.json +91 -0
- package/themes/pearl.json +93 -0
- package/themes/porcelain.json +91 -0
- package/themes/quartz.json +96 -0
- package/themes/sandstone.json +95 -0
- package/themes/titanium.json +90 -0
|
@@ -0,0 +1,2094 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-fff: FFF-powered file search extension for pi
|
|
3
|
+
*
|
|
4
|
+
* Overrides built-in `find` and `grep` tools with FFF and adds FFF-backed
|
|
5
|
+
* @-mention autocomplete suggestions to the interactive editor.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import {
|
|
10
|
+
DEFAULT_MAX_BYTES,
|
|
11
|
+
DEFAULT_MAX_LINES,
|
|
12
|
+
formatSize,
|
|
13
|
+
truncateHead,
|
|
14
|
+
type TruncationResult,
|
|
15
|
+
} from "@earendil-works/pi-coding-agent";
|
|
16
|
+
import {
|
|
17
|
+
type AutocompleteItem,
|
|
18
|
+
type AutocompleteProvider,
|
|
19
|
+
Text,
|
|
20
|
+
} from "@earendil-works/pi-tui";
|
|
21
|
+
import type {
|
|
22
|
+
GrepCursor,
|
|
23
|
+
GrepMatch,
|
|
24
|
+
GrepMode,
|
|
25
|
+
GrepResult,
|
|
26
|
+
MixedItem,
|
|
27
|
+
SearchResult,
|
|
28
|
+
} from "@ff-labs/fff-node";
|
|
29
|
+
import { FileFinder } from "@ff-labs/fff-node";
|
|
30
|
+
import { Type } from "typebox";
|
|
31
|
+
import { closeSync, fstatSync, openSync, readSync, statSync } from "node:fs";
|
|
32
|
+
import path from "node:path";
|
|
33
|
+
import { StringDecoder } from "node:string_decoder";
|
|
34
|
+
import { buildQuery, normalizeExcludes, normalizePathConstraint } from "./lib/query";
|
|
35
|
+
import { readDisabledTools } from "../../lib/tools";
|
|
36
|
+
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
// Constants
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
const DEFAULT_GREP_LIMIT = 20;
|
|
42
|
+
const DEFAULT_FIND_LIMIT = 30;
|
|
43
|
+
const GREP_MAX_LINE_LENGTH = 500;
|
|
44
|
+
const GREP_MAX_FILE_SIZE = 10 * 1024 * 1024;
|
|
45
|
+
|
|
46
|
+
const VALID_MODES = ["tools-and-ui", "tools-only", "override"] as const;
|
|
47
|
+
type FffMode = (typeof VALID_MODES)[number];
|
|
48
|
+
|
|
49
|
+
// ---------------------------------------------------------------------------
|
|
50
|
+
// Cursor store — simple bounded Map for pagination cursors
|
|
51
|
+
// ---------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
export class BoundedMap<V> {
|
|
54
|
+
private map = new Map<string, V>();
|
|
55
|
+
private counter = 0;
|
|
56
|
+
constructor(private maxSize: number, private prefix: string) {}
|
|
57
|
+
store(value: V): string {
|
|
58
|
+
const id = `${this.prefix}:${++this.counter}`;
|
|
59
|
+
this.map.set(id, value);
|
|
60
|
+
if (this.map.size > this.maxSize) {
|
|
61
|
+
const first = this.map.keys().next().value;
|
|
62
|
+
if (first) this.map.delete(first);
|
|
63
|
+
}
|
|
64
|
+
return id;
|
|
65
|
+
}
|
|
66
|
+
get(id: string): V | undefined {
|
|
67
|
+
const value = this.map.get(id);
|
|
68
|
+
// LRU: re-insert so a live cursor never becomes the eviction candidate.
|
|
69
|
+
if (value !== undefined) {
|
|
70
|
+
this.map.delete(id);
|
|
71
|
+
this.map.set(id, value);
|
|
72
|
+
}
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface GrepCursorState {
|
|
78
|
+
tool: "grep";
|
|
79
|
+
cwd: string;
|
|
80
|
+
cursor: GrepCursor;
|
|
81
|
+
query: string;
|
|
82
|
+
scope?: string;
|
|
83
|
+
hiddenFile?: boolean;
|
|
84
|
+
exclude?: string | string[];
|
|
85
|
+
glob?: string;
|
|
86
|
+
mode: GrepMode;
|
|
87
|
+
smartCase: boolean;
|
|
88
|
+
context?: number;
|
|
89
|
+
outputMode: GrepOutputMode;
|
|
90
|
+
pageSize: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface MultiGrepCursorState {
|
|
94
|
+
tool: "multi";
|
|
95
|
+
cwd: string;
|
|
96
|
+
cursor: GrepCursor;
|
|
97
|
+
patterns: string[];
|
|
98
|
+
scope?: string;
|
|
99
|
+
hiddenFile?: boolean;
|
|
100
|
+
exclude?: string | string[];
|
|
101
|
+
constraints?: string;
|
|
102
|
+
smartCase: boolean;
|
|
103
|
+
context?: number;
|
|
104
|
+
outputMode: GrepOutputMode;
|
|
105
|
+
pageSize: number;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
type StoredGrepCursor = GrepCursorState | MultiGrepCursorState;
|
|
109
|
+
const cursorStore = new BoundedMap<StoredGrepCursor>(200, "grep");
|
|
110
|
+
|
|
111
|
+
// Find pagination uses a page-index cursor: native `fileSearch` takes
|
|
112
|
+
// pageIndex/pageSize, so the cursor is just the next page index paired with
|
|
113
|
+
// the query+limit that produced it. Stored tokens are opaque IDs to the agent.
|
|
114
|
+
interface FindCursor {
|
|
115
|
+
cwd: string;
|
|
116
|
+
query: string;
|
|
117
|
+
pattern: string;
|
|
118
|
+
pageSize: number;
|
|
119
|
+
nextPageIndex: number;
|
|
120
|
+
scope?: string;
|
|
121
|
+
exclude?: string | string[];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const findCursorStore = new BoundedMap<FindCursor>(200, "find");
|
|
125
|
+
|
|
126
|
+
// ---------------------------------------------------------------------------
|
|
127
|
+
// Output formatting helpers
|
|
128
|
+
// ---------------------------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
function truncateLine(line: string, max = GREP_MAX_LINE_LENGTH): string {
|
|
131
|
+
const trimmed = line.trimEnd();
|
|
132
|
+
return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max)}...`;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function stripLeadingAt(value: string): string {
|
|
136
|
+
return value.trim().replace(/^@/, "");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function companionStem(filePath: string): string {
|
|
140
|
+
return path.posix.basename(filePath)
|
|
141
|
+
.replace(/\.(test|spec|story|stories|type|types|style|styles|d|module)\./g, ".")
|
|
142
|
+
.replace(/\.[^.]+$/, "");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function boundedText(text: string): { text: string; truncation?: TruncationResult } {
|
|
146
|
+
const truncation = truncateHead(text, {
|
|
147
|
+
maxLines: DEFAULT_MAX_LINES,
|
|
148
|
+
maxBytes: DEFAULT_MAX_BYTES,
|
|
149
|
+
});
|
|
150
|
+
if (!truncation.truncated) return { text };
|
|
151
|
+
const cursorNotice = text.match(/\[[^\]]*cursor="[^"]+"[^\]]*\]$/)?.[0];
|
|
152
|
+
return {
|
|
153
|
+
text: `${truncation.content}\n\n[Output truncated: ${truncation.outputLines} of ${truncation.totalLines} lines (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).]${cursorNotice ? `\n\n${cursorNotice}` : ""}`,
|
|
154
|
+
truncation,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const HOT_FRECENCY = 25;
|
|
159
|
+
const WARM_FRECENCY = 20;
|
|
160
|
+
|
|
161
|
+
// Shared annotation helper for both find-output paths and grep-output file
|
|
162
|
+
// headers. Returns at most ONE tag so output stays scannable. Priority:
|
|
163
|
+
// git-dirty (most actionable — file is changing right now) beats frecency
|
|
164
|
+
// (historically often-touched). Keeping one function ensures the two tools
|
|
165
|
+
// never drift in how they surface git/frecency signal.
|
|
166
|
+
function fffFileAnnotation(item: {
|
|
167
|
+
gitStatus?: string;
|
|
168
|
+
totalFrecencyScore?: number;
|
|
169
|
+
accessFrecencyScore?: number;
|
|
170
|
+
}): string {
|
|
171
|
+
const git = item.gitStatus;
|
|
172
|
+
if (git && git !== "clean" && git !== "unknown" && git !== "") {
|
|
173
|
+
return ` [${git} in git]`;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const frecency = item.totalFrecencyScore ?? item.accessFrecencyScore ?? 0;
|
|
177
|
+
if (frecency >= HOT_FRECENCY) return " [VERY often touched file]";
|
|
178
|
+
if (frecency >= WARM_FRECENCY) return " [often touched file]";
|
|
179
|
+
|
|
180
|
+
return "";
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// fff-core native definition classifier (byte-level scanner in Rust) is enabled
|
|
184
|
+
// via GrepOptions.classifyDefinitions. Each GrepMatch carries isDefinition for
|
|
185
|
+
// downstream consumers; pi-fff does NOT use it to re-sort.
|
|
186
|
+
//
|
|
187
|
+
// Ordering policy: NO CUSTOM SORTING. The engine already returns items in
|
|
188
|
+
// frecency order (most-accessed files first). pi-fff only groups consecutive
|
|
189
|
+
// matches into per-file blocks and preserves whatever order the engine
|
|
190
|
+
// provided — inside a file we keep matches in source-line order because the
|
|
191
|
+
// engine emits them that way.
|
|
192
|
+
|
|
193
|
+
function formatGrepOutput(
|
|
194
|
+
result: GrepResult,
|
|
195
|
+
options?: { outputMode?: GrepOutputMode; explicitContext?: number },
|
|
196
|
+
): string {
|
|
197
|
+
if (result.items.length === 0) return "No matches found";
|
|
198
|
+
const outputMode = options?.outputMode ?? "content";
|
|
199
|
+
|
|
200
|
+
// count mode: file: count per file
|
|
201
|
+
if (outputMode === "count") {
|
|
202
|
+
const counts = new Map<string, number>();
|
|
203
|
+
const order: string[] = [];
|
|
204
|
+
for (const item of result.items) {
|
|
205
|
+
if (!counts.has(item.relativePath)) order.push(item.relativePath);
|
|
206
|
+
counts.set(item.relativePath, (counts.get(item.relativePath) ?? 0) + 1);
|
|
207
|
+
}
|
|
208
|
+
return order.map((p) => `${p}: ${counts.get(p)}`).join("\n");
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// files_with_matches mode: one preview per file, with definition auto-expand
|
|
212
|
+
if (outputMode === "files_with_matches") {
|
|
213
|
+
const seen = new Set<string>();
|
|
214
|
+
const lines: string[] = [];
|
|
215
|
+
for (const match of result.items) {
|
|
216
|
+
if (!seen.has(match.relativePath)) {
|
|
217
|
+
seen.add(match.relativePath);
|
|
218
|
+
lines.push(`${match.relativePath}${fffFileAnnotation(match)}`);
|
|
219
|
+
lines.push(` ${match.lineNumber}: ${truncateLine(match.lineContent)}`);
|
|
220
|
+
if (options?.explicitContext !== undefined) {
|
|
221
|
+
match.contextAfter
|
|
222
|
+
?.slice(0, options.explicitContext)
|
|
223
|
+
.forEach((line: string, i: number) =>
|
|
224
|
+
lines.push(` ${match.lineNumber + 1 + i}| ${truncateLine(line)}`),
|
|
225
|
+
);
|
|
226
|
+
} else appendDefContext(lines, match, "|");
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return lines.join("\n");
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// content mode (default) — with definition auto-expand
|
|
233
|
+
const hasExplicitContext = options?.explicitContext !== undefined;
|
|
234
|
+
const explicitContext = options?.explicitContext ?? 0;
|
|
235
|
+
const lines: string[] = [];
|
|
236
|
+
let currentFile = "";
|
|
237
|
+
|
|
238
|
+
for (const match of result.items) {
|
|
239
|
+
if (match.relativePath !== currentFile) {
|
|
240
|
+
if (lines.length > 0) lines.push("");
|
|
241
|
+
currentFile = match.relativePath;
|
|
242
|
+
lines.push(`${currentFile}${fffFileAnnotation(match)}`);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const before = match.contextBefore?.slice(-explicitContext) ?? [];
|
|
246
|
+
before.forEach((line: string, i: number) => {
|
|
247
|
+
const lineNum = match.lineNumber - before.length + i;
|
|
248
|
+
lines.push(` ${lineNum}- ${truncateLine(line)}`);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
lines.push(` ${match.lineNumber}: ${truncateLine(match.lineContent)}`);
|
|
252
|
+
|
|
253
|
+
if (hasExplicitContext) {
|
|
254
|
+
match.contextAfter?.slice(0, explicitContext).forEach((line: string, i: number) => {
|
|
255
|
+
const lineNum = match.lineNumber + 1 + i;
|
|
256
|
+
lines.push(` ${lineNum}- ${truncateLine(line)}`);
|
|
257
|
+
});
|
|
258
|
+
} else appendDefContext(lines, match, "-");
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return lines.join("\n");
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// Weak-match threshold is derived from the query length, matching the
|
|
265
|
+
// scoring formula in crates/fff-core/src/score.rs: a perfect match scores
|
|
266
|
+
// `len * 16`, so we treat anything below 50% of that as scattered fuzzy noise.
|
|
267
|
+
// When the top score is weak, trim output to a small sample instead of dumping
|
|
268
|
+
// the full limit worth of noise into the agent's context.
|
|
269
|
+
const FIND_WEAK_SAMPLE_SIZE = 5;
|
|
270
|
+
const DEFAULT_RESOLVE_LIMIT = 8;
|
|
271
|
+
|
|
272
|
+
function weakScoreThreshold(pattern: string): number {
|
|
273
|
+
const perfect = pattern.length * 16;
|
|
274
|
+
return Math.floor((perfect * 50) / 100);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
type GrepOutputMode = "content" | "files_with_matches" | "count";
|
|
278
|
+
|
|
279
|
+
function appendDefContext(lines: string[], match: GrepMatch, prefix: string): void {
|
|
280
|
+
if (!match.isDefinition) return;
|
|
281
|
+
const after = match.contextAfter?.slice(0, 3) ?? [];
|
|
282
|
+
for (let i = 0; i < after.length; i++) {
|
|
283
|
+
lines.push(` ${match.lineNumber + 1 + i}${prefix} ${truncateLine(after[i])}`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function scoreDominates(top?: { matchType?: string; exactMatch?: boolean; total?: number } | null, second?: { total?: number } | null): boolean {
|
|
288
|
+
if (!top) return false;
|
|
289
|
+
return top.matchType === "exact" || top.exactMatch === true || !second || (top.total ?? 0) > (second.total ?? 0) * 2;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
type GrepResultFormat = { content: { type: "text"; text: string }[]; details: { totalMatched: number; totalFiles: number } };
|
|
293
|
+
|
|
294
|
+
function formatGrepResult(
|
|
295
|
+
result: GrepResult,
|
|
296
|
+
outputMode: GrepOutputMode | undefined,
|
|
297
|
+
explicitContext: number | undefined,
|
|
298
|
+
extras?: {
|
|
299
|
+
regexFallbackError?: string;
|
|
300
|
+
fuzzyNotice?: string | null;
|
|
301
|
+
cursorState?:
|
|
302
|
+
| Omit<GrepCursorState, "cursor">
|
|
303
|
+
| Omit<MultiGrepCursorState, "cursor">;
|
|
304
|
+
},
|
|
305
|
+
): GrepResultFormat {
|
|
306
|
+
let output = formatGrepOutput(result, { outputMode, explicitContext });
|
|
307
|
+
const notices: string[] = [];
|
|
308
|
+
if (extras?.regexFallbackError) notices.push(`Invalid regex: ${extras.regexFallbackError}, used literal match`);
|
|
309
|
+
if (result.nextCursor && extras?.cursorState) {
|
|
310
|
+
notices.push(
|
|
311
|
+
`Continue with cursor="${cursorStore.store({ ...extras.cursorState, cursor: result.nextCursor } as StoredGrepCursor)}"`,
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
if (notices.length > 0) output += `\n\n[${notices.join(". ")}]`;
|
|
315
|
+
if (extras?.fuzzyNotice) output = `[${extras.fuzzyNotice}]\n${output}`;
|
|
316
|
+
return { content: [{ type: "text", text: output }], details: { totalMatched: result.totalMatched, totalFiles: result.totalFiles } };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
interface FormattedFind {
|
|
320
|
+
output: string;
|
|
321
|
+
weak: boolean;
|
|
322
|
+
shownCount: number;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function formatFindOutput(
|
|
326
|
+
result: SearchResult,
|
|
327
|
+
limit: number,
|
|
328
|
+
pattern: string,
|
|
329
|
+
pageIndex = 0,
|
|
330
|
+
): FormattedFind {
|
|
331
|
+
if (result.items.length === 0) {
|
|
332
|
+
return {
|
|
333
|
+
output: "No files found matching pattern",
|
|
334
|
+
weak: false,
|
|
335
|
+
shownCount: 0,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Peek at the top native score to decide whether results are scattered
|
|
340
|
+
// fuzzy noise (query length-scaled threshold from score.rs).
|
|
341
|
+
const topScore = result.scores[0]?.total ?? 0;
|
|
342
|
+
const weak = topScore < weakScoreThreshold(pattern);
|
|
343
|
+
const effective = weak ? Math.min(FIND_WEAK_SAMPLE_SIZE, limit) : limit;
|
|
344
|
+
const shown = result.items.slice(0, effective);
|
|
345
|
+
|
|
346
|
+
const items: string[] = [];
|
|
347
|
+
|
|
348
|
+
// On first page, add a "→ Read" hint when the top candidate strongly dominates
|
|
349
|
+
if (pageIndex === 0 && shown.length > 0 && scoreDominates(result.scores[0], result.scores[1])) {
|
|
350
|
+
const label = result.scores[0]?.matchType === "exact" || result.scores[0]?.exactMatch ? "exact match!" : "best match";
|
|
351
|
+
items.push(`→ Read ${shown[0].relativePath} (${label})`);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
items.push(...shown.map((item) => `${item.relativePath}${fffFileAnnotation(item)}`));
|
|
355
|
+
|
|
356
|
+
return {
|
|
357
|
+
output: items.join("\n"),
|
|
358
|
+
weak,
|
|
359
|
+
shownCount: shown.length,
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// ---------------------------------------------------------------------------
|
|
364
|
+
// Mention autocomplete helpers
|
|
365
|
+
// ---------------------------------------------------------------------------
|
|
366
|
+
|
|
367
|
+
function extractAtPrefix(textBeforeCursor: string): string | null {
|
|
368
|
+
const match = textBeforeCursor.match(/(?:^|[ \t])(@(?:"[^"]*|[^\s]*))$/);
|
|
369
|
+
return match?.[1] ?? null;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function buildAtCompletionValue(path: string): string {
|
|
373
|
+
return path.includes(" ") ? `@"${path}"` : `@${path}`;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function createFffMentionProvider(
|
|
377
|
+
getItems: (query: string, signal: AbortSignal) => Promise<AutocompleteItem[]>,
|
|
378
|
+
): AutocompleteProvider {
|
|
379
|
+
return {
|
|
380
|
+
async getSuggestions(lines, cursorLine, cursorCol, options) {
|
|
381
|
+
const currentLine = lines[cursorLine] || "";
|
|
382
|
+
const prefix = extractAtPrefix(currentLine.slice(0, cursorCol));
|
|
383
|
+
if (!prefix || options.signal.aborted) return null;
|
|
384
|
+
|
|
385
|
+
const query = prefix.startsWith('@"') ? prefix.slice(2) : prefix.slice(1);
|
|
386
|
+
const items = await getItems(query, options.signal);
|
|
387
|
+
return options.signal.aborted || items.length === 0 ? null : { items, prefix };
|
|
388
|
+
},
|
|
389
|
+
applyCompletion(_lines, cursorLine, cursorCol, item, prefix) {
|
|
390
|
+
const currentLine = _lines[cursorLine] || "";
|
|
391
|
+
const before = currentLine.slice(0, cursorCol - prefix.length);
|
|
392
|
+
const after = currentLine.slice(cursorCol);
|
|
393
|
+
const newLine = before + item.value + after;
|
|
394
|
+
const newCursorCol = cursorCol - prefix.length + item.value.length;
|
|
395
|
+
return {
|
|
396
|
+
lines: [..._lines.slice(0, cursorLine), newLine, ..._lines.slice(cursorLine + 1)],
|
|
397
|
+
cursorLine,
|
|
398
|
+
cursorCol: newCursorCol,
|
|
399
|
+
};
|
|
400
|
+
},
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// ---------------------------------------------------------------------------
|
|
405
|
+
// Extension
|
|
406
|
+
// ---------------------------------------------------------------------------
|
|
407
|
+
|
|
408
|
+
export default function fffExtension(pi: ExtensionAPI) {
|
|
409
|
+
let finder: FileFinder | null = null;
|
|
410
|
+
let finderCwd: string | null = null;
|
|
411
|
+
// Scoped hidden-dir finders, keyed by resolved scope — created once, reused
|
|
412
|
+
// across repeated hidden searches, destroyed on session_shutdown.
|
|
413
|
+
const scopedFinders = new Map<string, FileFinder>();
|
|
414
|
+
// Concurrent ensureFinder() callers share the same in-flight promise so
|
|
415
|
+
// FileFinder.create() (which takes native DB locks) runs at most once per
|
|
416
|
+
// base path at a time — otherwise parallel tool calls would race and
|
|
417
|
+
// deadlock at the native layer (issue #403).
|
|
418
|
+
let finderPromise: Promise<FileFinder> | null = null;
|
|
419
|
+
let activeCwd = process.cwd();
|
|
420
|
+
|
|
421
|
+
let currentMode: FffMode = "tools-and-ui";
|
|
422
|
+
let grepName = "ffgrep";
|
|
423
|
+
let findName = "fffind";
|
|
424
|
+
let frecencyDbPath: string | undefined;
|
|
425
|
+
let historyDbPath: string | undefined;
|
|
426
|
+
let enableFsRootScanning = false;
|
|
427
|
+
let toolsRegistered = false;
|
|
428
|
+
let autocompleteRegistered = false;
|
|
429
|
+
let disabledTools: Set<string> = new Set();
|
|
430
|
+
|
|
431
|
+
function resolveRuntimeConfig() {
|
|
432
|
+
// Pi populates extension flag values only after loading extension factories.
|
|
433
|
+
const configuredMode = pi.getFlag("fff-mode") ?? process.env.PI_FFF_MODE;
|
|
434
|
+
currentMode = VALID_MODES.includes(configuredMode as FffMode)
|
|
435
|
+
? (configuredMode as FffMode)
|
|
436
|
+
: "tools-and-ui";
|
|
437
|
+
grepName = currentMode === "override" ? "grep" : "ffgrep";
|
|
438
|
+
findName = currentMode === "override" ? "find" : "fffind";
|
|
439
|
+
|
|
440
|
+
frecencyDbPath =
|
|
441
|
+
(pi.getFlag("fff-frecency-db") as string | undefined) ??
|
|
442
|
+
process.env.FFF_FRECENCY_DB;
|
|
443
|
+
historyDbPath =
|
|
444
|
+
(pi.getFlag("fff-history-db") as string | undefined) ??
|
|
445
|
+
process.env.FFF_HISTORY_DB;
|
|
446
|
+
|
|
447
|
+
const rootScanFlag = pi.getFlag("fff-enable-root-scan");
|
|
448
|
+
const rootScanEnv = process.env.FFF_ENABLE_ROOT_SCAN;
|
|
449
|
+
enableFsRootScanning =
|
|
450
|
+
rootScanFlag === true ||
|
|
451
|
+
rootScanFlag === "true" ||
|
|
452
|
+
rootScanFlag === "1" ||
|
|
453
|
+
(rootScanFlag == null && (rootScanEnv === "1" || rootScanEnv === "true"));
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function ensureFinder(cwd: string): Promise<FileFinder> {
|
|
457
|
+
if (finderPromise) return finderPromise;
|
|
458
|
+
if (finder && !finder.isDestroyed && finderCwd === cwd)
|
|
459
|
+
return Promise.resolve(finder);
|
|
460
|
+
|
|
461
|
+
finderPromise = (async () => {
|
|
462
|
+
if (finder && !finder.isDestroyed) {
|
|
463
|
+
finder.destroy();
|
|
464
|
+
finder = null;
|
|
465
|
+
finderCwd = null;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const result = FileFinder.create({
|
|
469
|
+
basePath: cwd,
|
|
470
|
+
frecencyDbPath,
|
|
471
|
+
historyDbPath,
|
|
472
|
+
aiMode: true,
|
|
473
|
+
enableHomeDirScanning: true,
|
|
474
|
+
enableFsRootScanning,
|
|
475
|
+
});
|
|
476
|
+
|
|
477
|
+
if (!result.ok)
|
|
478
|
+
throw new Error(`Failed to create FFF file finder: ${result.error}`);
|
|
479
|
+
|
|
480
|
+
finder = result.value;
|
|
481
|
+
finderCwd = cwd;
|
|
482
|
+
await finder.waitForScan(15000);
|
|
483
|
+
return finder;
|
|
484
|
+
})().finally(() => {
|
|
485
|
+
finderPromise = null;
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
return finderPromise;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function resolveExplicitHiddenScope(pathConstraint: string | undefined) {
|
|
492
|
+
if (!pathConstraint) return null;
|
|
493
|
+
const normalized = normalizePathConstraint(pathConstraint, activeCwd);
|
|
494
|
+
if (!normalized) return null;
|
|
495
|
+
|
|
496
|
+
const segments = normalized.replace(/\/$/, "").split("/");
|
|
497
|
+
const globIndex = segments.findIndex((segment) => /[*?[{]/.test(segment));
|
|
498
|
+
const scopeSegments = globIndex < 0 ? segments : segments.slice(0, globIndex);
|
|
499
|
+
const scope = scopeSegments.join("/");
|
|
500
|
+
if (!scope || !scopeSegments.some((segment) => segment.startsWith("."))) return null;
|
|
501
|
+
|
|
502
|
+
const absoluteScope = path.resolve(activeCwd, scope);
|
|
503
|
+
try {
|
|
504
|
+
return {
|
|
505
|
+
scope: scope.replaceAll(path.sep, "/"),
|
|
506
|
+
absoluteScope,
|
|
507
|
+
constraint: globIndex < 0 ? undefined : segments.slice(globIndex).join("/"),
|
|
508
|
+
stat: statSync(absoluteScope),
|
|
509
|
+
};
|
|
510
|
+
} catch {
|
|
511
|
+
return null;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function rebaseScopedExcludes(
|
|
516
|
+
exclude: string | string[] | undefined,
|
|
517
|
+
scope: string,
|
|
518
|
+
): { excludeAll: boolean; values?: string[] } {
|
|
519
|
+
const prefix = `${scope.replace(/\/$/, "")}/`;
|
|
520
|
+
const values: string[] = [];
|
|
521
|
+
for (const negated of normalizeExcludes(exclude, activeCwd)) {
|
|
522
|
+
const constraint = negated.slice(1);
|
|
523
|
+
if (constraint === prefix || constraint === scope) return { excludeAll: true };
|
|
524
|
+
if (constraint.startsWith(prefix)) {
|
|
525
|
+
values.push(constraint.slice(prefix.length));
|
|
526
|
+
} else if (!constraint.replace(/\/$/, "").includes("/") || constraint.startsWith("**/")) {
|
|
527
|
+
values.push(constraint);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
return { excludeAll: false, values: values.length > 0 ? values : undefined };
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
async function withExplicitHiddenFinder<T>(
|
|
534
|
+
pathConstraint: string | undefined,
|
|
535
|
+
run: (finder: FileFinder, scope: string, cwd: string, constraint?: string) => T,
|
|
536
|
+
): Promise<{ scope: string; value: T } | null> {
|
|
537
|
+
const resolved = resolveExplicitHiddenScope(pathConstraint);
|
|
538
|
+
if (!resolved?.stat.isDirectory()) return null;
|
|
539
|
+
|
|
540
|
+
let scopedFinder = scopedFinders.get(resolved.scope);
|
|
541
|
+
if (!scopedFinder || scopedFinder.isDestroyed) {
|
|
542
|
+
const created = FileFinder.create({
|
|
543
|
+
basePath: resolved.absoluteScope,
|
|
544
|
+
// ponytail: scoped fallback is ephemeral; sharing workspace DBs risks native lock contention.
|
|
545
|
+
aiMode: true,
|
|
546
|
+
enableHomeDirScanning: true,
|
|
547
|
+
enableFsRootScanning,
|
|
548
|
+
});
|
|
549
|
+
if (!created.ok) return null;
|
|
550
|
+
|
|
551
|
+
scopedFinder = created.value;
|
|
552
|
+
// Register BEFORE waitForScan: a rejection must leave the finder in the
|
|
553
|
+
// map so session_shutdown can destroy it (and so it's reusable), not
|
|
554
|
+
// abandoned un-destroyed.
|
|
555
|
+
scopedFinders.set(resolved.scope, scopedFinder);
|
|
556
|
+
await scopedFinder.waitForScan(15000);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
return {
|
|
560
|
+
scope: resolved.scope,
|
|
561
|
+
value: run(scopedFinder, resolved.scope, resolved.absoluteScope, resolved.constraint),
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function matchesExplicitFile(
|
|
566
|
+
relativePath: string,
|
|
567
|
+
pattern: string,
|
|
568
|
+
exclude: string | string[] | undefined,
|
|
569
|
+
): boolean {
|
|
570
|
+
const candidate = relativePath.replaceAll(path.sep, "/");
|
|
571
|
+
const basename = path.posix.basename(candidate);
|
|
572
|
+
const matchesConstraint = (constraint: string) => {
|
|
573
|
+
if (constraint.endsWith("/")) return candidate.startsWith(constraint);
|
|
574
|
+
if (/[*?[{]/.test(constraint)) {
|
|
575
|
+
try {
|
|
576
|
+
return path.matchesGlob(candidate, constraint) || path.matchesGlob(basename, constraint);
|
|
577
|
+
} catch {
|
|
578
|
+
return false;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return candidate === constraint || basename === constraint;
|
|
582
|
+
};
|
|
583
|
+
if (normalizeExcludes(exclude, activeCwd).some((value) => matchesConstraint(value.slice(1)))) {
|
|
584
|
+
return false;
|
|
585
|
+
}
|
|
586
|
+
if (!pattern || pattern === "*") return true;
|
|
587
|
+
if (/[*?[{]/.test(pattern)) return matchesConstraint(pattern);
|
|
588
|
+
|
|
589
|
+
const target = candidate.toLowerCase();
|
|
590
|
+
return pattern.toLowerCase().split(/\s+/).filter(Boolean).every((term) => {
|
|
591
|
+
let index = 0;
|
|
592
|
+
for (const char of target) if (char === term[index]) index++;
|
|
593
|
+
return index === term.length;
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function emptyGrepResult(totalFiles = 0): GrepResult {
|
|
598
|
+
return {
|
|
599
|
+
items: [],
|
|
600
|
+
totalMatched: 0,
|
|
601
|
+
totalFilesSearched: 0,
|
|
602
|
+
totalFiles,
|
|
603
|
+
filteredFileCount: 0,
|
|
604
|
+
nextCursor: null,
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function prefixGrepResult(result: GrepResult, scope: string): GrepResult {
|
|
609
|
+
return {
|
|
610
|
+
...result,
|
|
611
|
+
items: result.items.map((item) => ({
|
|
612
|
+
...item,
|
|
613
|
+
relativePath: `${scope}/${item.relativePath}`,
|
|
614
|
+
})),
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
function grepExplicitHiddenFile(
|
|
619
|
+
pathConstraint: string | undefined,
|
|
620
|
+
patterns: string[],
|
|
621
|
+
options: {
|
|
622
|
+
mode: GrepMode;
|
|
623
|
+
smartCase: boolean;
|
|
624
|
+
context: number;
|
|
625
|
+
pageSize: number;
|
|
626
|
+
exclude?: string | string[];
|
|
627
|
+
glob?: string;
|
|
628
|
+
offset?: number;
|
|
629
|
+
},
|
|
630
|
+
): GrepResult | null {
|
|
631
|
+
const resolved = resolveExplicitHiddenScope(pathConstraint);
|
|
632
|
+
if (!resolved?.stat.isFile()) return null;
|
|
633
|
+
if (!matchesExplicitFile(resolved.scope, options.glob ?? "*", options.exclude)) {
|
|
634
|
+
return emptyGrepResult(1);
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
const smartInsensitive = options.smartCase && patterns.every((pattern) => pattern === pattern.toLowerCase());
|
|
638
|
+
const matchers = patterns.map((pattern) => {
|
|
639
|
+
if (options.mode === "regex") {
|
|
640
|
+
const insensitive = pattern.match(/^\(\?i:(.*)\)$/s);
|
|
641
|
+
try {
|
|
642
|
+
const regex = new RegExp(insensitive?.[1] ?? pattern, insensitive || smartInsensitive ? "i" : "");
|
|
643
|
+
return (line: string) => regex.test(line);
|
|
644
|
+
} catch {
|
|
645
|
+
const literal = insensitive?.[1] ?? pattern;
|
|
646
|
+
const needle = smartInsensitive ? literal.toLowerCase() : literal;
|
|
647
|
+
return (line: string) => (smartInsensitive ? line.toLowerCase() : line).includes(needle);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
const needle = smartInsensitive ? pattern.toLowerCase() : pattern;
|
|
651
|
+
return (line: string) => {
|
|
652
|
+
const candidate = smartInsensitive ? line.toLowerCase() : line;
|
|
653
|
+
if (options.mode === "plain") return candidate.includes(needle);
|
|
654
|
+
let index = 0;
|
|
655
|
+
for (const char of candidate) if (char === needle[index]) index++;
|
|
656
|
+
return index === needle.length;
|
|
657
|
+
};
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
const offset = options.offset ?? 0;
|
|
661
|
+
const items: GrepMatch[] = [];
|
|
662
|
+
const before: string[] = [];
|
|
663
|
+
const pending: Array<{ item: GrepMatch; remaining: number }> = [];
|
|
664
|
+
let matched = 0;
|
|
665
|
+
let hasMore = false;
|
|
666
|
+
let lineNumber = 1;
|
|
667
|
+
let stopMatching = false;
|
|
668
|
+
|
|
669
|
+
const processLine = (rawLine: string) => {
|
|
670
|
+
const line = rawLine.replace(/\r$/, "");
|
|
671
|
+
for (const entry of pending) {
|
|
672
|
+
entry.item.contextAfter!.push(line);
|
|
673
|
+
entry.remaining--;
|
|
674
|
+
}
|
|
675
|
+
while (pending[0]?.remaining === 0) pending.shift();
|
|
676
|
+
|
|
677
|
+
if (!stopMatching && matchers.some((matcher) => matcher(line))) {
|
|
678
|
+
if (matched >= offset) {
|
|
679
|
+
if (items.length >= options.pageSize) {
|
|
680
|
+
hasMore = true;
|
|
681
|
+
stopMatching = true;
|
|
682
|
+
} else {
|
|
683
|
+
const item = {
|
|
684
|
+
relativePath: resolved.scope,
|
|
685
|
+
fileName: path.posix.basename(resolved.scope),
|
|
686
|
+
lineNumber,
|
|
687
|
+
lineContent: line,
|
|
688
|
+
contextBefore: [...before],
|
|
689
|
+
contextAfter: [],
|
|
690
|
+
} as unknown as GrepMatch;
|
|
691
|
+
items.push(item);
|
|
692
|
+
if (options.context > 0) pending.push({ item, remaining: options.context });
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
matched++;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
if (options.context > 0) {
|
|
699
|
+
before.push(line);
|
|
700
|
+
if (before.length > options.context) before.shift();
|
|
701
|
+
}
|
|
702
|
+
lineNumber++;
|
|
703
|
+
return stopMatching && pending.length === 0;
|
|
704
|
+
};
|
|
705
|
+
|
|
706
|
+
const fd = openSync(resolved.absoluteScope, "r");
|
|
707
|
+
try {
|
|
708
|
+
if (fstatSync(fd).size > GREP_MAX_FILE_SIZE) return emptyGrepResult(1);
|
|
709
|
+
const buffer = Buffer.allocUnsafe(64 * 1024);
|
|
710
|
+
const decoder = new StringDecoder("utf8");
|
|
711
|
+
let remainder = "";
|
|
712
|
+
let bytesReadTotal = 0;
|
|
713
|
+
let done = false;
|
|
714
|
+
while (!done) {
|
|
715
|
+
const bytesRead = readSync(fd, buffer, 0, buffer.length, null);
|
|
716
|
+
if (bytesRead === 0) break;
|
|
717
|
+
bytesReadTotal += bytesRead;
|
|
718
|
+
if (bytesReadTotal > GREP_MAX_FILE_SIZE || buffer.subarray(0, bytesRead).includes(0)) {
|
|
719
|
+
return emptyGrepResult(1);
|
|
720
|
+
}
|
|
721
|
+
const chunk = remainder + decoder.write(buffer.subarray(0, bytesRead));
|
|
722
|
+
let start = 0;
|
|
723
|
+
for (;;) {
|
|
724
|
+
const newline = chunk.indexOf("\n", start);
|
|
725
|
+
if (newline < 0) {
|
|
726
|
+
remainder = chunk.slice(start);
|
|
727
|
+
break;
|
|
728
|
+
}
|
|
729
|
+
if (processLine(chunk.slice(start, newline))) {
|
|
730
|
+
done = true;
|
|
731
|
+
break;
|
|
732
|
+
}
|
|
733
|
+
start = newline + 1;
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
if (!done) processLine(remainder + decoder.end());
|
|
737
|
+
} finally {
|
|
738
|
+
closeSync(fd);
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
const nextOffset = offset + items.length;
|
|
742
|
+
return {
|
|
743
|
+
items,
|
|
744
|
+
totalMatched: items.length,
|
|
745
|
+
totalFilesSearched: 1,
|
|
746
|
+
totalFiles: 1,
|
|
747
|
+
filteredFileCount: 1,
|
|
748
|
+
nextCursor: hasMore
|
|
749
|
+
? { __brand: "GrepCursor", _offset: nextOffset } as GrepCursor
|
|
750
|
+
: null,
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
async function searchExplicitHiddenScope(
|
|
755
|
+
pathConstraint: string | undefined,
|
|
756
|
+
pattern: string,
|
|
757
|
+
exclude: string | string[] | undefined,
|
|
758
|
+
pageIndex: number,
|
|
759
|
+
pageSize: number,
|
|
760
|
+
): Promise<SearchResult | null> {
|
|
761
|
+
const resolved = resolveExplicitHiddenScope(pathConstraint);
|
|
762
|
+
if (!resolved) return null;
|
|
763
|
+
|
|
764
|
+
if (resolved.stat.isFile()) {
|
|
765
|
+
if (pageIndex > 0 || !matchesExplicitFile(resolved.scope, pattern, exclude)) return null;
|
|
766
|
+
return {
|
|
767
|
+
items: [{ relativePath: resolved.scope, fileName: path.basename(resolved.scope) } as SearchResult["items"][number]],
|
|
768
|
+
scores: [{ total: Number.MAX_SAFE_INTEGER, matchType: "exact", exactMatch: true } as SearchResult["scores"][number]],
|
|
769
|
+
totalMatched: 1,
|
|
770
|
+
totalFiles: 1,
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
const rebased = rebaseScopedExcludes(exclude, resolved.scope);
|
|
775
|
+
if (rebased.excludeAll) {
|
|
776
|
+
return { items: [], scores: [], totalMatched: 0, totalFiles: 0 };
|
|
777
|
+
}
|
|
778
|
+
const searched = await withExplicitHiddenFinder(pathConstraint, (scopedFinder, scope, cwd, constraint) => {
|
|
779
|
+
const scopedQuery = buildQuery(constraint, pattern, rebased.values, cwd);
|
|
780
|
+
const result = scopedFinder.fileSearch(scopedQuery, { pageIndex, pageSize });
|
|
781
|
+
if (!result.ok) return null;
|
|
782
|
+
return {
|
|
783
|
+
...result.value,
|
|
784
|
+
items: result.value.items.map((item) => ({
|
|
785
|
+
...item,
|
|
786
|
+
relativePath: `${scope}/${item.relativePath}`,
|
|
787
|
+
})),
|
|
788
|
+
};
|
|
789
|
+
});
|
|
790
|
+
return searched?.value ?? null;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
async function searchOverrideFind(
|
|
794
|
+
finder: FileFinder,
|
|
795
|
+
pattern: string,
|
|
796
|
+
searchPath: string | undefined,
|
|
797
|
+
limit: number,
|
|
798
|
+
) {
|
|
799
|
+
const pathScope = searchPath ? normalizePathConstraint(searchPath, activeCwd) : null;
|
|
800
|
+
const hidden = resolveExplicitHiddenScope(searchPath ?? pattern);
|
|
801
|
+
let result: SearchResult;
|
|
802
|
+
|
|
803
|
+
if (hidden?.stat.isFile()) {
|
|
804
|
+
const matched = matchesExplicitFile(hidden.scope, searchPath ? pattern : hidden.scope, undefined);
|
|
805
|
+
result = matched
|
|
806
|
+
? {
|
|
807
|
+
items: [{ relativePath: searchPath ? path.posix.basename(hidden.scope) : hidden.scope, fileName: path.posix.basename(hidden.scope) } as SearchResult["items"][number]],
|
|
808
|
+
scores: [{ total: Number.MAX_SAFE_INTEGER, matchType: "exact", exactMatch: true } as SearchResult["scores"][number]],
|
|
809
|
+
totalMatched: 1,
|
|
810
|
+
totalFiles: 1,
|
|
811
|
+
}
|
|
812
|
+
: { items: [], scores: [], totalMatched: 0, totalFiles: 0 };
|
|
813
|
+
} else if (hidden?.stat.isDirectory()) {
|
|
814
|
+
const localPattern = searchPath ? pattern : hidden.constraint ?? "*";
|
|
815
|
+
const scoped = await withExplicitHiddenFinder(hidden.scope, (target) =>
|
|
816
|
+
target.glob(localPattern, { pageSize: limit }),
|
|
817
|
+
);
|
|
818
|
+
if (!scoped?.value.ok) {
|
|
819
|
+
return { content: [{ type: "text" as const, text: "No files found matching pattern" }], details: undefined };
|
|
820
|
+
}
|
|
821
|
+
result = {
|
|
822
|
+
...scoped.value.value,
|
|
823
|
+
items: scoped.value.value.items.map((item) => ({
|
|
824
|
+
...item,
|
|
825
|
+
relativePath: searchPath ? item.relativePath : `${hidden.scope}/${item.relativePath}`,
|
|
826
|
+
})),
|
|
827
|
+
};
|
|
828
|
+
} else {
|
|
829
|
+
const scope = pathScope?.replace(/\/$/, "");
|
|
830
|
+
const scopedPattern = scope ? `${scope}/${pattern}` : pattern;
|
|
831
|
+
const searched = finder.glob(scopedPattern, { pageSize: limit });
|
|
832
|
+
if (!searched.ok) {
|
|
833
|
+
return { content: [{ type: "text" as const, text: `Search failed: ${searched.error}` }], details: undefined };
|
|
834
|
+
}
|
|
835
|
+
result = {
|
|
836
|
+
...searched.value,
|
|
837
|
+
items: searched.value.items.map((item) => ({
|
|
838
|
+
...item,
|
|
839
|
+
relativePath: scope && item.relativePath.startsWith(`${scope}/`)
|
|
840
|
+
? item.relativePath.slice(scope.length + 1)
|
|
841
|
+
: item.relativePath,
|
|
842
|
+
})),
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
const output = result.items.map((item) => item.relativePath).join("\n") || "No files found matching pattern";
|
|
847
|
+
return {
|
|
848
|
+
content: [{ type: "text" as const, text: output }],
|
|
849
|
+
details: result.totalMatched > result.items.length
|
|
850
|
+
? { resultLimitReached: limit }
|
|
851
|
+
: undefined,
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
function destroyFinder() {
|
|
856
|
+
if (finder && !finder.isDestroyed) {
|
|
857
|
+
finder.destroy();
|
|
858
|
+
finder = null;
|
|
859
|
+
finderCwd = null;
|
|
860
|
+
}
|
|
861
|
+
for (const scopedFinder of scopedFinders.values()) {
|
|
862
|
+
if (!scopedFinder.isDestroyed) scopedFinder.destroy();
|
|
863
|
+
}
|
|
864
|
+
scopedFinders.clear();
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
async function getMentionItems(
|
|
868
|
+
query: string,
|
|
869
|
+
signal: AbortSignal,
|
|
870
|
+
): Promise<AutocompleteItem[]> {
|
|
871
|
+
if (signal.aborted) return [];
|
|
872
|
+
const f = await ensureFinder(activeCwd);
|
|
873
|
+
if (signal.aborted) return [];
|
|
874
|
+
|
|
875
|
+
const result = f.mixedSearch(query, { pageSize: 20 });
|
|
876
|
+
if (!result.ok) return [];
|
|
877
|
+
|
|
878
|
+
return result.value.items.slice(0, 20).map((mixed: MixedItem) => {
|
|
879
|
+
if (mixed.type === "directory") {
|
|
880
|
+
return {
|
|
881
|
+
value: buildAtCompletionValue(mixed.item.relativePath),
|
|
882
|
+
label: mixed.item.dirName,
|
|
883
|
+
description: mixed.item.relativePath,
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
return {
|
|
887
|
+
value: buildAtCompletionValue(mixed.item.relativePath),
|
|
888
|
+
label: mixed.item.fileName,
|
|
889
|
+
description: mixed.item.relativePath,
|
|
890
|
+
};
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
function registerAutocompleteProvider(ctx: {
|
|
895
|
+
ui: {
|
|
896
|
+
addAutocompleteProvider: (
|
|
897
|
+
factory: (current: AutocompleteProvider) => AutocompleteProvider,
|
|
898
|
+
) => void;
|
|
899
|
+
};
|
|
900
|
+
}) {
|
|
901
|
+
if (autocompleteRegistered) return;
|
|
902
|
+
autocompleteRegistered = true;
|
|
903
|
+
ctx.ui.addAutocompleteProvider((current) => {
|
|
904
|
+
const mentionProvider = createFffMentionProvider(getMentionItems);
|
|
905
|
+
|
|
906
|
+
return {
|
|
907
|
+
async getSuggestions(lines, cursorLine, cursorCol, options) {
|
|
908
|
+
if (currentMode !== "tools-only") {
|
|
909
|
+
try {
|
|
910
|
+
const mentionResult = await mentionProvider.getSuggestions(
|
|
911
|
+
lines,
|
|
912
|
+
cursorLine,
|
|
913
|
+
cursorCol,
|
|
914
|
+
options,
|
|
915
|
+
);
|
|
916
|
+
if (mentionResult) return mentionResult;
|
|
917
|
+
} catch {
|
|
918
|
+
// Delegate when FFF lookup is unavailable.
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
return current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
923
|
+
},
|
|
924
|
+
applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
|
|
925
|
+
return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
|
|
926
|
+
},
|
|
927
|
+
shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
|
|
928
|
+
return (
|
|
929
|
+
current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true
|
|
930
|
+
);
|
|
931
|
+
},
|
|
932
|
+
};
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
// --- Flags / lifecycle ---
|
|
937
|
+
|
|
938
|
+
pi.registerFlag("fff-mode", {
|
|
939
|
+
description: "FFF mode: tools-and-ui | tools-only | override",
|
|
940
|
+
type: "string",
|
|
941
|
+
});
|
|
942
|
+
|
|
943
|
+
pi.registerFlag("fff-frecency-db", {
|
|
944
|
+
description: "Path to the frecency database (overrides FFF_FRECENCY_DB env)",
|
|
945
|
+
type: "string",
|
|
946
|
+
});
|
|
947
|
+
|
|
948
|
+
pi.registerFlag("fff-history-db", {
|
|
949
|
+
description: "Path to the query history database (overrides FFF_HISTORY_DB env)",
|
|
950
|
+
type: "string",
|
|
951
|
+
});
|
|
952
|
+
|
|
953
|
+
pi.registerFlag("fff-enable-root-scan", {
|
|
954
|
+
description:
|
|
955
|
+
"Allow indexing when launched from the filesystem root (also: FFF_ENABLE_ROOT_SCAN env)",
|
|
956
|
+
type: "boolean",
|
|
957
|
+
});
|
|
958
|
+
|
|
959
|
+
pi.on("before_agent_start", async (event) => {
|
|
960
|
+
// Skip in override mode: the tools already carry builtin grep/find names there.
|
|
961
|
+
if (currentMode === "override") return;
|
|
962
|
+
// Skip when the fff tools aren't active for this turn (user disabled via
|
|
963
|
+
// /tools) or init failed — don't advertise tools that can't run.
|
|
964
|
+
const active = pi.getActiveTools();
|
|
965
|
+
if (!active.includes("ffgrep") && !active.includes("fffind")) return;
|
|
966
|
+
return {
|
|
967
|
+
systemPrompt:
|
|
968
|
+
event.systemPrompt +
|
|
969
|
+
"\n\nSearch tools: ffgrep/fffind (FFF engine) are the preferred content/file search — " +
|
|
970
|
+
"frecency-ranked, paginated, lower token cost than `bash grep`/`find`. " +
|
|
971
|
+
"Use plain grep/find only for pipelines (sort/uniq/wc) or paths outside the workspace.",
|
|
972
|
+
};
|
|
973
|
+
});
|
|
974
|
+
|
|
975
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
976
|
+
try {
|
|
977
|
+
activeCwd = ctx.cwd;
|
|
978
|
+
resolveRuntimeConfig();
|
|
979
|
+
registerTools();
|
|
980
|
+
if (currentMode === "override") {
|
|
981
|
+
const available = new Set(pi.getAllTools().map((tool) => tool.name));
|
|
982
|
+
const active = pi.getActiveTools();
|
|
983
|
+
const overrides = ["find", "grep"].filter(
|
|
984
|
+
(name) => available.has(name) && !active.includes(name),
|
|
985
|
+
);
|
|
986
|
+
if (overrides.length > 0) pi.setActiveTools([...active, ...overrides]);
|
|
987
|
+
}
|
|
988
|
+
registerAutocompleteProvider(ctx);
|
|
989
|
+
await ensureFinder(activeCwd);
|
|
990
|
+
} catch (e: unknown) {
|
|
991
|
+
ctx.ui.notify(
|
|
992
|
+
`FFF init failed: ${e instanceof Error ? e.message : String(e)}`,
|
|
993
|
+
"error",
|
|
994
|
+
);
|
|
995
|
+
}
|
|
996
|
+
});
|
|
997
|
+
|
|
998
|
+
pi.on("session_shutdown", async () => {
|
|
999
|
+
destroyFinder();
|
|
1000
|
+
});
|
|
1001
|
+
|
|
1002
|
+
function registerTools() {
|
|
1003
|
+
if (toolsRegistered) return;
|
|
1004
|
+
toolsRegistered = true;
|
|
1005
|
+
disabledTools = readDisabledTools();
|
|
1006
|
+
|
|
1007
|
+
// --- Shared render helpers ---
|
|
1008
|
+
|
|
1009
|
+
const renderTextResult = (
|
|
1010
|
+
result: { content?: { type: string; text?: string }[] },
|
|
1011
|
+
options: { expanded?: boolean },
|
|
1012
|
+
theme: any,
|
|
1013
|
+
context: any,
|
|
1014
|
+
maxLines = 15,
|
|
1015
|
+
) => {
|
|
1016
|
+
const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
|
|
1017
|
+
const output = result.content?.find((c) => c.type === "text")?.text?.trim() ?? "";
|
|
1018
|
+
if (!output) {
|
|
1019
|
+
text.setText(theme.fg("muted", "No output"));
|
|
1020
|
+
return text;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
const lines = output.split("\n");
|
|
1024
|
+
const displayLines = lines.slice(0, options.expanded ? lines.length : maxLines);
|
|
1025
|
+
let content = `\n${displayLines.map((line: string) => theme.fg("toolOutput", line)).join("\n")}`;
|
|
1026
|
+
if (lines.length > displayLines.length) {
|
|
1027
|
+
content += theme.fg(
|
|
1028
|
+
"muted",
|
|
1029
|
+
`\n... (${lines.length - displayLines.length} more lines)`,
|
|
1030
|
+
);
|
|
1031
|
+
}
|
|
1032
|
+
text.setText(content);
|
|
1033
|
+
return text;
|
|
1034
|
+
};
|
|
1035
|
+
|
|
1036
|
+
const registerBoundedTool = (tool: any) => {
|
|
1037
|
+
const execute = tool.execute;
|
|
1038
|
+
// Per-tool kill-switch (ceulen.disabledTools): rows use canonical names
|
|
1039
|
+
// (ffgrep/fffind); override mode registers grep/find, so map before the
|
|
1040
|
+
// defaultActive check. /config re-activates disabled tools live.
|
|
1041
|
+
const canonical = tool.name === "grep" ? "ffgrep" : tool.name === "find" ? "fffind" : tool.name;
|
|
1042
|
+
pi.registerTool({
|
|
1043
|
+
...tool,
|
|
1044
|
+
defaultActive: !disabledTools.has(canonical),
|
|
1045
|
+
async execute(...args: any[]) {
|
|
1046
|
+
const result = await execute(...args);
|
|
1047
|
+
let truncation: TruncationResult | undefined;
|
|
1048
|
+
const content = result.content?.map((item: any) => {
|
|
1049
|
+
if (item.type !== "text") return item;
|
|
1050
|
+
const bounded = boundedText(item.text);
|
|
1051
|
+
truncation ??= bounded.truncation;
|
|
1052
|
+
return { ...item, text: bounded.text };
|
|
1053
|
+
});
|
|
1054
|
+
return {
|
|
1055
|
+
...result,
|
|
1056
|
+
content,
|
|
1057
|
+
details: truncation
|
|
1058
|
+
? { ...(result.details ?? {}), truncation }
|
|
1059
|
+
: result.details,
|
|
1060
|
+
};
|
|
1061
|
+
},
|
|
1062
|
+
});
|
|
1063
|
+
};
|
|
1064
|
+
|
|
1065
|
+
// --- grep tool ---
|
|
1066
|
+
|
|
1067
|
+
const grepSchema = currentMode === "override"
|
|
1068
|
+
? Type.Object({
|
|
1069
|
+
pattern: Type.String({ description: "Search pattern (regex or literal string)" }),
|
|
1070
|
+
path: Type.Optional(Type.String({ description: "Directory or file to search (default: current directory)" })),
|
|
1071
|
+
glob: Type.Optional(Type.String({ description: "Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'" })),
|
|
1072
|
+
ignoreCase: Type.Optional(Type.Boolean({ description: "Case-insensitive search (default: false)" })),
|
|
1073
|
+
literal: Type.Optional(Type.Boolean({ description: "Treat pattern as literal string instead of regex (default: false)" })),
|
|
1074
|
+
context: Type.Optional(Type.Number({ description: "Number of lines to show before and after each match (default: 0)" })),
|
|
1075
|
+
limit: Type.Optional(Type.Number({ description: "Maximum number of matches to return (default: 100)" })),
|
|
1076
|
+
})
|
|
1077
|
+
: Type.Object({
|
|
1078
|
+
pattern: Type.String({ description: "Literal text or regex" }),
|
|
1079
|
+
path: Type.Optional(Type.String({ description: "Dir prefix (src/), filename (main.rs), or glob (*.ts, src/**/*.cc)." })),
|
|
1080
|
+
exclude: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())], { description: "Exclude paths — dir prefix, filename, or glob." })),
|
|
1081
|
+
caseSensitive: Type.Optional(Type.Boolean({ description: "Force case-sensitive (smart-case by default)." })),
|
|
1082
|
+
context: Type.Optional(Type.Integer({ minimum: 0, description: "Context lines before+after" })),
|
|
1083
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, description: `Max matches (default ${DEFAULT_GREP_LIMIT})` })),
|
|
1084
|
+
outputMode: Type.Optional(Type.String({ description: "'content' (default), 'files_with_matches', or 'count'" })),
|
|
1085
|
+
cursor: Type.Optional(Type.String({ description: "Pagination cursor" })),
|
|
1086
|
+
});
|
|
1087
|
+
|
|
1088
|
+
registerBoundedTool({
|
|
1089
|
+
name: grepName,
|
|
1090
|
+
label: grepName,
|
|
1091
|
+
description: `Grep contents. Smart-case, regex auto-detect, git-aware, frecency-ranked.`,
|
|
1092
|
+
promptSnippet: "Grep contents (FFF: paginated, frecency-ranked — prefer over bash grep)",
|
|
1093
|
+
promptGuidelines: [
|
|
1094
|
+
"Preferred content search: paginated with cursor, lower token cost than bash grep.",
|
|
1095
|
+
"Bare identifiers preferred. Literal queries most efficient.",
|
|
1096
|
+
"Use path/include, exclude/noise.",
|
|
1097
|
+
"caseSensitive=true for exact case (smart-case by default).",
|
|
1098
|
+
"After 1-2 greps, read top match.",
|
|
1099
|
+
],
|
|
1100
|
+
parameters: grepSchema,
|
|
1101
|
+
|
|
1102
|
+
async execute(_toolCallId: any, params: any, signal: AbortSignal | undefined) {
|
|
1103
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
1104
|
+
|
|
1105
|
+
const override = currentMode === "override";
|
|
1106
|
+
const stored = !override && params.cursor ? cursorStore.get(params.cursor) : undefined;
|
|
1107
|
+
if (params.cursor && (!stored || stored.tool !== "grep" || stored.cwd !== activeCwd)) {
|
|
1108
|
+
return {
|
|
1109
|
+
content: [{ type: "text", text: "Invalid or expired grep cursor. Start the search again without cursor." }],
|
|
1110
|
+
details: override ? undefined : { totalMatched: 0, totalFiles: 0 },
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
let f;
|
|
1115
|
+
try {
|
|
1116
|
+
f = await ensureFinder(activeCwd);
|
|
1117
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
1118
|
+
} catch {
|
|
1119
|
+
return {
|
|
1120
|
+
content: [{ type: "text", text: "FFF search unavailable in this directory. Try a different working directory or use built-in find instead." }],
|
|
1121
|
+
details: currentMode === "override" ? undefined : { totalMatched: 0, totalFiles: 0 },
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
const resumed = stored?.tool === "grep" ? stored : undefined;
|
|
1126
|
+
const pageSize = resumed?.pageSize ?? Math.max(1, Math.floor(params.limit ?? (override ? 100 : DEFAULT_GREP_LIMIT)));
|
|
1127
|
+
const explicitContext = resumed?.context ?? (params.context === undefined
|
|
1128
|
+
? undefined
|
|
1129
|
+
: Math.max(0, Math.floor(params.context)));
|
|
1130
|
+
const contextLines = explicitContext ?? 0;
|
|
1131
|
+
const outputMode = resumed?.outputMode ?? (params.outputMode as GrepOutputMode | undefined) ?? "content";
|
|
1132
|
+
|
|
1133
|
+
let query = resumed?.query;
|
|
1134
|
+
let mode = resumed?.mode;
|
|
1135
|
+
let smartCase = resumed?.smartCase;
|
|
1136
|
+
let scope = resumed?.scope;
|
|
1137
|
+
let manualFile = resumed?.hiddenFile ?? false;
|
|
1138
|
+
let searchPattern = params.pattern;
|
|
1139
|
+
let hasRegexSyntax = false;
|
|
1140
|
+
try {
|
|
1141
|
+
if (!query || !mode || smartCase === undefined) {
|
|
1142
|
+
if (override) {
|
|
1143
|
+
mode = params.literal ? "plain" : "regex";
|
|
1144
|
+
if (params.ignoreCase) {
|
|
1145
|
+
searchPattern = mode === "plain" ? searchPattern.toLowerCase() : `(?i:${searchPattern})`;
|
|
1146
|
+
smartCase = true;
|
|
1147
|
+
} else smartCase = false;
|
|
1148
|
+
const withGlob = params.glob
|
|
1149
|
+
? buildQuery(params.glob, searchPattern, undefined, activeCwd)
|
|
1150
|
+
: searchPattern;
|
|
1151
|
+
query = buildQuery(params.path, withGlob, undefined, activeCwd);
|
|
1152
|
+
} else {
|
|
1153
|
+
query = buildQuery(params.path, searchPattern, params.exclude, activeCwd);
|
|
1154
|
+
hasRegexSyntax =
|
|
1155
|
+
searchPattern !== searchPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1156
|
+
mode = hasRegexSyntax ? "regex" : "plain";
|
|
1157
|
+
if (mode === "regex") {
|
|
1158
|
+
try {
|
|
1159
|
+
new RegExp(searchPattern);
|
|
1160
|
+
} catch {
|
|
1161
|
+
mode = "plain";
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
smartCase = params.caseSensitive !== true;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
} catch (e) {
|
|
1168
|
+
return {
|
|
1169
|
+
content: [{ type: "text", text: `Invalid path constraint: ${(e as Error).message}. Try without path/exclude constraints.` }],
|
|
1170
|
+
details: override ? undefined : { totalMatched: 0, totalFiles: 0 },
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
if (!query || !mode || smartCase === undefined) {
|
|
1175
|
+
return {
|
|
1176
|
+
content: [{ type: "text", text: "Search failed: invalid grep state" }],
|
|
1177
|
+
details: currentMode === "override" ? undefined : { totalMatched: 0, totalFiles: 0 },
|
|
1178
|
+
};
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
let scopeExcluded = false;
|
|
1182
|
+
if (!resumed) {
|
|
1183
|
+
const hidden = resolveExplicitHiddenScope(params.path);
|
|
1184
|
+
if (hidden?.stat.isFile()) {
|
|
1185
|
+
scope = hidden.scope;
|
|
1186
|
+
query = searchPattern;
|
|
1187
|
+
manualFile = true;
|
|
1188
|
+
} else if (hidden?.stat.isDirectory()) {
|
|
1189
|
+
scope = hidden.scope;
|
|
1190
|
+
const rebased = rebaseScopedExcludes(params.exclude, hidden.scope);
|
|
1191
|
+
scopeExcluded = rebased.excludeAll;
|
|
1192
|
+
query = override
|
|
1193
|
+
? buildQuery(hidden.constraint, buildQuery(params.glob, searchPattern, undefined, hidden.absoluteScope), undefined, hidden.absoluteScope)
|
|
1194
|
+
: buildQuery(hidden.constraint, searchPattern, rebased.values, hidden.absoluteScope);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
const p = params.pattern.trim();
|
|
1199
|
+
const isWildcardOnly =
|
|
1200
|
+
!override &&
|
|
1201
|
+
hasRegexSyntax &&
|
|
1202
|
+
/^(?:[.^$]*(?:[.][*+?]|\*|\+)[.^$]*|[.^$\s]*|\.\*\??|\.\*[+?]?|\.\+\??|\.|\*|\?)$/.test(p);
|
|
1203
|
+
if (isWildcardOnly) {
|
|
1204
|
+
return {
|
|
1205
|
+
content: [{ type: "text", text: `Pattern '${params.pattern}' matches everything — grep needs a concrete substring or identifier.` }],
|
|
1206
|
+
details: { totalMatched: 0, totalFiles: 0 },
|
|
1207
|
+
};
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
const runGrep = (
|
|
1211
|
+
target: FileFinder,
|
|
1212
|
+
targetQuery: string,
|
|
1213
|
+
targetMode: GrepMode,
|
|
1214
|
+
cursor: GrepCursor | null,
|
|
1215
|
+
) => target.grep(targetQuery, {
|
|
1216
|
+
mode: targetMode,
|
|
1217
|
+
smartCase,
|
|
1218
|
+
pageSize,
|
|
1219
|
+
maxMatchesPerFile: Math.min(pageSize, 50),
|
|
1220
|
+
cursor,
|
|
1221
|
+
beforeContext: contextLines,
|
|
1222
|
+
afterContext: Math.max(contextLines, explicitContext === undefined ? 3 : contextLines),
|
|
1223
|
+
classifyDefinitions: true,
|
|
1224
|
+
});
|
|
1225
|
+
|
|
1226
|
+
let grepResult;
|
|
1227
|
+
try {
|
|
1228
|
+
if (scopeExcluded) {
|
|
1229
|
+
grepResult = { ok: true as const, value: emptyGrepResult() };
|
|
1230
|
+
} else if (manualFile && scope) {
|
|
1231
|
+
const manual = grepExplicitHiddenFile(scope, [query!], {
|
|
1232
|
+
mode,
|
|
1233
|
+
smartCase,
|
|
1234
|
+
context: contextLines,
|
|
1235
|
+
pageSize,
|
|
1236
|
+
offset: resumed?.cursor._offset,
|
|
1237
|
+
exclude: resumed?.exclude,
|
|
1238
|
+
glob: resumed?.glob,
|
|
1239
|
+
});
|
|
1240
|
+
grepResult = manual ? { ok: true as const, value: manual } : undefined;
|
|
1241
|
+
} else if (scope) {
|
|
1242
|
+
const scoped = await withExplicitHiddenFinder(scope, (target) =>
|
|
1243
|
+
runGrep(target, query!, mode!, resumed?.cursor ?? null),
|
|
1244
|
+
);
|
|
1245
|
+
grepResult = scoped?.value;
|
|
1246
|
+
if (grepResult?.ok) grepResult = { ok: true, value: prefixGrepResult(grepResult.value, scope) };
|
|
1247
|
+
} else {
|
|
1248
|
+
grepResult = runGrep(f, query!, mode!, resumed?.cursor ?? null);
|
|
1249
|
+
}
|
|
1250
|
+
} catch (e) {
|
|
1251
|
+
return {
|
|
1252
|
+
content: [{ type: "text", text: `Search error: ${(e as Error).message}` }],
|
|
1253
|
+
details: override ? undefined : { totalMatched: 0, totalFiles: 0 },
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
if (!grepResult) {
|
|
1257
|
+
return {
|
|
1258
|
+
content: [{ type: "text", text: "Search failed: hidden path scope is unavailable" }],
|
|
1259
|
+
details: override ? undefined : { totalMatched: 0, totalFiles: 0 },
|
|
1260
|
+
};
|
|
1261
|
+
}
|
|
1262
|
+
if (!grepResult.ok) {
|
|
1263
|
+
return {
|
|
1264
|
+
content: [{ type: "text", text: `Search failed: ${grepResult.error}` }],
|
|
1265
|
+
details: override ? undefined : { totalMatched: 0, totalFiles: 0 },
|
|
1266
|
+
};
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
let result = grepResult.value;
|
|
1270
|
+
let fuzzyNotice: string | null = null;
|
|
1271
|
+
if (!override && !resumed && !scopeExcluded && result.items.length === 0 && mode !== "regex") {
|
|
1272
|
+
try {
|
|
1273
|
+
let fuzzy;
|
|
1274
|
+
if (manualFile && scope) {
|
|
1275
|
+
const manual = grepExplicitHiddenFile(scope, [query!], {
|
|
1276
|
+
mode: "fuzzy",
|
|
1277
|
+
smartCase,
|
|
1278
|
+
context: contextLines,
|
|
1279
|
+
pageSize,
|
|
1280
|
+
exclude: params.exclude,
|
|
1281
|
+
glob: params.glob,
|
|
1282
|
+
});
|
|
1283
|
+
fuzzy = manual ? { ok: true as const, value: manual } : undefined;
|
|
1284
|
+
} else if (scope) {
|
|
1285
|
+
const scoped = await withExplicitHiddenFinder(scope, (target) =>
|
|
1286
|
+
runGrep(target, query!, "fuzzy", null),
|
|
1287
|
+
);
|
|
1288
|
+
fuzzy = scoped?.value;
|
|
1289
|
+
if (fuzzy?.ok) fuzzy = { ok: true as const, value: prefixGrepResult(fuzzy.value, scope) };
|
|
1290
|
+
} else {
|
|
1291
|
+
fuzzy = runGrep(f, query!, "fuzzy", null);
|
|
1292
|
+
}
|
|
1293
|
+
if (fuzzy?.ok && fuzzy.value.items.length > 0) {
|
|
1294
|
+
mode = "fuzzy";
|
|
1295
|
+
fuzzyNotice = "0 exact matches. Maybe you meant this?";
|
|
1296
|
+
result = fuzzy.value;
|
|
1297
|
+
}
|
|
1298
|
+
} catch {
|
|
1299
|
+
// Keep the exact-search result when fuzzy fallback is unavailable.
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
const formatted = formatGrepResult(result, outputMode, explicitContext, {
|
|
1304
|
+
regexFallbackError: result.regexFallbackError,
|
|
1305
|
+
fuzzyNotice,
|
|
1306
|
+
cursorState: override
|
|
1307
|
+
? undefined
|
|
1308
|
+
: {
|
|
1309
|
+
tool: "grep",
|
|
1310
|
+
cwd: activeCwd,
|
|
1311
|
+
query: query!,
|
|
1312
|
+
scope,
|
|
1313
|
+
hiddenFile: manualFile,
|
|
1314
|
+
exclude: resumed?.exclude ?? params.exclude,
|
|
1315
|
+
glob: resumed?.glob ?? params.glob,
|
|
1316
|
+
mode: mode!,
|
|
1317
|
+
smartCase,
|
|
1318
|
+
context: explicitContext,
|
|
1319
|
+
outputMode,
|
|
1320
|
+
pageSize,
|
|
1321
|
+
},
|
|
1322
|
+
});
|
|
1323
|
+
if (!override) return formatted;
|
|
1324
|
+
|
|
1325
|
+
const details: { matchLimitReached?: number; linesTruncated?: boolean } = {};
|
|
1326
|
+
if (result.nextCursor) details.matchLimitReached = pageSize;
|
|
1327
|
+
if (result.items.some((item) =>
|
|
1328
|
+
[item.lineContent, ...(item.contextBefore ?? []), ...(item.contextAfter ?? [])]
|
|
1329
|
+
.some((line) => line.trimEnd().length > GREP_MAX_LINE_LENGTH))) {
|
|
1330
|
+
details.linesTruncated = true;
|
|
1331
|
+
}
|
|
1332
|
+
return {
|
|
1333
|
+
content: formatted.content,
|
|
1334
|
+
details: Object.keys(details).length > 0 ? details : undefined,
|
|
1335
|
+
};
|
|
1336
|
+
},
|
|
1337
|
+
|
|
1338
|
+
renderCall(args: any, theme: any, context: any) {
|
|
1339
|
+
const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
|
|
1340
|
+
const pattern = args?.pattern ?? "";
|
|
1341
|
+
const path = args?.path ?? ".";
|
|
1342
|
+
let content =
|
|
1343
|
+
theme.fg("toolTitle", theme.bold(grepName)) +
|
|
1344
|
+
" " +
|
|
1345
|
+
theme.fg("accent", `/${pattern}/`) +
|
|
1346
|
+
theme.fg("toolOutput", ` in ${path}`);
|
|
1347
|
+
if (args?.limit !== undefined)
|
|
1348
|
+
content += theme.fg("toolOutput", ` limit ${args.limit}`);
|
|
1349
|
+
if (args?.cursor) content += theme.fg("muted", ` (page)`);
|
|
1350
|
+
text.setText(content);
|
|
1351
|
+
return text;
|
|
1352
|
+
},
|
|
1353
|
+
|
|
1354
|
+
renderResult(result: any, options: any, theme: any, context: any) {
|
|
1355
|
+
return renderTextResult(result, options, theme, context, 15);
|
|
1356
|
+
},
|
|
1357
|
+
});
|
|
1358
|
+
|
|
1359
|
+
// --- find tool ---
|
|
1360
|
+
|
|
1361
|
+
const findSchema = currentMode === "override"
|
|
1362
|
+
? Type.Object({
|
|
1363
|
+
pattern: Type.String({ description: "Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'" }),
|
|
1364
|
+
path: Type.Optional(Type.String({ description: "Directory to search in (default: current directory)" })),
|
|
1365
|
+
limit: Type.Optional(Type.Number({ description: "Maximum number of results (default: 1000)" })),
|
|
1366
|
+
})
|
|
1367
|
+
: Type.Object({
|
|
1368
|
+
pattern: Type.String({ description: "Fuzzy filename/glob search. Frecency-ranked, git-aware. Multi-word narrows (AND)." }),
|
|
1369
|
+
path: Type.Optional(Type.String({ description: "Dir prefix (src/), filename (main.rs), or glob (*.ts, src/**/*.cc)." })),
|
|
1370
|
+
exclude: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())], { description: "Exclude paths — dir prefix, filename, or glob." })),
|
|
1371
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, description: `Max results per page (default ${DEFAULT_FIND_LIMIT})` })),
|
|
1372
|
+
cursor: Type.Optional(Type.String({ description: "Pagination cursor" })),
|
|
1373
|
+
});
|
|
1374
|
+
|
|
1375
|
+
registerBoundedTool({
|
|
1376
|
+
name: findName,
|
|
1377
|
+
label: findName,
|
|
1378
|
+
description: `Fuzzy path/glob search. Whole-path matching, frecency-ranked, git-aware.`,
|
|
1379
|
+
promptSnippet: "Find files by path or glob (FFF: frecency-ranked — prefer over bash find)",
|
|
1380
|
+
promptGuidelines: [
|
|
1381
|
+
"Preferred file search: frecency-ranked whole-path matching, lower token cost than bash find.",
|
|
1382
|
+
"Whole-path matching: 'profile' hits 'chrome/browser/profiles/x.cc' too.",
|
|
1383
|
+
"1-2 terms best; extra words narrow.",
|
|
1384
|
+
"Use for paths, use grep for content.",
|
|
1385
|
+
"Exact match: glob in `path` like '**/profile.h'. Bare patterns are fuzzy.",
|
|
1386
|
+
"List dir: path: 'dir/**' with empty/wildcard pattern.",
|
|
1387
|
+
"exclude: 'test/,*.min.js' to cut noise.",
|
|
1388
|
+
],
|
|
1389
|
+
parameters: findSchema,
|
|
1390
|
+
|
|
1391
|
+
async execute(_toolCallId: any, params: any, signal: AbortSignal | undefined) {
|
|
1392
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
1393
|
+
|
|
1394
|
+
const override = currentMode === "override";
|
|
1395
|
+
const resumed = !override && params.cursor ? findCursorStore.get(params.cursor) : undefined;
|
|
1396
|
+
if (params.cursor && (!resumed || resumed.cwd !== activeCwd)) {
|
|
1397
|
+
return {
|
|
1398
|
+
content: [{ type: "text", text: "Invalid or expired find cursor. Start the search again without cursor." }],
|
|
1399
|
+
details: override ? undefined : { totalMatched: 0, totalFiles: 0, pageIndex: 0, hasMore: false },
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
let f;
|
|
1404
|
+
try {
|
|
1405
|
+
f = await ensureFinder(activeCwd);
|
|
1406
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
1407
|
+
} catch {
|
|
1408
|
+
return {
|
|
1409
|
+
content: [{ type: "text", text: "FFF search unavailable in this directory. Try a different working directory." }],
|
|
1410
|
+
details: override ? undefined : { totalMatched: 0, totalFiles: 0, pageIndex: 0, hasMore: false },
|
|
1411
|
+
};
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
if (override) {
|
|
1415
|
+
try {
|
|
1416
|
+
return await searchOverrideFind(
|
|
1417
|
+
f,
|
|
1418
|
+
params.pattern,
|
|
1419
|
+
params.path,
|
|
1420
|
+
Math.max(1, Math.floor(params.limit ?? 1000)),
|
|
1421
|
+
);
|
|
1422
|
+
} catch (e) {
|
|
1423
|
+
return {
|
|
1424
|
+
content: [{ type: "text", text: `Invalid path constraint: ${(e as Error).message}. Try without path/exclude constraints.` }],
|
|
1425
|
+
};
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
// Resume from a prior cursor if supplied — cursor owns query+pageSize so
|
|
1430
|
+
// the agent can't accidentally mix patterns across pages.
|
|
1431
|
+
const effectiveLimit = resumed
|
|
1432
|
+
? resumed.pageSize
|
|
1433
|
+
: Math.max(1, Math.floor(params.limit ?? DEFAULT_FIND_LIMIT));
|
|
1434
|
+
let query;
|
|
1435
|
+
try {
|
|
1436
|
+
query = resumed
|
|
1437
|
+
? resumed.query
|
|
1438
|
+
: buildQuery(params.path, params.pattern, params.exclude, activeCwd);
|
|
1439
|
+
} catch (e) {
|
|
1440
|
+
return {
|
|
1441
|
+
content: [{ type: "text", text: `Invalid path constraint: ${(e as Error).message}. Try without path/exclude constraints.` }],
|
|
1442
|
+
details: { totalMatched: 0, totalFiles: 0, pageIndex: 0, hasMore: false },
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
const pattern = resumed ? resumed.pattern : params.pattern;
|
|
1446
|
+
const pageIndex = resumed?.nextPageIndex ?? 0;
|
|
1447
|
+
const scope = resumed?.scope ?? params.path;
|
|
1448
|
+
|
|
1449
|
+
let searchResult;
|
|
1450
|
+
try {
|
|
1451
|
+
if (resolveExplicitHiddenScope(scope)) {
|
|
1452
|
+
searchResult = {
|
|
1453
|
+
ok: true as const,
|
|
1454
|
+
value: (await searchExplicitHiddenScope(
|
|
1455
|
+
scope,
|
|
1456
|
+
pattern,
|
|
1457
|
+
resumed?.exclude ?? params.exclude,
|
|
1458
|
+
pageIndex,
|
|
1459
|
+
effectiveLimit,
|
|
1460
|
+
)) ?? { items: [], scores: [], totalMatched: 0, totalFiles: 0 },
|
|
1461
|
+
};
|
|
1462
|
+
} else {
|
|
1463
|
+
searchResult = f.fileSearch(query, {
|
|
1464
|
+
pageIndex,
|
|
1465
|
+
pageSize: effectiveLimit,
|
|
1466
|
+
});
|
|
1467
|
+
}
|
|
1468
|
+
} catch (e) {
|
|
1469
|
+
return {
|
|
1470
|
+
content: [{ type: "text", text: `Search error: ${(e as Error).message}` }],
|
|
1471
|
+
details: { totalMatched: 0, totalFiles: 0, pageIndex: 0, hasMore: false },
|
|
1472
|
+
};
|
|
1473
|
+
}
|
|
1474
|
+
if (!searchResult.ok) {
|
|
1475
|
+
return {
|
|
1476
|
+
content: [{ type: "text", text: `Search failed: ${searchResult.error}` }],
|
|
1477
|
+
details: { totalMatched: 0, totalFiles: 0, pageIndex: 0, hasMore: false },
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
const result = searchResult.value;
|
|
1482
|
+
const formatted = formatFindOutput(result, effectiveLimit, pattern, pageIndex);
|
|
1483
|
+
let output = formatted.output;
|
|
1484
|
+
|
|
1485
|
+
// Infer hasMore: native fileSearch fills pageSize when more results
|
|
1486
|
+
// exist, so if we got a full page AND totalMatched exceeds what we've
|
|
1487
|
+
// shown so far there's another page to fetch.
|
|
1488
|
+
const shownSoFar = pageIndex * effectiveLimit + result.items.length;
|
|
1489
|
+
const hasMore =
|
|
1490
|
+
result.items.length >= effectiveLimit && result.totalMatched > shownSoFar;
|
|
1491
|
+
|
|
1492
|
+
const notices: string[] = [];
|
|
1493
|
+
if (formatted.weak && formatted.shownCount > 0)
|
|
1494
|
+
notices.push(
|
|
1495
|
+
`Query "${pattern}" produced only weak scattered fuzzy matches. Output capped at ${formatted.shownCount}/${result.totalMatched}.`,
|
|
1496
|
+
);
|
|
1497
|
+
|
|
1498
|
+
if (!formatted.weak && hasMore) {
|
|
1499
|
+
const remaining = result.totalMatched - shownSoFar;
|
|
1500
|
+
const cursorId = findCursorStore.store({
|
|
1501
|
+
cwd: activeCwd,
|
|
1502
|
+
query,
|
|
1503
|
+
pattern,
|
|
1504
|
+
pageSize: effectiveLimit,
|
|
1505
|
+
nextPageIndex: pageIndex + 1,
|
|
1506
|
+
scope,
|
|
1507
|
+
exclude: resumed?.exclude ?? params.exclude,
|
|
1508
|
+
});
|
|
1509
|
+
notices.push(
|
|
1510
|
+
`${remaining} more match${remaining === 1 ? "" : "es"} available. cursor="${cursorId}" to continue`,
|
|
1511
|
+
);
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
if (notices.length > 0) output += `\n\n[${notices.join(". ")}]`;
|
|
1515
|
+
return {
|
|
1516
|
+
content: [{ type: "text", text: output }],
|
|
1517
|
+
details: {
|
|
1518
|
+
totalMatched: result.totalMatched,
|
|
1519
|
+
totalFiles: result.totalFiles,
|
|
1520
|
+
pageIndex,
|
|
1521
|
+
hasMore,
|
|
1522
|
+
},
|
|
1523
|
+
};
|
|
1524
|
+
},
|
|
1525
|
+
|
|
1526
|
+
renderCall(args: any, theme: any, context: any) {
|
|
1527
|
+
const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
|
|
1528
|
+
const pattern = args?.pattern ?? "";
|
|
1529
|
+
const path = args?.path ?? ".";
|
|
1530
|
+
let content =
|
|
1531
|
+
theme.fg("toolTitle", theme.bold(findName)) +
|
|
1532
|
+
" " +
|
|
1533
|
+
theme.fg("accent", pattern) +
|
|
1534
|
+
theme.fg("toolOutput", ` in ${path}`);
|
|
1535
|
+
if (args?.limit !== undefined)
|
|
1536
|
+
content += theme.fg("toolOutput", ` (limit ${args.limit})`);
|
|
1537
|
+
if (args?.cursor) content += theme.fg("muted", ` (page)`);
|
|
1538
|
+
text.setText(content);
|
|
1539
|
+
return text;
|
|
1540
|
+
},
|
|
1541
|
+
|
|
1542
|
+
renderResult(result: any, options: any, theme: any, context: any) {
|
|
1543
|
+
return renderTextResult(result, options, theme, context, 20);
|
|
1544
|
+
},
|
|
1545
|
+
});
|
|
1546
|
+
|
|
1547
|
+
// --- resolve_file tool ---
|
|
1548
|
+
|
|
1549
|
+
const resolveFileSchema = Type.Object({
|
|
1550
|
+
pattern: Type.String({
|
|
1551
|
+
description:
|
|
1552
|
+
"Fuzzy file path query. Turn vague reference ('auth middleware') into exact path.",
|
|
1553
|
+
}),
|
|
1554
|
+
limit: Type.Optional(
|
|
1555
|
+
Type.Integer({
|
|
1556
|
+
minimum: 1,
|
|
1557
|
+
description: `Max candidates when ambiguous (default ${DEFAULT_RESOLVE_LIMIT})`,
|
|
1558
|
+
}),
|
|
1559
|
+
),
|
|
1560
|
+
});
|
|
1561
|
+
|
|
1562
|
+
registerBoundedTool({
|
|
1563
|
+
name: "resolve_file",
|
|
1564
|
+
label: "Resolve File",
|
|
1565
|
+
description:
|
|
1566
|
+
"Resolve fuzzy file ref to exact path. Auto-resolves when one candidate dominates.",
|
|
1567
|
+
promptSnippet: "Resolve a fuzzy file reference",
|
|
1568
|
+
promptGuidelines: [
|
|
1569
|
+
"Use for vague refs like 'auth middleware' instead of exact path.",
|
|
1570
|
+
"Returns resolved path or ranked candidates.",
|
|
1571
|
+
"2-3 word queries produce best results.",
|
|
1572
|
+
],
|
|
1573
|
+
parameters: resolveFileSchema,
|
|
1574
|
+
|
|
1575
|
+
async execute(_toolCallId: any, params: any, signal: AbortSignal | undefined) {
|
|
1576
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
1577
|
+
|
|
1578
|
+
let f;
|
|
1579
|
+
try {
|
|
1580
|
+
f = await ensureFinder(activeCwd);
|
|
1581
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
1582
|
+
} catch {
|
|
1583
|
+
return {
|
|
1584
|
+
content: [{ type: "text", text: "FFF search unavailable in this directory." }],
|
|
1585
|
+
details: { resolved: false, totalMatched: 0 },
|
|
1586
|
+
};
|
|
1587
|
+
}
|
|
1588
|
+
const limit = params.limit ?? DEFAULT_RESOLVE_LIMIT;
|
|
1589
|
+
const pattern = stripLeadingAt(params.pattern);
|
|
1590
|
+
|
|
1591
|
+
let result;
|
|
1592
|
+
try {
|
|
1593
|
+
result = f.fileSearch(pattern, { pageSize: Math.max(limit, 2) });
|
|
1594
|
+
} catch (e) {
|
|
1595
|
+
return {
|
|
1596
|
+
content: [{ type: "text", text: `Search error: ${(e as Error).message}` }],
|
|
1597
|
+
details: { resolved: false, totalMatched: 0 },
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
if (!result.ok) {
|
|
1601
|
+
return {
|
|
1602
|
+
content: [{ type: "text", text: `Search failed: ${result.error}` }],
|
|
1603
|
+
details: { resolved: false, totalMatched: 0 },
|
|
1604
|
+
};
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
if (result.value.items.length === 0) {
|
|
1608
|
+
return {
|
|
1609
|
+
content: [{ type: "text", text: `No files matched "${pattern}".` }],
|
|
1610
|
+
details: { resolved: false, totalMatched: 0 },
|
|
1611
|
+
};
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
const topResult = result.value.items[0];
|
|
1615
|
+
const topScore = result.value.scores[0];
|
|
1616
|
+
const secondScore = result.value.scores[1];
|
|
1617
|
+
|
|
1618
|
+
// Auto-resolve when top candidate dominates or is an exact match
|
|
1619
|
+
if (scoreDominates(topScore, secondScore)) {
|
|
1620
|
+
return {
|
|
1621
|
+
content: [
|
|
1622
|
+
{
|
|
1623
|
+
type: "text",
|
|
1624
|
+
text: `→ Read ${topResult.relativePath}${fffFileAnnotation(topResult)}`,
|
|
1625
|
+
},
|
|
1626
|
+
],
|
|
1627
|
+
details: {
|
|
1628
|
+
resolved: true,
|
|
1629
|
+
totalMatched: result.value.totalMatched,
|
|
1630
|
+
},
|
|
1631
|
+
};
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
// Ambiguous — return ranked candidates
|
|
1635
|
+
const candidates = result.value.items
|
|
1636
|
+
.slice(0, limit)
|
|
1637
|
+
.map(
|
|
1638
|
+
(item, i) =>
|
|
1639
|
+
`${i + 1}. ${item.relativePath}${fffFileAnnotation(item)}`,
|
|
1640
|
+
)
|
|
1641
|
+
.join("\n");
|
|
1642
|
+
|
|
1643
|
+
return {
|
|
1644
|
+
content: [
|
|
1645
|
+
{
|
|
1646
|
+
type: "text",
|
|
1647
|
+
text: `Ambiguous reference. Top candidates:\n${candidates}`,
|
|
1648
|
+
},
|
|
1649
|
+
],
|
|
1650
|
+
details: {
|
|
1651
|
+
resolved: false,
|
|
1652
|
+
totalMatched: result.value.totalMatched,
|
|
1653
|
+
},
|
|
1654
|
+
};
|
|
1655
|
+
},
|
|
1656
|
+
});
|
|
1657
|
+
|
|
1658
|
+
// --- fff_multi_grep tool ---
|
|
1659
|
+
|
|
1660
|
+
const multiGrepSchema = Type.Object({
|
|
1661
|
+
patterns: Type.Array(Type.String({ description: "Literal pattern" }), {
|
|
1662
|
+
minItems: 1,
|
|
1663
|
+
maxItems: 10,
|
|
1664
|
+
description: "Literal patterns, one pass. For renames, aliases, or spelling variants.",
|
|
1665
|
+
}),
|
|
1666
|
+
path: Type.Optional(
|
|
1667
|
+
Type.String({
|
|
1668
|
+
description:
|
|
1669
|
+
"Dir prefix (src/), filename (main.rs), or glob (*.ts, src/**/*.cc).",
|
|
1670
|
+
}),
|
|
1671
|
+
),
|
|
1672
|
+
exclude: Type.Optional(
|
|
1673
|
+
Type.Union([Type.String(), Type.Array(Type.String())], {
|
|
1674
|
+
description:
|
|
1675
|
+
"Exclude paths — dir prefix, filename, or glob.",
|
|
1676
|
+
}),
|
|
1677
|
+
),
|
|
1678
|
+
context: Type.Optional(
|
|
1679
|
+
Type.Integer({ minimum: 0, description: "Context lines before+after" }),
|
|
1680
|
+
),
|
|
1681
|
+
limit: Type.Optional(
|
|
1682
|
+
Type.Integer({
|
|
1683
|
+
minimum: 1,
|
|
1684
|
+
description: `Max matches (default ${DEFAULT_GREP_LIMIT})`,
|
|
1685
|
+
}),
|
|
1686
|
+
),
|
|
1687
|
+
outputMode: Type.Optional(
|
|
1688
|
+
Type.String({
|
|
1689
|
+
description: "'content' (default), 'files_with_matches', or 'count'",
|
|
1690
|
+
}),
|
|
1691
|
+
),
|
|
1692
|
+
cursor: Type.Optional(
|
|
1693
|
+
Type.String({ description: "Pagination cursor" }),
|
|
1694
|
+
),
|
|
1695
|
+
caseSensitive: Type.Optional(
|
|
1696
|
+
Type.Boolean({
|
|
1697
|
+
description:
|
|
1698
|
+
"caseSensitive=true for exact case (smart-case by default).",
|
|
1699
|
+
}),
|
|
1700
|
+
),
|
|
1701
|
+
});
|
|
1702
|
+
|
|
1703
|
+
registerBoundedTool({
|
|
1704
|
+
name: "fff_multi_grep",
|
|
1705
|
+
label: "FFF Multi Grep",
|
|
1706
|
+
description:
|
|
1707
|
+
"Search for any of multiple literal patterns in one pass. For renamed symbols, aliases, or spelling variants.",
|
|
1708
|
+
promptSnippet: "Grep for multiple patterns",
|
|
1709
|
+
promptGuidelines: [
|
|
1710
|
+
"2-10 literal patterns, one indexed pass.",
|
|
1711
|
+
"Use for renames, migrations, or multiple related terms.",
|
|
1712
|
+
"Use path/exclude to scope, outputMode for conciseness.",
|
|
1713
|
+
],
|
|
1714
|
+
parameters: multiGrepSchema,
|
|
1715
|
+
|
|
1716
|
+
async execute(_toolCallId: any, params: any, signal: AbortSignal | undefined) {
|
|
1717
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
1718
|
+
|
|
1719
|
+
const stored = params.cursor ? cursorStore.get(params.cursor) : undefined;
|
|
1720
|
+
if (params.cursor && (!stored || stored.tool !== "multi" || stored.cwd !== activeCwd)) {
|
|
1721
|
+
return {
|
|
1722
|
+
content: [{ type: "text", text: "Invalid or expired multi-grep cursor. Start the search again without cursor." }],
|
|
1723
|
+
details: { totalMatched: 0, totalFiles: 0 },
|
|
1724
|
+
};
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
let f;
|
|
1728
|
+
try {
|
|
1729
|
+
f = await ensureFinder(activeCwd);
|
|
1730
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
1731
|
+
} catch {
|
|
1732
|
+
return {
|
|
1733
|
+
content: [{ type: "text", text: "FFF search unavailable in this directory." }],
|
|
1734
|
+
details: { totalMatched: 0, totalFiles: 0 },
|
|
1735
|
+
};
|
|
1736
|
+
}
|
|
1737
|
+
const resumed = stored?.tool === "multi" ? stored : undefined;
|
|
1738
|
+
const pageSize = resumed?.pageSize ?? Math.max(1, Math.floor(params.limit ?? DEFAULT_GREP_LIMIT));
|
|
1739
|
+
const patterns = resumed?.patterns ?? params.patterns;
|
|
1740
|
+
const explicitContext = resumed?.context ?? (params.context === undefined
|
|
1741
|
+
? undefined
|
|
1742
|
+
: Math.max(0, Math.floor(params.context)));
|
|
1743
|
+
const contextLines = explicitContext ?? 0;
|
|
1744
|
+
const smartCase = resumed?.smartCase ?? params.caseSensitive !== true;
|
|
1745
|
+
const outputMode = resumed?.outputMode ?? (params.outputMode as GrepOutputMode | undefined) ?? "content";
|
|
1746
|
+
let scope = resumed?.scope;
|
|
1747
|
+
let manualFile = resumed?.hiddenFile ?? false;
|
|
1748
|
+
let constraints = resumed?.constraints;
|
|
1749
|
+
let scopeExcluded = false;
|
|
1750
|
+
try {
|
|
1751
|
+
if (!resumed) {
|
|
1752
|
+
constraints = buildQuery(params.path, "", params.exclude, activeCwd) || undefined;
|
|
1753
|
+
const hidden = resolveExplicitHiddenScope(params.path);
|
|
1754
|
+
if (hidden?.stat.isFile()) {
|
|
1755
|
+
scope = hidden.scope;
|
|
1756
|
+
manualFile = true;
|
|
1757
|
+
} else if (hidden?.stat.isDirectory()) {
|
|
1758
|
+
scope = hidden.scope;
|
|
1759
|
+
const rebased = rebaseScopedExcludes(params.exclude, hidden.scope);
|
|
1760
|
+
scopeExcluded = rebased.excludeAll;
|
|
1761
|
+
constraints = buildQuery(hidden.constraint, "", rebased.values, hidden.absoluteScope) || undefined;
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
} catch (e) {
|
|
1765
|
+
return {
|
|
1766
|
+
content: [{ type: "text", text: `Invalid path constraint: ${(e as Error).message}.` }],
|
|
1767
|
+
details: { totalMatched: 0, totalFiles: 0 },
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
const runMultiGrep = (
|
|
1772
|
+
target: FileFinder,
|
|
1773
|
+
targetConstraints: string | undefined,
|
|
1774
|
+
cursor: GrepCursor | null,
|
|
1775
|
+
) => target.multiGrep({
|
|
1776
|
+
patterns,
|
|
1777
|
+
constraints: targetConstraints,
|
|
1778
|
+
cursor,
|
|
1779
|
+
beforeContext: contextLines,
|
|
1780
|
+
afterContext: Math.max(contextLines, explicitContext === undefined ? 3 : contextLines),
|
|
1781
|
+
pageSize,
|
|
1782
|
+
maxMatchesPerFile: Math.min(pageSize, 50),
|
|
1783
|
+
smartCase,
|
|
1784
|
+
classifyDefinitions: true,
|
|
1785
|
+
});
|
|
1786
|
+
|
|
1787
|
+
let grepResult;
|
|
1788
|
+
try {
|
|
1789
|
+
if (scopeExcluded) {
|
|
1790
|
+
grepResult = { ok: true as const, value: emptyGrepResult() };
|
|
1791
|
+
} else if (manualFile && scope) {
|
|
1792
|
+
const manual = grepExplicitHiddenFile(scope, patterns, {
|
|
1793
|
+
mode: "plain",
|
|
1794
|
+
smartCase,
|
|
1795
|
+
context: contextLines,
|
|
1796
|
+
pageSize,
|
|
1797
|
+
offset: resumed?.cursor._offset,
|
|
1798
|
+
exclude: resumed?.exclude,
|
|
1799
|
+
});
|
|
1800
|
+
grepResult = manual ? { ok: true as const, value: manual } : undefined;
|
|
1801
|
+
} else if (scope) {
|
|
1802
|
+
const scoped = await withExplicitHiddenFinder(scope, (target) =>
|
|
1803
|
+
runMultiGrep(target, constraints, resumed?.cursor ?? null),
|
|
1804
|
+
);
|
|
1805
|
+
grepResult = scoped?.value;
|
|
1806
|
+
if (grepResult?.ok) grepResult = { ok: true, value: prefixGrepResult(grepResult.value, scope) };
|
|
1807
|
+
} else {
|
|
1808
|
+
grepResult = runMultiGrep(f, constraints, resumed?.cursor ?? null);
|
|
1809
|
+
}
|
|
1810
|
+
} catch (e) {
|
|
1811
|
+
return {
|
|
1812
|
+
content: [{ type: "text", text: `Search error: ${(e as Error).message}` }],
|
|
1813
|
+
details: { totalMatched: 0, totalFiles: 0 },
|
|
1814
|
+
};
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
if (!grepResult) {
|
|
1818
|
+
return {
|
|
1819
|
+
content: [{ type: "text", text: "Search failed: hidden path scope is unavailable" }],
|
|
1820
|
+
details: { totalMatched: 0, totalFiles: 0 },
|
|
1821
|
+
};
|
|
1822
|
+
}
|
|
1823
|
+
if (!grepResult.ok) {
|
|
1824
|
+
return {
|
|
1825
|
+
content: [{ type: "text", text: `Search failed: ${grepResult.error}` }],
|
|
1826
|
+
details: { totalMatched: 0, totalFiles: 0 },
|
|
1827
|
+
};
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1830
|
+
const result = grepResult.value;
|
|
1831
|
+
return formatGrepResult(result, outputMode, explicitContext, {
|
|
1832
|
+
cursorState: {
|
|
1833
|
+
tool: "multi",
|
|
1834
|
+
cwd: activeCwd,
|
|
1835
|
+
patterns,
|
|
1836
|
+
scope,
|
|
1837
|
+
hiddenFile: manualFile,
|
|
1838
|
+
exclude: resumed?.exclude ?? params.exclude,
|
|
1839
|
+
constraints,
|
|
1840
|
+
smartCase,
|
|
1841
|
+
context: explicitContext,
|
|
1842
|
+
outputMode,
|
|
1843
|
+
pageSize,
|
|
1844
|
+
},
|
|
1845
|
+
});
|
|
1846
|
+
},
|
|
1847
|
+
});
|
|
1848
|
+
|
|
1849
|
+
// --- related_files tool ---
|
|
1850
|
+
|
|
1851
|
+
const relatedFilesSchema = Type.Object({
|
|
1852
|
+
path: Type.String({
|
|
1853
|
+
description:
|
|
1854
|
+
"File path (relative or fuzzy) to find companion files for (tests, types, styles, stories).",
|
|
1855
|
+
}),
|
|
1856
|
+
limit: Type.Optional(
|
|
1857
|
+
Type.Integer({
|
|
1858
|
+
minimum: 1,
|
|
1859
|
+
description: `Max related files (default ${DEFAULT_RESOLVE_LIMIT})`,
|
|
1860
|
+
}),
|
|
1861
|
+
),
|
|
1862
|
+
});
|
|
1863
|
+
|
|
1864
|
+
registerBoundedTool({
|
|
1865
|
+
name: "related_files",
|
|
1866
|
+
label: "Related Files",
|
|
1867
|
+
description:
|
|
1868
|
+
"Find companion files by stem matching (tests, types, styles).",
|
|
1869
|
+
promptSnippet: "Find companion files",
|
|
1870
|
+
promptGuidelines: [
|
|
1871
|
+
"Pass any file path. Strips test/spec/story/types/styles/.d/.module suffixes.",
|
|
1872
|
+
"Great for finding test files or type defs for a module.",
|
|
1873
|
+
],
|
|
1874
|
+
parameters: relatedFilesSchema,
|
|
1875
|
+
|
|
1876
|
+
async execute(_toolCallId: any, params: any, signal: AbortSignal | undefined) {
|
|
1877
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
1878
|
+
|
|
1879
|
+
let f;
|
|
1880
|
+
try {
|
|
1881
|
+
f = await ensureFinder(activeCwd);
|
|
1882
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
1883
|
+
} catch {
|
|
1884
|
+
return {
|
|
1885
|
+
content: [{ type: "text", text: "FFF search unavailable in this directory." }],
|
|
1886
|
+
details: { reference: "", related: [] },
|
|
1887
|
+
};
|
|
1888
|
+
}
|
|
1889
|
+
const limit = params.limit ?? DEFAULT_RESOLVE_LIMIT;
|
|
1890
|
+
const referenceQuery = stripLeadingAt(params.path);
|
|
1891
|
+
|
|
1892
|
+
// Resolve the reference file first
|
|
1893
|
+
let refResult;
|
|
1894
|
+
try {
|
|
1895
|
+
refResult = f.fileSearch(referenceQuery, { pageSize: limit * 2 });
|
|
1896
|
+
} catch (e) {
|
|
1897
|
+
return {
|
|
1898
|
+
content: [{ type: "text", text: `Search error: ${(e as Error).message}` }],
|
|
1899
|
+
details: { reference: "", related: [] },
|
|
1900
|
+
};
|
|
1901
|
+
}
|
|
1902
|
+
if (!refResult.ok) {
|
|
1903
|
+
return {
|
|
1904
|
+
content: [{ type: "text", text: `Search failed: ${refResult.error}` }],
|
|
1905
|
+
details: { reference: "", related: [] },
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
if (refResult.value.items.length === 0) {
|
|
1909
|
+
return {
|
|
1910
|
+
content: [{ type: "text", text: `No file matched "${referenceQuery}".` }],
|
|
1911
|
+
details: { reference: "", related: [] },
|
|
1912
|
+
};
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
const referencePath = refResult.value.items[0].relativePath;
|
|
1916
|
+
|
|
1917
|
+
const stem = companionStem(referencePath);
|
|
1918
|
+
|
|
1919
|
+
const referenceDir = path.posix.dirname(referencePath);
|
|
1920
|
+
|
|
1921
|
+
// Search only the reference directory for files with the same stem.
|
|
1922
|
+
let relatedResult;
|
|
1923
|
+
try {
|
|
1924
|
+
relatedResult = f.fileSearch(
|
|
1925
|
+
buildQuery(referenceDir === "." ? undefined : `${referenceDir}/`, stem),
|
|
1926
|
+
{ pageSize: limit * 3 },
|
|
1927
|
+
);
|
|
1928
|
+
} catch (e) {
|
|
1929
|
+
return {
|
|
1930
|
+
content: [{ type: "text", text: `Search error: ${(e as Error).message}` }],
|
|
1931
|
+
details: { reference: "", related: [] },
|
|
1932
|
+
};
|
|
1933
|
+
}
|
|
1934
|
+
if (!relatedResult.ok) {
|
|
1935
|
+
return {
|
|
1936
|
+
content: [{ type: "text", text: `Search failed: ${relatedResult.error}` }],
|
|
1937
|
+
details: { reference: "", related: [] },
|
|
1938
|
+
};
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
// Filter out the reference file and keep normalized-stem companions in
|
|
1942
|
+
// the same directory only.
|
|
1943
|
+
const related = relatedResult.value.items
|
|
1944
|
+
.filter((item) => item.relativePath !== referencePath)
|
|
1945
|
+
.filter((item) => {
|
|
1946
|
+
if (path.posix.dirname(item.relativePath) !== referenceDir) return false;
|
|
1947
|
+
return companionStem(item.relativePath) === stem;
|
|
1948
|
+
})
|
|
1949
|
+
.slice(0, limit);
|
|
1950
|
+
|
|
1951
|
+
if (related.length === 0) {
|
|
1952
|
+
return {
|
|
1953
|
+
content: [
|
|
1954
|
+
{
|
|
1955
|
+
type: "text",
|
|
1956
|
+
text: `No related files found for "${referencePath}".`,
|
|
1957
|
+
},
|
|
1958
|
+
],
|
|
1959
|
+
details: { reference: referencePath, related: [] },
|
|
1960
|
+
};
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
const output = [
|
|
1964
|
+
`Related files for ${referencePath}:`,
|
|
1965
|
+
...related.map(
|
|
1966
|
+
(item, i) => `${i + 1}. ${item.relativePath}${fffFileAnnotation(item)}`,
|
|
1967
|
+
),
|
|
1968
|
+
].join("\n");
|
|
1969
|
+
|
|
1970
|
+
return {
|
|
1971
|
+
content: [{ type: "text", text: output }],
|
|
1972
|
+
details: {
|
|
1973
|
+
reference: referencePath,
|
|
1974
|
+
related: related.map((i) => i.relativePath),
|
|
1975
|
+
},
|
|
1976
|
+
};
|
|
1977
|
+
},
|
|
1978
|
+
});
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
// --- commands ---
|
|
1982
|
+
|
|
1983
|
+
pi.registerCommand("fff-mode", {
|
|
1984
|
+
description: "Show or set FFF mode: /fff-mode [tools-and-ui | tools-only | override]",
|
|
1985
|
+
getArgumentCompletions: (prefix) => {
|
|
1986
|
+
const items = VALID_MODES
|
|
1987
|
+
.filter((k) => k.startsWith(prefix.trim().toLowerCase()))
|
|
1988
|
+
.map((k) => ({ value: k, label: k }));
|
|
1989
|
+
return items.length > 0 ? items : null;
|
|
1990
|
+
},
|
|
1991
|
+
handler: async (args, ctx) => {
|
|
1992
|
+
const arg = (args || "").trim();
|
|
1993
|
+
|
|
1994
|
+
// No args - show current mode
|
|
1995
|
+
if (!arg) {
|
|
1996
|
+
ctx.ui.notify(`Current mode: '${currentMode}' (flag: ${pi.getFlag("fff-mode") ?? "unset"})`, "info");
|
|
1997
|
+
return;
|
|
1998
|
+
}
|
|
1999
|
+
|
|
2000
|
+
// Validate and set mode
|
|
2001
|
+
if (!VALID_MODES.includes(arg as FffMode)) {
|
|
2002
|
+
ctx.ui.notify(`Usage: /fff-mode [${VALID_MODES.join(" | ")}]`, "warning");
|
|
2003
|
+
return;
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
const flagMode = pi.getFlag("fff-mode");
|
|
2007
|
+
if (VALID_MODES.includes(flagMode as FffMode) && flagMode !== arg) {
|
|
2008
|
+
ctx.ui.notify(`Mode is fixed by --fff-mode=${flagMode}. Restart without the flag to change it.`, "warning");
|
|
2009
|
+
return;
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
const newMode = arg as FffMode;
|
|
2013
|
+
const oldMode = currentMode;
|
|
2014
|
+
currentMode = newMode;
|
|
2015
|
+
process.env.PI_FFF_MODE = newMode;
|
|
2016
|
+
|
|
2017
|
+
if ((oldMode === "override") !== (newMode === "override")) {
|
|
2018
|
+
ctx.ui.notify(`Mode changed: '${oldMode}' → '${newMode}'. Reloading tools...`, "info");
|
|
2019
|
+
await ctx.reload();
|
|
2020
|
+
return;
|
|
2021
|
+
}
|
|
2022
|
+
ctx.ui.notify(`Mode changed: '${oldMode}' → '${newMode}'`, "info");
|
|
2023
|
+
},
|
|
2024
|
+
});
|
|
2025
|
+
|
|
2026
|
+
pi.registerCommand("fff-health", {
|
|
2027
|
+
description: "Show FFF file finder health and status",
|
|
2028
|
+
handler: async (_args, ctx) => {
|
|
2029
|
+
if (!finder || finder.isDestroyed) {
|
|
2030
|
+
try {
|
|
2031
|
+
await ensureFinder(activeCwd);
|
|
2032
|
+
} catch {
|
|
2033
|
+
ctx.ui.notify("FFF initialization failed", "warning");
|
|
2034
|
+
return;
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
if (!finder || finder.isDestroyed) {
|
|
2038
|
+
ctx.ui.notify("FFF initializing", "warning");
|
|
2039
|
+
return;
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
const health = finder.healthCheck();
|
|
2043
|
+
if (!health.ok) {
|
|
2044
|
+
ctx.ui.notify(`Health check failed: ${health.error}`, "error");
|
|
2045
|
+
return;
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
const h = health.value;
|
|
2049
|
+
const lines = [
|
|
2050
|
+
`FFF v${h.version}`,
|
|
2051
|
+
`Mode: ${currentMode}`,
|
|
2052
|
+
`Git: ${h.git.repositoryFound ? `yes (${h.git.workdir ?? "unknown"})` : "no"}`,
|
|
2053
|
+
`Picker: ${h.filePicker.initialized ? `${h.filePicker.indexedFiles ?? 0} files` : "not initialized"}`,
|
|
2054
|
+
`Frecency: ${h.frecency.initialized ? "active" : "disabled"}`,
|
|
2055
|
+
`Query tracker: ${h.queryTracker.initialized ? "active" : "disabled"}`,
|
|
2056
|
+
];
|
|
2057
|
+
|
|
2058
|
+
const progress = finder.getScanProgress();
|
|
2059
|
+
if (progress.ok) {
|
|
2060
|
+
lines.push(
|
|
2061
|
+
`Scanning: ${progress.value.isScanning ? "yes" : "no"} (${progress.value.scannedFilesCount} files)`,
|
|
2062
|
+
);
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
2066
|
+
},
|
|
2067
|
+
});
|
|
2068
|
+
|
|
2069
|
+
pi.registerCommand("fff-rescan", {
|
|
2070
|
+
description: "Trigger FFF to rescan files",
|
|
2071
|
+
handler: async (_args, ctx) => {
|
|
2072
|
+
if (!finder || finder.isDestroyed) {
|
|
2073
|
+
try {
|
|
2074
|
+
await ensureFinder(activeCwd);
|
|
2075
|
+
} catch {
|
|
2076
|
+
ctx.ui.notify("FFF initialization failed", "warning");
|
|
2077
|
+
return;
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
if (!finder || finder.isDestroyed) {
|
|
2081
|
+
ctx.ui.notify("FFF initializing", "warning");
|
|
2082
|
+
return;
|
|
2083
|
+
}
|
|
2084
|
+
|
|
2085
|
+
const result = finder.scanFiles();
|
|
2086
|
+
if (!result.ok) {
|
|
2087
|
+
ctx.ui.notify(`Rescan failed: ${result.error}`, "error");
|
|
2088
|
+
return;
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
ctx.ui.notify("FFF rescan triggered", "info");
|
|
2092
|
+
},
|
|
2093
|
+
});
|
|
2094
|
+
}
|