@duckmind/dm-darwin-x64 0.43.4 → 0.48.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/dm +0 -0
  2. package/extensions/.dm-extensions.json +242 -50
  3. package/extensions/dm-9router-ext/package.json +2 -19
  4. package/extensions/dm-9router-ext/src/index.js +5 -0
  5. package/extensions/dm-ask-user/index.js +10 -0
  6. package/extensions/dm-ask-user/package.json +1 -21
  7. package/extensions/dm-cli-anything/package.json +0 -6
  8. package/extensions/dm-context/package.json +2 -12
  9. package/extensions/dm-context/src/context.js +1 -0
  10. package/extensions/dm-context/src/index.js +7 -0
  11. package/extensions/dm-context/src/utils.js +1 -0
  12. package/extensions/dm-cua/package.json +0 -7
  13. package/extensions/dm-fff/package.json +1 -28
  14. package/extensions/dm-fff/src/index.js +15 -0
  15. package/extensions/dm-fff/src/query.js +1 -0
  16. package/extensions/dm-goal/package.json +2 -31
  17. package/extensions/dm-goal/src/goal.js +43 -0
  18. package/extensions/dm-grill-me/index.js +174 -0
  19. package/extensions/dm-grill-me/package.json +1 -26
  20. package/extensions/dm-image2/package.json +0 -7
  21. package/extensions/dm-subagents/package.json +1 -32
  22. package/extensions/dm-subagents/src/agents/agent-management.js +37 -0
  23. package/extensions/dm-subagents/src/agents/agent-memory.js +6 -0
  24. package/extensions/dm-subagents/src/agents/agent-scope.js +1 -0
  25. package/extensions/dm-subagents/src/agents/agent-selection.js +1 -0
  26. package/extensions/dm-subagents/src/agents/agent-serializer.js +7 -0
  27. package/extensions/dm-subagents/src/agents/agents.js +11 -0
  28. package/extensions/dm-subagents/src/agents/chain-serializer.js +12 -0
  29. package/extensions/dm-subagents/src/agents/frontmatter.js +6 -0
  30. package/extensions/dm-subagents/src/agents/identity.js +1 -0
  31. package/extensions/dm-subagents/src/agents/proactive-skills.js +1 -0
  32. package/extensions/dm-subagents/src/agents/skills.js +6 -0
  33. package/extensions/dm-subagents/src/extension/config.js +2 -0
  34. package/extensions/dm-subagents/src/extension/control-notices.js +4 -0
  35. package/extensions/dm-subagents/src/extension/doctor.js +16 -0
  36. package/extensions/dm-subagents/src/extension/fanout-child.js +231 -0
  37. package/extensions/dm-subagents/src/extension/index.js +367 -0
  38. package/extensions/dm-subagents/src/extension/rpc.js +8 -0
  39. package/extensions/dm-subagents/src/extension/schemas.js +1 -0
  40. package/extensions/dm-subagents/src/extension/{tool-description.ts → tool-description.js} +6 -126
  41. package/extensions/dm-subagents/src/intercom/intercom-bridge.js +13 -0
  42. package/extensions/dm-subagents/src/intercom/native-supervisor-channel.js +5 -0
  43. package/extensions/dm-subagents/src/intercom/result-intercom.js +3 -0
  44. package/extensions/dm-subagents/src/profiles/profiles.js +3 -0
  45. package/extensions/dm-subagents/src/runs/background/async-execution.js +46 -0
  46. package/extensions/dm-subagents/src/runs/background/async-job-tracker.js +14 -0
  47. package/extensions/dm-subagents/src/runs/background/async-resume.js +8 -0
  48. package/extensions/dm-subagents/src/runs/background/async-status.js +12 -0
  49. package/extensions/dm-subagents/src/runs/background/chain-append.js +2 -0
  50. package/extensions/dm-subagents/src/runs/background/chain-root-attachment.js +1 -0
  51. package/extensions/dm-subagents/src/runs/background/completion-batcher.js +1 -0
  52. package/extensions/dm-subagents/src/runs/background/completion-dedupe.js +1 -0
  53. package/extensions/dm-subagents/src/runs/background/control-channel.js +1 -0
  54. package/extensions/dm-subagents/src/runs/background/fleet-view.js +17 -0
  55. package/extensions/dm-subagents/src/runs/background/notify.js +3 -0
  56. package/extensions/dm-subagents/src/runs/background/parallel-groups.js +1 -0
  57. package/extensions/dm-subagents/src/runs/background/result-watcher.js +8 -0
  58. package/extensions/dm-subagents/src/runs/background/run-id-resolver.js +4 -0
  59. package/extensions/dm-subagents/src/runs/background/run-status.js +23 -0
  60. package/extensions/dm-subagents/src/runs/background/scheduled-runs.js +4 -0
  61. package/extensions/dm-subagents/src/runs/background/stale-run-reconciler.js +11 -0
  62. package/extensions/dm-subagents/src/runs/background/subagent-runner.js +78 -0
  63. package/extensions/dm-subagents/src/runs/background/top-level-async.js +1 -0
  64. package/extensions/dm-subagents/src/runs/background/wait.js +11 -0
  65. package/extensions/dm-subagents/src/runs/foreground/chain-clarify.js +12 -0
  66. package/extensions/dm-subagents/src/runs/foreground/chain-execution.js +102 -0
  67. package/extensions/dm-subagents/src/runs/foreground/execution.js +51 -0
  68. package/extensions/dm-subagents/src/runs/foreground/subagent-executor.js +228 -0
  69. package/extensions/dm-subagents/src/runs/shared/acceptance.js +3 -0
  70. package/extensions/dm-subagents/src/runs/shared/chain-outputs.js +1 -0
  71. package/extensions/dm-subagents/src/runs/shared/completion-guard.js +3 -0
  72. package/extensions/dm-subagents/src/runs/shared/dm-args.js +1 -0
  73. package/extensions/dm-subagents/src/runs/shared/dm-spawn.js +1 -0
  74. package/extensions/dm-subagents/src/runs/shared/dynamic-fanout.js +1 -0
  75. package/extensions/dm-subagents/src/runs/shared/long-running-guard.js +1 -0
  76. package/extensions/dm-subagents/src/runs/shared/mcp-direct-tool-allowlist.js +1 -0
  77. package/extensions/dm-subagents/src/runs/shared/model-fallback.js +1 -0
  78. package/extensions/dm-subagents/src/runs/shared/model-scope.js +1 -0
  79. package/extensions/dm-subagents/src/runs/shared/nested-events.js +8 -0
  80. package/extensions/dm-subagents/src/runs/shared/nested-path.js +1 -0
  81. package/extensions/dm-subagents/src/runs/shared/nested-render.js +1 -0
  82. package/extensions/dm-subagents/src/runs/shared/parallel-utils.js +5 -0
  83. package/extensions/dm-subagents/src/runs/shared/run-history.js +5 -0
  84. package/extensions/dm-subagents/src/runs/shared/single-output.js +14 -0
  85. package/extensions/dm-subagents/src/runs/shared/structured-output.js +1 -0
  86. package/extensions/dm-subagents/src/runs/shared/subagent-control.js +5 -0
  87. package/extensions/dm-subagents/src/runs/shared/subagent-prompt-runtime.js +22 -0
  88. package/extensions/dm-subagents/src/runs/shared/tool-budget.js +1 -0
  89. package/extensions/dm-subagents/src/runs/shared/turn-budget.js +7 -0
  90. package/extensions/dm-subagents/src/runs/shared/workflow-graph.js +1 -0
  91. package/extensions/dm-subagents/src/runs/shared/worktree.js +3 -0
  92. package/extensions/dm-subagents/src/shared/artifacts.js +2 -0
  93. package/extensions/dm-subagents/src/shared/atomic-json.js +1 -0
  94. package/extensions/dm-subagents/src/shared/child-transcript.js +5 -0
  95. package/extensions/dm-subagents/src/shared/file-coalescer.js +1 -0
  96. package/extensions/dm-subagents/src/shared/fork-context.js +6 -0
  97. package/extensions/dm-subagents/src/shared/formatters.js +9 -0
  98. package/extensions/dm-subagents/src/shared/jsonl-writer.js +2 -0
  99. package/extensions/dm-subagents/src/shared/model-info.js +1 -0
  100. package/extensions/dm-subagents/src/shared/post-exit-stdio-guard.js +1 -0
  101. package/extensions/dm-subagents/src/shared/session-identity.js +1 -0
  102. package/extensions/dm-subagents/src/shared/session-tokens.js +2 -0
  103. package/extensions/dm-subagents/src/shared/settings.js +23 -0
  104. package/extensions/dm-subagents/src/shared/status-format.js +1 -0
  105. package/extensions/dm-subagents/src/shared/types.js +8 -0
  106. package/extensions/dm-subagents/src/shared/utils.js +2 -0
  107. package/extensions/dm-subagents/src/slash/prompt-template-bridge.js +1 -0
  108. package/extensions/dm-subagents/src/slash/prompt-workflows.js +7 -0
  109. package/extensions/dm-subagents/src/slash/slash-bridge.js +1 -0
  110. package/extensions/dm-subagents/src/slash/slash-commands.js +38 -0
  111. package/extensions/dm-subagents/src/slash/slash-live-state.js +6 -0
  112. package/extensions/dm-subagents/src/tui/render-helpers.js +1 -0
  113. package/extensions/dm-subagents/src/tui/render.js +4 -0
  114. package/extensions/dm-tasks/package.json +1 -30
  115. package/extensions/dm-tasks/src/auto-clear.js +1 -0
  116. package/extensions/dm-tasks/src/index.js +212 -0
  117. package/extensions/dm-tasks/src/process-tracker.js +1 -0
  118. package/extensions/dm-tasks/src/task-store.js +1 -0
  119. package/extensions/dm-tasks/src/tasks-config.js +1 -0
  120. package/extensions/dm-tasks/src/types.js +0 -0
  121. package/extensions/dm-tasks/src/ui/settings-menu.js +1 -0
  122. package/extensions/dm-tasks/src/ui/task-widget.js +1 -0
  123. package/extensions/dm-usage/index.js +9 -0
  124. package/extensions/dm-usage/package.json +1 -18
  125. package/extensions/greedysearch-dm/bin/search.mjs +51 -51
  126. package/extensions/greedysearch-dm/index.js +20 -0
  127. package/extensions/greedysearch-dm/package.json +1 -22
  128. package/extensions/greedysearch-dm/src/formatters/results.js +8 -0
  129. package/extensions/greedysearch-dm/src/formatters/sources.js +1 -0
  130. package/extensions/greedysearch-dm/src/formatters/synthesis.js +1 -0
  131. package/extensions/greedysearch-dm/src/search/research.mjs +59 -59
  132. package/extensions/greedysearch-dm/src/search/synthesis-runner.mjs +10 -10
  133. package/extensions/greedysearch-dm/src/tools/greedy-search-handler.js +20 -0
  134. package/extensions/greedysearch-dm/src/tools/shared.js +9 -0
  135. package/extensions/greedysearch-dm/src/types.js +0 -0
  136. package/extensions/greedysearch-dm/src/utils/helpers.js +1 -0
  137. package/package.json +1 -1
  138. package/extensions/dm-9router-ext/src/index.ts +0 -541
  139. package/extensions/dm-ask-user/index.ts +0 -857
  140. package/extensions/dm-context/src/context.ts +0 -158
  141. package/extensions/dm-context/src/index.ts +0 -439
  142. package/extensions/dm-context/src/utils.ts +0 -6
  143. package/extensions/dm-fff/src/index.ts +0 -1023
  144. package/extensions/dm-fff/src/query.ts +0 -87
  145. package/extensions/dm-goal/src/goal.ts +0 -1073
  146. package/extensions/dm-grill-me/index.ts +0 -1085
  147. package/extensions/dm-subagents/src/agents/agent-management.ts +0 -1052
  148. package/extensions/dm-subagents/src/agents/agent-memory.ts +0 -254
  149. package/extensions/dm-subagents/src/agents/agent-scope.ts +0 -6
  150. package/extensions/dm-subagents/src/agents/agent-selection.ts +0 -25
  151. package/extensions/dm-subagents/src/agents/agent-serializer.ts +0 -121
  152. package/extensions/dm-subagents/src/agents/agents.ts +0 -1553
  153. package/extensions/dm-subagents/src/agents/chain-serializer.ts +0 -277
  154. package/extensions/dm-subagents/src/agents/frontmatter.ts +0 -93
  155. package/extensions/dm-subagents/src/agents/identity.ts +0 -30
  156. package/extensions/dm-subagents/src/agents/proactive-skills.ts +0 -191
  157. package/extensions/dm-subagents/src/agents/skills.ts +0 -729
  158. package/extensions/dm-subagents/src/extension/config.ts +0 -39
  159. package/extensions/dm-subagents/src/extension/control-notices.ts +0 -92
  160. package/extensions/dm-subagents/src/extension/doctor.ts +0 -214
  161. package/extensions/dm-subagents/src/extension/fanout-child.ts +0 -172
  162. package/extensions/dm-subagents/src/extension/index.ts +0 -656
  163. package/extensions/dm-subagents/src/extension/rpc.ts +0 -369
  164. package/extensions/dm-subagents/src/extension/schemas.ts +0 -309
  165. package/extensions/dm-subagents/src/intercom/intercom-bridge.ts +0 -180
  166. package/extensions/dm-subagents/src/intercom/native-supervisor-channel.ts +0 -519
  167. package/extensions/dm-subagents/src/intercom/result-intercom.ts +0 -377
  168. package/extensions/dm-subagents/src/profiles/profiles.ts +0 -637
  169. package/extensions/dm-subagents/src/runs/background/async-execution.ts +0 -1065
  170. package/extensions/dm-subagents/src/runs/background/async-job-tracker.ts +0 -441
  171. package/extensions/dm-subagents/src/runs/background/async-resume.ts +0 -391
  172. package/extensions/dm-subagents/src/runs/background/async-status.ts +0 -395
  173. package/extensions/dm-subagents/src/runs/background/chain-append.ts +0 -282
  174. package/extensions/dm-subagents/src/runs/background/chain-root-attachment.ts +0 -191
  175. package/extensions/dm-subagents/src/runs/background/completion-batcher.ts +0 -166
  176. package/extensions/dm-subagents/src/runs/background/completion-dedupe.ts +0 -63
  177. package/extensions/dm-subagents/src/runs/background/control-channel.ts +0 -332
  178. package/extensions/dm-subagents/src/runs/background/fleet-view.ts +0 -515
  179. package/extensions/dm-subagents/src/runs/background/notify.ts +0 -225
  180. package/extensions/dm-subagents/src/runs/background/parallel-groups.ts +0 -45
  181. package/extensions/dm-subagents/src/runs/background/result-watcher.ts +0 -315
  182. package/extensions/dm-subagents/src/runs/background/run-id-resolver.ts +0 -84
  183. package/extensions/dm-subagents/src/runs/background/run-status.ts +0 -434
  184. package/extensions/dm-subagents/src/runs/background/scheduled-runs.ts +0 -514
  185. package/extensions/dm-subagents/src/runs/background/stale-run-reconciler.ts +0 -368
  186. package/extensions/dm-subagents/src/runs/background/subagent-runner.ts +0 -3171
  187. package/extensions/dm-subagents/src/runs/background/top-level-async.ts +0 -13
  188. package/extensions/dm-subagents/src/runs/background/wait.ts +0 -353
  189. package/extensions/dm-subagents/src/runs/foreground/chain-clarify.ts +0 -1333
  190. package/extensions/dm-subagents/src/runs/foreground/chain-execution.ts +0 -1313
  191. package/extensions/dm-subagents/src/runs/foreground/execution.ts +0 -1239
  192. package/extensions/dm-subagents/src/runs/foreground/subagent-executor.ts +0 -3613
  193. package/extensions/dm-subagents/src/runs/shared/acceptance.ts +0 -879
  194. package/extensions/dm-subagents/src/runs/shared/chain-outputs.ts +0 -116
  195. package/extensions/dm-subagents/src/runs/shared/completion-guard.ts +0 -147
  196. package/extensions/dm-subagents/src/runs/shared/dm-args.ts +0 -271
  197. package/extensions/dm-subagents/src/runs/shared/dm-spawn.ts +0 -147
  198. package/extensions/dm-subagents/src/runs/shared/dynamic-fanout.ts +0 -295
  199. package/extensions/dm-subagents/src/runs/shared/long-running-guard.ts +0 -175
  200. package/extensions/dm-subagents/src/runs/shared/mcp-direct-tool-allowlist.ts +0 -365
  201. package/extensions/dm-subagents/src/runs/shared/model-fallback.ts +0 -292
  202. package/extensions/dm-subagents/src/runs/shared/model-scope.ts +0 -128
  203. package/extensions/dm-subagents/src/runs/shared/nested-events.ts +0 -908
  204. package/extensions/dm-subagents/src/runs/shared/nested-path.ts +0 -52
  205. package/extensions/dm-subagents/src/runs/shared/nested-render.ts +0 -115
  206. package/extensions/dm-subagents/src/runs/shared/parallel-utils.ts +0 -198
  207. package/extensions/dm-subagents/src/runs/shared/run-history.ts +0 -60
  208. package/extensions/dm-subagents/src/runs/shared/single-output.ts +0 -180
  209. package/extensions/dm-subagents/src/runs/shared/structured-output.ts +0 -77
  210. package/extensions/dm-subagents/src/runs/shared/subagent-control.ts +0 -223
  211. package/extensions/dm-subagents/src/runs/shared/subagent-prompt-runtime.ts +0 -342
  212. package/extensions/dm-subagents/src/runs/shared/tool-budget.ts +0 -74
  213. package/extensions/dm-subagents/src/runs/shared/turn-budget.ts +0 -52
  214. package/extensions/dm-subagents/src/runs/shared/workflow-graph.ts +0 -206
  215. package/extensions/dm-subagents/src/runs/shared/worktree.ts +0 -600
  216. package/extensions/dm-subagents/src/shared/artifacts.ts +0 -113
  217. package/extensions/dm-subagents/src/shared/atomic-json.ts +0 -86
  218. package/extensions/dm-subagents/src/shared/child-transcript.ts +0 -212
  219. package/extensions/dm-subagents/src/shared/file-coalescer.ts +0 -40
  220. package/extensions/dm-subagents/src/shared/fork-context.ts +0 -194
  221. package/extensions/dm-subagents/src/shared/formatters.ts +0 -133
  222. package/extensions/dm-subagents/src/shared/jsonl-writer.ts +0 -81
  223. package/extensions/dm-subagents/src/shared/model-info.ts +0 -78
  224. package/extensions/dm-subagents/src/shared/post-exit-stdio-guard.ts +0 -85
  225. package/extensions/dm-subagents/src/shared/session-identity.ts +0 -10
  226. package/extensions/dm-subagents/src/shared/session-tokens.ts +0 -44
  227. package/extensions/dm-subagents/src/shared/settings.ts +0 -450
  228. package/extensions/dm-subagents/src/shared/status-format.ts +0 -49
  229. package/extensions/dm-subagents/src/shared/types.ts +0 -1257
  230. package/extensions/dm-subagents/src/shared/utils.ts +0 -554
  231. package/extensions/dm-subagents/src/slash/prompt-template-bridge.ts +0 -420
  232. package/extensions/dm-subagents/src/slash/prompt-workflows.ts +0 -330
  233. package/extensions/dm-subagents/src/slash/slash-bridge.ts +0 -176
  234. package/extensions/dm-subagents/src/slash/slash-commands.ts +0 -1296
  235. package/extensions/dm-subagents/src/slash/slash-live-state.ts +0 -292
  236. package/extensions/dm-subagents/src/tui/render-helpers.ts +0 -80
  237. package/extensions/dm-subagents/src/tui/render.ts +0 -1748
  238. package/extensions/dm-tasks/src/auto-clear.ts +0 -91
  239. package/extensions/dm-tasks/src/index.ts +0 -1145
  240. package/extensions/dm-tasks/src/process-tracker.ts +0 -140
  241. package/extensions/dm-tasks/src/task-store.ts +0 -305
  242. package/extensions/dm-tasks/src/tasks-config.ts +0 -23
  243. package/extensions/dm-tasks/src/types.ts +0 -40
  244. package/extensions/dm-tasks/src/ui/settings-menu.ts +0 -100
  245. package/extensions/dm-tasks/src/ui/task-widget.ts +0 -265
  246. package/extensions/dm-usage/index.ts +0 -1718
  247. package/extensions/greedysearch-dm/index.ts +0 -177
  248. package/extensions/greedysearch-dm/src/formatters/results.ts +0 -163
  249. package/extensions/greedysearch-dm/src/formatters/sources.ts +0 -116
  250. package/extensions/greedysearch-dm/src/formatters/synthesis.ts +0 -87
  251. package/extensions/greedysearch-dm/src/tools/greedy-search-handler.ts +0 -370
  252. package/extensions/greedysearch-dm/src/tools/shared.ts +0 -187
  253. package/extensions/greedysearch-dm/src/types.ts +0 -110
  254. package/extensions/greedysearch-dm/src/utils/helpers.ts +0 -40
@@ -1,1023 +0,0 @@
1
- /**
2
- * dm-fff: FFF-powered file search extension for DM
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 "@duckmind/dm-coding-agent";
9
- import {
10
- type AutocompleteItem,
11
- type AutocompleteProvider,
12
- Text,
13
- } from "@duckmind/dm-tui";
14
- import type {
15
- GrepCursor,
16
- GrepMode,
17
- GrepResult,
18
- MixedItem,
19
- SearchResult,
20
- } from "@ff-labs/fff-node";
21
- import { FileFinder } from "@ff-labs/fff-node";
22
- import { Type } from "@sinclair/typebox";
23
- import { buildQuery } from "./query";
24
-
25
- // ---------------------------------------------------------------------------
26
- // Constants
27
- // ---------------------------------------------------------------------------
28
-
29
- const DEFAULT_GREP_LIMIT = 20;
30
- const DEFAULT_FIND_LIMIT = 30;
31
- const GREP_MAX_LINE_LENGTH = 500;
32
- const MENTION_MAX_RESULTS = 20;
33
-
34
- type FffMode = "tools-and-ui" | "tools-only" | "override";
35
-
36
- const VALID_MODES: FffMode[] = ["tools-and-ui", "tools-only", "override"];
37
-
38
- interface ToolNames {
39
- grep: string;
40
- find: string;
41
- multiGrep: string;
42
- }
43
-
44
- const FFF_TOOL_NAMES: ToolNames = {
45
- grep: "ffgrep",
46
- find: "fffind",
47
- multiGrep: "fff-multi-grep",
48
- };
49
- const OVERRIDE_TOOL_NAMES: ToolNames = {
50
- grep: "grep",
51
- find: "find",
52
- multiGrep: "multi_grep",
53
- };
54
-
55
- function resolveToolNames(mode: FffMode): ToolNames {
56
- return mode === "override" ? OVERRIDE_TOOL_NAMES : FFF_TOOL_NAMES;
57
- }
58
-
59
- // ---------------------------------------------------------------------------
60
- // Cursor store — simple bounded Map for pagination cursors
61
- // ---------------------------------------------------------------------------
62
-
63
- const cursorCache = new Map<string, GrepCursor>();
64
- let cursorCounter = 0;
65
-
66
- function storeCursor(cursor: GrepCursor): string {
67
- const id = `fff_c${++cursorCounter}`;
68
- cursorCache.set(id, cursor);
69
- if (cursorCache.size > 200) {
70
- const first = cursorCache.keys().next().value;
71
- if (first) cursorCache.delete(first);
72
- }
73
- return id;
74
- }
75
-
76
- function getCursor(id: string): GrepCursor | undefined {
77
- return cursorCache.get(id);
78
- }
79
-
80
- // Find pagination uses a page-index cursor: native `fileSearch` takes
81
- // pageIndex/pageSize, so the cursor is just the next page index paired with
82
- // the query+limit that produced it. Stored tokens are opaque IDs to the agent.
83
- interface FindCursor {
84
- query: string;
85
- pattern: string;
86
- pageSize: number;
87
- nextPageIndex: number;
88
- }
89
-
90
- const findCursorCache = new Map<string, FindCursor>();
91
- let findCursorCounter = 0;
92
-
93
- function storeFindCursor(cursor: FindCursor): string {
94
- const id = `${++findCursorCounter}`;
95
- findCursorCache.set(id, cursor);
96
- if (findCursorCache.size > 200) {
97
- const first = findCursorCache.keys().next().value;
98
- if (first) findCursorCache.delete(first);
99
- }
100
- return id;
101
- }
102
-
103
- function getFindCursor(id: string): FindCursor | undefined {
104
- return findCursorCache.get(id);
105
- }
106
-
107
- // ---------------------------------------------------------------------------
108
- // Output formatting helpers
109
- // ---------------------------------------------------------------------------
110
-
111
- function truncateLine(line: string, max = GREP_MAX_LINE_LENGTH): string {
112
- const trimmed = line.trim();
113
- return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max)}...`;
114
- }
115
-
116
- const HOT_FRECENCY = 25;
117
- const WARM_FRECENCY = 20;
118
-
119
- // Shared annotation helper for both find-output paths and grep-output file
120
- // headers. Returns at most ONE tag so output stays scannable. Priority:
121
- // git-dirty (most actionable — file is changing right now) beats frecency
122
- // (historically often-touched). Keeping one function ensures the two tools
123
- // never drift in how they surface git/frecency signal.
124
- export function fffFileAnnotation(item: {
125
- gitStatus?: string;
126
- totalFrecencyScore?: number;
127
- accessFrecencyScore?: number;
128
- }): string {
129
- const git = item.gitStatus;
130
- if (git && git !== "clean" && git !== "unknown" && git !== "") {
131
- return ` [${git} in git]`;
132
- }
133
-
134
- const frecency = item.totalFrecencyScore ?? item.accessFrecencyScore ?? 0;
135
- if (frecency >= HOT_FRECENCY) return " [VERY often touched file]";
136
- if (frecency >= WARM_FRECENCY) return " [often touched file]";
137
-
138
- return "";
139
- }
140
-
141
- // fff-core native definition classifier (byte-level scanner in Rust) is enabled
142
- // via GrepOptions.classifyDefinitions. Each GrepMatch carries isDefinition for
143
- // downstream consumers; dm-fff does NOT use it to re-sort.
144
- //
145
- // Ordering policy: NO CUSTOM SORTING. The engine already returns items in
146
- // frecency order (most-accessed files first). dm-fff only groups consecutive
147
- // matches into per-file blocks and preserves whatever order the engine
148
- // provided — inside a file we keep matches in source-line order because the
149
- // engine emits them that way.
150
-
151
- function formatGrepOutput(result: GrepResult): string {
152
- if (result.items.length === 0) return "No matches found";
153
-
154
- // Build file-grouped output in the order files first appear in the result.
155
- // This preserves native frecency ordering across files without re-sorting.
156
- const lines: string[] = [];
157
- let currentFile = "";
158
- let shown = 0;
159
-
160
- for (const match of result.items) {
161
- if (match.relativePath !== currentFile) {
162
- if (lines.length > 0) lines.push("");
163
- currentFile = match.relativePath;
164
- lines.push(`${currentFile}${fffFileAnnotation(match)}`);
165
- }
166
-
167
- match.contextBefore?.forEach((line: string, i: number) => {
168
- const lineNum = match.lineNumber - match.contextBefore!.length + i;
169
- lines.push(` ${lineNum}- ${truncateLine(line)}`);
170
- });
171
-
172
- lines.push(` ${match.lineNumber}: ${truncateLine(match.lineContent)}`);
173
- shown++;
174
-
175
- match.contextAfter?.forEach((line: string, i: number) => {
176
- const lineNum = match.lineNumber + 1 + i;
177
- lines.push(` ${lineNum}- ${truncateLine(line)}`);
178
- });
179
- }
180
-
181
- return lines.join("\n");
182
- }
183
-
184
- // Weak-match threshold is derived from the query length, matching the
185
- // scoring formula in crates/fff-core/src/score.rs: a perfect match scores
186
- // `len * 16`, so we treat anything below 50% of that as scattered fuzzy noise.
187
- // When the top score is weak, trim output to a small sample instead of dumping
188
- // the full limit worth of noise into the agent's context.
189
- const FIND_WEAK_SAMPLE_SIZE = 5;
190
-
191
- function weakScoreThreshold(pattern: string): number {
192
- const perfect = pattern.length * 12;
193
- return Math.floor((perfect * 50) / 100);
194
- }
195
-
196
- interface FormattedFind {
197
- output: string;
198
- weak: boolean;
199
- shownCount: number;
200
- }
201
-
202
- function formatFindOutput(
203
- result: SearchResult,
204
- limit: number,
205
- pattern: string,
206
- ): FormattedFind {
207
- if (result.items.length === 0) {
208
- return {
209
- output: "No files found matching pattern",
210
- weak: false,
211
- shownCount: 0,
212
- };
213
- }
214
-
215
- // NO CUSTOM SORTING — trust native frecency order from the engine.
216
- const reordered = result.items.map((item) => ({ item }));
217
-
218
- // Peek at the top native score to decide whether results are scattered
219
- // fuzzy noise (query length-scaled threshold from score.rs).
220
- const topScore = result.scores[0]?.total ?? 0;
221
- const weak = topScore < weakScoreThreshold(pattern);
222
- const effective = weak ? Math.min(FIND_WEAK_SAMPLE_SIZE, limit) : limit;
223
- const shown = reordered.slice(0, effective);
224
-
225
- return {
226
- output: shown
227
- .map((p) => `${p.item.relativePath}${fffFileAnnotation(p.item)}`)
228
- .join("\n"),
229
- weak,
230
- shownCount: shown.length,
231
- };
232
- }
233
-
234
- // ---------------------------------------------------------------------------
235
- // Mention autocomplete helpers
236
- // ---------------------------------------------------------------------------
237
-
238
- function extractAtPrefix(textBeforeCursor: string): string | null {
239
- const match = textBeforeCursor.match(/(?:^|[ \t])(@(?:"[^"]*|[^\s]*))$/);
240
- return match?.[1] ?? null;
241
- }
242
-
243
- function buildAtCompletionValue(path: string): string {
244
- return path.includes(" ") ? `@"${path}"` : `@${path}`;
245
- }
246
-
247
- function createFffMentionProvider(
248
- getItems: (query: string, signal: AbortSignal) => Promise<AutocompleteItem[]>,
249
- ): AutocompleteProvider {
250
- return {
251
- async getSuggestions(lines, cursorLine, cursorCol, options) {
252
- const currentLine = lines[cursorLine] || "";
253
- const prefix = extractAtPrefix(currentLine.slice(0, cursorCol));
254
- if (!prefix || options.signal.aborted) return null;
255
-
256
- const query = prefix.startsWith('@"') ? prefix.slice(2) : prefix.slice(1);
257
- const items = await getItems(query, options.signal);
258
- return options.signal.aborted || items.length === 0 ? null : { items, prefix };
259
- },
260
- applyCompletion(_lines, cursorLine, cursorCol, item, prefix) {
261
- const currentLine = _lines[cursorLine] || "";
262
- const before = currentLine.slice(0, cursorCol - prefix.length);
263
- const after = currentLine.slice(cursorCol);
264
- const newLine = before + item.value + after;
265
- const newCursorCol = cursorCol - prefix.length + item.value.length;
266
- return {
267
- lines: [..._lines.slice(0, cursorLine), newLine, ..._lines.slice(cursorLine + 1)],
268
- cursorLine,
269
- cursorCol: newCursorCol,
270
- };
271
- },
272
- };
273
- }
274
-
275
- // ---------------------------------------------------------------------------
276
- // Extension
277
- // ---------------------------------------------------------------------------
278
-
279
- export default function fffExtension(dm: ExtensionAPI) {
280
- let finder: FileFinder | null = null;
281
- let finderCwd: string | null = null;
282
- // Concurrent ensureFinder() callers share the same in-flight promise so
283
- // FileFinder.create() (which takes native DB locks) runs at most once per
284
- // base path at a time — otherwise parallel tool calls would race and
285
- // deadlock at the native layer (issue #403).
286
- let finderPromise: Promise<FileFinder> | null = null;
287
- let activeCwd = process.cwd();
288
-
289
- // Mode resolution: flag > env > default
290
- let currentMode: FffMode =
291
- (dm.getFlag("fff-mode") as FffMode) ??
292
- (process.env.DM_FFF_MODE as FffMode) ??
293
- "tools-and-ui";
294
-
295
- const toolNames = resolveToolNames(currentMode);
296
-
297
- // DB path resolution: flag > env > undefined (use fff-node defaults)
298
- const frecencyDbPath =
299
- (dm.getFlag("fff-frecency-db") as string | undefined) ??
300
- process.env.FFF_FRECENCY_DB ??
301
- undefined;
302
- const historyDbPath =
303
- (dm.getFlag("fff-history-db") as string | undefined) ??
304
- process.env.FFF_HISTORY_DB ??
305
- undefined;
306
-
307
- // Root scanning opt-in: flag (boolean) > env ("1"/"true") > false.
308
- // FFF refuses to init at / unless this is set. Home dir scanning is on by
309
- // default for DM — launching dm from $HOME is a normal flow.
310
- function resolveBoolOpt(flagName: string, envName: string): boolean {
311
- const flag = dm.getFlag(flagName);
312
- if (typeof flag === "boolean") return flag;
313
- if (typeof flag === "string") return flag === "true" || flag === "1";
314
- const env = process.env[envName];
315
- return env === "1" || env === "true";
316
- }
317
- const enableFsRootScanning = resolveBoolOpt(
318
- "fff-enable-root-scan",
319
- "FFF_ENABLE_ROOT_SCAN",
320
- );
321
-
322
- function getMode(): FffMode {
323
- return currentMode;
324
- }
325
-
326
- function setMode(mode: FffMode): void {
327
- currentMode = mode;
328
- }
329
-
330
- function shouldEnableMentions(): boolean {
331
- return currentMode !== "tools-only";
332
- }
333
-
334
- function ensureFinder(cwd: string): Promise<FileFinder> {
335
- if (finder && !finder.isDestroyed && finderCwd === cwd)
336
- return Promise.resolve(finder);
337
- if (finderPromise) return finderPromise;
338
-
339
- finderPromise = (async () => {
340
- if (finder && !finder.isDestroyed) {
341
- finder.destroy();
342
- finder = null;
343
- finderCwd = null;
344
- }
345
-
346
- const result = FileFinder.create({
347
- basePath: cwd,
348
- frecencyDbPath,
349
- historyDbPath,
350
- aiMode: true,
351
- enableHomeDirScanning: true,
352
- enableFsRootScanning,
353
- });
354
-
355
- if (!result.ok)
356
- throw new Error(`Failed to create FFF file finder: ${result.error}`);
357
-
358
- finder = result.value;
359
- finderCwd = cwd;
360
- await finder.waitForScan(15000);
361
- return finder;
362
- })().finally(() => {
363
- finderPromise = null;
364
- });
365
-
366
- return finderPromise;
367
- }
368
-
369
- function destroyFinder() {
370
- if (finder && !finder.isDestroyed) {
371
- finder.destroy();
372
- finder = null;
373
- finderCwd = null;
374
- }
375
- }
376
-
377
- async function getMentionItems(
378
- query: string,
379
- signal: AbortSignal,
380
- ): Promise<AutocompleteItem[]> {
381
- if (signal.aborted) return [];
382
- const f = await ensureFinder(activeCwd);
383
- if (signal.aborted) return [];
384
-
385
- const result = f.mixedSearch(query, { pageSize: MENTION_MAX_RESULTS });
386
- if (!result.ok) return [];
387
-
388
- return result.value.items.slice(0, MENTION_MAX_RESULTS).map((mixed: MixedItem) => {
389
- if (mixed.type === "directory") {
390
- return {
391
- value: buildAtCompletionValue(mixed.item.relativePath),
392
- label: mixed.item.dirName,
393
- description: mixed.item.relativePath,
394
- };
395
- }
396
- return {
397
- value: buildAtCompletionValue(mixed.item.relativePath),
398
- label: mixed.item.fileName,
399
- description: mixed.item.relativePath,
400
- };
401
- });
402
- }
403
-
404
- function registerAutocompleteProvider(ctx: {
405
- ui: {
406
- addAutocompleteProvider: (
407
- factory: (current: AutocompleteProvider) => AutocompleteProvider,
408
- ) => void;
409
- };
410
- }) {
411
- ctx.ui.addAutocompleteProvider((current) => {
412
- const mentionProvider = createFffMentionProvider(getMentionItems);
413
-
414
- return {
415
- async getSuggestions(lines, cursorLine, cursorCol, options) {
416
- if (shouldEnableMentions()) {
417
- try {
418
- const mentionResult = await mentionProvider.getSuggestions(
419
- lines,
420
- cursorLine,
421
- cursorCol,
422
- options,
423
- );
424
- if (mentionResult) return mentionResult;
425
- } catch {
426
- // Delegate when FFF lookup is unavailable.
427
- }
428
- }
429
-
430
- return current.getSuggestions(lines, cursorLine, cursorCol, options);
431
- },
432
- applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
433
- return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
434
- },
435
- shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
436
- return (
437
- current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true
438
- );
439
- },
440
- };
441
- });
442
- }
443
-
444
- // --- Flags / lifecycle ---
445
-
446
- dm.registerFlag("fff-mode", {
447
- description: "FFF mode: tools-and-ui | tools-only | override",
448
- type: "string",
449
- });
450
-
451
- dm.registerFlag("fff-frecency-db", {
452
- description: "Path to the frecency database (overrides FFF_FRECENCY_DB env)",
453
- type: "string",
454
- });
455
-
456
- dm.registerFlag("fff-history-db", {
457
- description: "Path to the query history database (overrides FFF_HISTORY_DB env)",
458
- type: "string",
459
- });
460
-
461
- dm.registerFlag("fff-enable-root-scan", {
462
- description:
463
- "Allow indexing when launched from the filesystem root (also: FFF_ENABLE_ROOT_SCAN env)",
464
- type: "boolean",
465
- });
466
-
467
- dm.on("session_start", async (_event, ctx) => {
468
- try {
469
- activeCwd = ctx.cwd;
470
-
471
- // Restore persisted mode from session entries. This handles session
472
- // resume after process restart where env vars are lost, and ensures
473
- // the env var is set for the next /reload in the same session.
474
- const entries = ctx.sessionManager?.getEntries();
475
- if (entries) {
476
- const modeEntry = [...entries]
477
- .reverse()
478
- .find(
479
- (e: { type: string; customType?: string }) =>
480
- e.type === "custom" && e.customType === "fff-mode",
481
- );
482
- if (
483
- modeEntry &&
484
- typeof (modeEntry as any).data?.mode === "string" &&
485
- VALID_MODES.includes((modeEntry as any).data.mode as FffMode)
486
- ) {
487
- const restored = (modeEntry as any).data.mode as FffMode;
488
- if (restored !== currentMode) {
489
- currentMode = restored;
490
- }
491
- }
492
- }
493
-
494
- registerAutocompleteProvider(ctx);
495
- await ensureFinder(activeCwd);
496
- } catch (e: unknown) {
497
- ctx.ui.notify(
498
- `FFF init failed: ${e instanceof Error ? e.message : String(e)}`,
499
- "error",
500
- );
501
- }
502
- });
503
-
504
- dm.on("session_shutdown", async () => {
505
- destroyFinder();
506
- });
507
-
508
- // --- Shared render helpers ---
509
-
510
- const renderTextResult = (
511
- result: { content?: { type: string; text?: string }[] },
512
- options: { expanded?: boolean },
513
- theme: any,
514
- context: any,
515
- maxLines = 15,
516
- ) => {
517
- const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
518
- const output = result.content?.find((c) => c.type === "text")?.text?.trim() ?? "";
519
- if (!output) {
520
- text.setText(theme.fg("muted", "No output"));
521
- return text;
522
- }
523
-
524
- const lines = output.split("\n");
525
- const displayLines = lines.slice(0, options.expanded ? lines.length : maxLines);
526
- let content = `\n${displayLines.map((line: string) => theme.fg("toolOutput", line)).join("\n")}`;
527
- if (lines.length > displayLines.length) {
528
- content += theme.fg(
529
- "muted",
530
- `\n... (${lines.length - displayLines.length} more lines)`,
531
- );
532
- }
533
- text.setText(content);
534
- return text;
535
- };
536
-
537
- // --- grep tool ---
538
-
539
- const grepSchema = Type.Object({
540
- pattern: Type.String({
541
- description: "Search pattern (literal text or regex)",
542
- }),
543
- path: Type.Optional(
544
- Type.String({
545
- description:
546
- "Repo-relative path constraint. Directory prefix (src/ or src/foo/), bare filename with extension (main.rs), or glob (*.ts, src/**/*.cc, {src,lib}/**). Applied to the full repo-relative path.",
547
- }),
548
- ),
549
- exclude: Type.Optional(
550
- Type.Union([Type.String(), Type.Array(Type.String())], {
551
- description:
552
- "Exclude paths (comma/space-separated or array). Same syntax as path: directory prefix ('test/'), filename with extension ('config.json'), or glob ('*.min.js', '**/*.{rs,go}'). A leading '!' is optional and ignored — both 'test/' and '!test/' work. Example: 'test/,*.min.js,!vendor/'.",
553
- }),
554
- ),
555
- caseSensitive: Type.Optional(
556
- Type.Boolean({
557
- description:
558
- "Force case-sensitive matching. Default uses smart-case (case-insensitive when pattern is all lowercase).",
559
- }),
560
- ),
561
- context: Type.Optional(
562
- Type.Number({ description: "Context lines before+after each match" }),
563
- ),
564
- limit: Type.Optional(
565
- Type.Number({
566
- description: `Max matches (default ${DEFAULT_GREP_LIMIT})`,
567
- }),
568
- ),
569
- cursor: Type.Optional(
570
- Type.String({ description: "Pagination cursor from previous result" }),
571
- ),
572
- });
573
-
574
- dm.registerTool({
575
- name: toolNames.grep,
576
- label: toolNames.grep,
577
- description: `Grep file contents. Smart-case, auto-detects regex vs literal, git-aware. Results are ranked by frecency (most-accessed files first); matches within a file stay in source order. Default limit ${DEFAULT_GREP_LIMIT}.`,
578
- promptSnippet: "Grep contents",
579
- promptGuidelines: [
580
- "Prefer bare identifiers as patterns. Literal queries are most efficient.",
581
- "Use path for include ('src/', '*.ts') and exclude for noise ('test/,*.min.js').",
582
- "caseSensitive: true when you need exact case (smart-case otherwise).",
583
- "After 1-2 greps, read the top match instead of more greps.",
584
- ],
585
- parameters: grepSchema,
586
-
587
- async execute(_toolCallId, params, signal) {
588
- if (signal?.aborted) throw new Error("Operation aborted");
589
-
590
- const f = await ensureFinder(activeCwd);
591
- const effectiveLimit = Math.max(1, params.limit ?? DEFAULT_GREP_LIMIT);
592
- const query = buildQuery(params.path, params.pattern, params.exclude, activeCwd);
593
- // Auto-detect: regex if the pattern has regex metacharacters AND parses
594
- // as a valid regex, otherwise plain literal. The fuzzy fallback below
595
- // only kicks in for plain mode — regex queries are intentional.
596
- const hasRegexSyntax =
597
- params.pattern !== params.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
598
- let mode: GrepMode = hasRegexSyntax ? "regex" : "plain";
599
- if (mode === "regex") {
600
- try {
601
- new RegExp(params.pattern);
602
- } catch {
603
- mode = "plain";
604
- }
605
- }
606
-
607
- // Guard: the agent keeps calling grep with '.*' or similar wildcard-only regex
608
- // to try to read a whole file. That's not what grep is for — return a terse error
609
- // steering them to a real pattern, preventing dozens of wasted retries.
610
- const p = params.pattern.trim();
611
- const isWildcardOnly =
612
- hasRegexSyntax &&
613
- /^(?:[.^$]*(?:[.][*+?]|\*|\+)[.^$]*|[.^$\s]*|\.\*\??|\.\*[+?]?|\.\+\??|\.|\*|\?)$/.test(
614
- p,
615
- );
616
-
617
- if (isWildcardOnly) {
618
- return {
619
- content: [
620
- {
621
- type: "text",
622
- text: `Pattern '${params.pattern}' matches everything — grep needs a concrete substring or identifier. Example: \`pattern: 'MyClass'\` or \`pattern: 'export function'\`.`,
623
- },
624
- ],
625
- details: { totalMatched: 0, totalFiles: 0 },
626
- };
627
- }
628
-
629
- // caseSensitive override flips smartCase off; omitting it keeps smart-case
630
- // (case-insensitive when pattern is all lowercase).
631
- const smartCase = params.caseSensitive !== true;
632
-
633
- const grepResult = f.grep(query, {
634
- mode,
635
- smartCase,
636
- maxMatchesPerFile: Math.min(effectiveLimit, 50),
637
- cursor: (params.cursor ? getCursor(params.cursor) : null) ?? null,
638
- beforeContext: params.context ?? 0,
639
- afterContext: params.context ?? 0,
640
- classifyDefinitions: true,
641
- });
642
-
643
- if (!grepResult.ok) throw new Error(grepResult.error);
644
-
645
- let result = grepResult.value;
646
- let fuzzyNotice: string | null = null;
647
-
648
- // automatic fuzzy fallback allows to broad the queries and find different cases
649
- if (result.items.length === 0 && !params.cursor && mode !== "regex") {
650
- const fuzzy = f.grep(params.pattern, {
651
- mode: "fuzzy",
652
- smartCase,
653
- maxMatchesPerFile: Math.min(effectiveLimit, 50),
654
- cursor: null,
655
- beforeContext: 0,
656
- afterContext: 0,
657
- classifyDefinitions: true,
658
- });
659
-
660
- if (fuzzy.ok && fuzzy.value.items.length > 0) {
661
- fuzzyNotice = `0 exact matches. Maybe you meant this?`;
662
- result = fuzzy.value;
663
- }
664
- }
665
-
666
- let output = formatGrepOutput(result);
667
- const notices: string[] = [];
668
- if (result.regexFallbackError) {
669
- notices.push(`Invalid regex: ${result.regexFallbackError}, used literal match`);
670
- }
671
- if (result.nextCursor) {
672
- notices.push(`Continue with cursor="${storeCursor(result.nextCursor)}"`);
673
- }
674
-
675
- if (notices.length > 0) output += `\n\n[${notices.join(". ")}]`;
676
- if (fuzzyNotice) output = `[${fuzzyNotice}]\n${output}`;
677
-
678
- return {
679
- content: [{ type: "text", text: output }],
680
- details: {
681
- totalMatched: result.totalMatched,
682
- totalFiles: result.totalFiles,
683
- },
684
- };
685
- },
686
-
687
- renderCall(args, theme, context) {
688
- const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
689
- const pattern = args?.pattern ?? "";
690
- const path = args?.path ?? ".";
691
- let content =
692
- theme.fg("toolTitle", theme.bold(toolNames.grep)) +
693
- " " +
694
- theme.fg("accent", `/${pattern}/`) +
695
- theme.fg("toolOutput", ` in ${path}`);
696
- if (args?.limit !== undefined)
697
- content += theme.fg("toolOutput", ` limit ${args.limit}`);
698
- if (args?.cursor) content += theme.fg("muted", ` (page)`);
699
- text.setText(content);
700
- return text;
701
- },
702
-
703
- renderResult(result, options, theme, context) {
704
- return renderTextResult(result, options, theme, context, 15);
705
- },
706
- });
707
-
708
- // --- find tool ---
709
-
710
- const findSchema = Type.Object({
711
- pattern: Type.String({
712
- description:
713
- "Fuzzy filename search and glob search. Frecency-ranked, git-aware. Multi-word = narrower (AND) not bound to order, use for multi word related concept search. Prefer this over ls/find/bash as the first exploration step whenever the user names a concept, feature, or symbol — it surfaces the relevant files in one call. Only use ls/read on a directory when you specifically need the alphabetical layout of an unknown repo, or when a concept search returned nothing.",
714
- }),
715
- path: Type.Optional(
716
- Type.String({
717
- description:
718
- "Repo-relative path constraint. Directory prefix (src/ or src/foo/), bare filename with extension (main.rs), or glob (*.ts, src/**/*.cc, {src,lib}/**). Applied to the full repo-relative path.",
719
- }),
720
- ),
721
- exclude: Type.Optional(
722
- Type.Union([Type.String(), Type.Array(Type.String())], {
723
- description:
724
- "Exclude paths (comma/space-separated or array). Same syntax as path: directory prefix ('test/'), filename with extension ('config.json'), or glob ('*.min.js', '**/*.{rs,go}'). A leading '!' is optional and ignored — both 'test/' and '!test/' work. Example: 'test/,*.min.js,!vendor/'.",
725
- }),
726
- ),
727
- limit: Type.Optional(
728
- Type.Number({
729
- description: `Max results per page (default ${DEFAULT_FIND_LIMIT})`,
730
- }),
731
- ),
732
- cursor: Type.Optional(
733
- Type.String({ description: "Pagination cursor from previous result" }),
734
- ),
735
- });
736
-
737
- dm.registerTool({
738
- name: toolNames.find,
739
- label: toolNames.find,
740
- description: `Fuzzy path search and glob search. Matches against the whole repo-relative path, not just the filename. Frecency-ranked, git-aware. Multi-word = narrower (AND). Default limit ${DEFAULT_FIND_LIMIT}.`,
741
- promptSnippet: "Find files by path or glob",
742
- promptGuidelines: [
743
- "Matches the WHOLE path, not just the filename — `profile` hits `chrome/browser/profiles/x.cc` too.",
744
- "Keep queries to 1-2 terms; extra words narrow.",
745
- "Use for paths, not content. Use grep for content.",
746
- "For exact path matches use a glob in `path` — e.g. path: '**/profile.h' for exact filename, or path: 'src/**/profile.h' scoped to a subtree. Bare patterns are fuzzy.",
747
- "To list everything inside a directory, pass path: 'dir/**' with an empty or wildcard pattern instead of using pattern alone.",
748
- "Use exclude: 'test/,*.min.js' to cut noise in large repos.",
749
- ],
750
- parameters: findSchema,
751
-
752
- async execute(_toolCallId, params, signal) {
753
- if (signal?.aborted) throw new Error("Operation aborted");
754
-
755
- const f = await ensureFinder(activeCwd);
756
-
757
- // Resume from a prior cursor if supplied — cursor owns query+pageSize so
758
- // the agent can't accidentally mix patterns across pages.
759
- const resumed = params.cursor ? getFindCursor(params.cursor) : undefined;
760
- const effectiveLimit = resumed
761
- ? resumed.pageSize
762
- : Math.max(1, params.limit ?? DEFAULT_FIND_LIMIT);
763
- const query = resumed
764
- ? resumed.query
765
- : buildQuery(params.path, params.pattern, params.exclude, activeCwd);
766
- const pattern = resumed ? resumed.pattern : params.pattern;
767
- const pageIndex = resumed?.nextPageIndex ?? 0;
768
-
769
- const searchResult = f.fileSearch(query, {
770
- pageIndex,
771
- pageSize: effectiveLimit,
772
- });
773
- if (!searchResult.ok) throw new Error(searchResult.error);
774
-
775
- const result = searchResult.value;
776
- const formatted = formatFindOutput(result, effectiveLimit, pattern);
777
- let output = formatted.output;
778
-
779
- // Infer hasMore: native fileSearch fills pageSize when more results
780
- // exist, so if we got a full page AND totalMatched exceeds what we've
781
- // shown so far there's another page to fetch.
782
- const shownSoFar = pageIndex * effectiveLimit + result.items.length;
783
- const hasMore =
784
- result.items.length >= effectiveLimit && result.totalMatched > shownSoFar;
785
-
786
- const notices: string[] = [];
787
- if (formatted.weak && formatted.shownCount > 0)
788
- notices.push(
789
- `Query "${pattern}" produced only weak scattered fuzzy matches. Output capped at ${formatted.shownCount}/${result.totalMatched}.`,
790
- );
791
-
792
- if (!formatted.weak && hasMore) {
793
- const remaining = result.totalMatched - shownSoFar;
794
- const cursorId = storeFindCursor({
795
- query,
796
- pattern,
797
- pageSize: effectiveLimit,
798
- nextPageIndex: pageIndex + 1,
799
- });
800
- notices.push(
801
- `${remaining} more match${remaining === 1 ? "" : "es"} available. cursor="${cursorId}" to continue`,
802
- );
803
- }
804
-
805
- if (notices.length > 0) output += `\n\n[${notices.join(". ")}]`;
806
- return {
807
- content: [{ type: "text", text: output }],
808
- details: {
809
- totalMatched: result.totalMatched,
810
- totalFiles: result.totalFiles,
811
- pageIndex,
812
- hasMore,
813
- },
814
- };
815
- },
816
-
817
- renderCall(args, theme, context) {
818
- const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
819
- const pattern = args?.pattern ?? "";
820
- const path = args?.path ?? ".";
821
- let content =
822
- theme.fg("toolTitle", theme.bold(toolNames.find)) +
823
- " " +
824
- theme.fg("accent", pattern) +
825
- theme.fg("toolOutput", ` in ${path}`);
826
- if (args?.limit !== undefined)
827
- content += theme.fg("toolOutput", ` (limit ${args.limit})`);
828
- if (args?.cursor) content += theme.fg("muted", ` (page)`);
829
- text.setText(content);
830
- return text;
831
- },
832
-
833
- renderResult(result, options, theme, context) {
834
- return renderTextResult(result, options, theme, context, 20);
835
- },
836
- });
837
-
838
- // --- multi_grep tool ---
839
- // My latest tests are showing that the multi grep tool is only harmful, trying to get rid of it
840
- const enableMultiGrep = process.env.DM_FFF_MULTIGREP === "1";
841
-
842
- if (enableMultiGrep) {
843
- const multiGrepSchema = Type.Object({
844
- patterns: Type.Array(Type.String(), {
845
- description:
846
- "Literal patterns (OR). Include snake_case/camelCase/PascalCase variants.",
847
- }),
848
- constraints: Type.Optional(
849
- Type.String({ description: "File filter, e.g. '*.{ts,tsx} !test/'" }),
850
- ),
851
- context: Type.Optional(Type.Number({ description: "Context lines before+after" })),
852
- limit: Type.Optional(
853
- Type.Number({
854
- description: `Max matches (default ${DEFAULT_GREP_LIMIT})`,
855
- }),
856
- ),
857
- cursor: Type.Optional(Type.String({ description: "Pagination cursor" })),
858
- });
859
-
860
- dm.registerTool({
861
- name: toolNames.multiGrep,
862
- label: toolNames.multiGrep,
863
- description:
864
- "Search file contents for ANY of multiple literal patterns (OR, SIMD Aho-Corasick). Faster than regex alternation.",
865
- promptSnippet: "Multi-pattern OR content search",
866
- promptGuidelines: [
867
- "Use when searching for several identifiers at once.",
868
- "Include all naming-convention variants (snake/camel/Pascal).",
869
- "Patterns are literal. Use constraints for file filters.",
870
- ],
871
- parameters: multiGrepSchema,
872
-
873
- async execute(_toolCallId, params, signal) {
874
- if (signal?.aborted) throw new Error("Operation aborted");
875
- if (!params.patterns?.length)
876
- throw new Error("patterns array must have at least 1 element");
877
-
878
- const f = await ensureFinder(activeCwd);
879
- const effectiveLimit = Math.max(1, params.limit ?? DEFAULT_GREP_LIMIT);
880
-
881
- const grepResult = f.multiGrep({
882
- patterns: params.patterns,
883
- constraints: params.constraints,
884
- maxMatchesPerFile: Math.min(effectiveLimit, 50),
885
- smartCase: true,
886
- cursor: (params.cursor ? getCursor(params.cursor) : null) ?? null,
887
- beforeContext: params.context ?? 0,
888
- afterContext: params.context ?? 0,
889
- });
890
-
891
- if (!grepResult.ok) throw new Error(grepResult.error);
892
-
893
- const result = grepResult.value;
894
- let output = formatGrepOutput(result);
895
-
896
- const notices: string[] = [];
897
- if (result.items.length >= effectiveLimit)
898
- notices.push(`${effectiveLimit}+ matches (refine patterns)`);
899
- if (result.nextCursor)
900
- notices.push(
901
- `More available. cursor="${storeCursor(result.nextCursor)}" to continue`,
902
- );
903
-
904
- if (notices.length > 0) output += `\n\n[${notices.join(". ")}]`;
905
-
906
- return {
907
- content: [{ type: "text", text: output }],
908
- details: {
909
- totalMatched: result.totalMatched,
910
- totalFiles: result.totalFiles,
911
- patterns: params.patterns,
912
- },
913
- };
914
- },
915
-
916
- renderCall(args, theme, context) {
917
- const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
918
- const patterns = args?.patterns ?? [];
919
- const constraints = args?.constraints;
920
- let content =
921
- theme.fg("toolTitle", theme.bold(toolNames.multiGrep)) +
922
- " " +
923
- theme.fg("accent", patterns.map((p: string) => `"${p}"`).join(", "));
924
- if (constraints) content += theme.fg("toolOutput", ` (${constraints})`);
925
- if (args?.cursor) content += theme.fg("muted", ` (page)`);
926
- text.setText(content);
927
- return text;
928
- },
929
-
930
- renderResult(result, options, theme, context) {
931
- return renderTextResult(result, options, theme, context, 15);
932
- },
933
- });
934
- } // end if (enableMultiGrep)
935
-
936
- // --- commands ---
937
-
938
- dm.registerCommand("fff-mode", {
939
- description: "Show or set FFF mode: /fff-mode [tools-and-ui | tools-only | override]",
940
- handler: async (args, ctx) => {
941
- const arg = (args || "").trim();
942
-
943
- // No args - show current mode
944
- if (!arg) {
945
- const mode = getMode();
946
- const flag = dm.getFlag("fff-mode") ?? "unset";
947
- ctx.ui.notify(`Current mode: '${mode}' (flag: ${flag})`, "info");
948
- return;
949
- }
950
-
951
- // Validate and set mode
952
- if (!VALID_MODES.includes(arg as FffMode)) {
953
- ctx.ui.notify(`Usage: /fff-mode [${VALID_MODES.join(" | ")}]`, "warning");
954
- return;
955
- }
956
-
957
- const newMode = arg as FffMode;
958
- const oldMode = getMode();
959
- setMode(newMode);
960
-
961
- dm.appendEntry("fff-mode", { mode: newMode });
962
-
963
- const note =
964
- (oldMode === "override") !== (newMode === "override")
965
- ? " (tool name change requires /reload)"
966
- : "";
967
- ctx.ui.notify(`Mode changed: '${oldMode}' → '${newMode}'${note}`, "info");
968
- },
969
- });
970
-
971
- dm.registerCommand("fff-health", {
972
- description: "Show FFF file finder health and status",
973
- handler: async (_args, ctx) => {
974
- if (!finder || finder.isDestroyed) {
975
- ctx.ui.notify("FFF not initialized", "warning");
976
- return;
977
- }
978
-
979
- const health = finder.healthCheck();
980
- if (!health.ok) {
981
- ctx.ui.notify(`Health check failed: ${health.error}`, "error");
982
- return;
983
- }
984
-
985
- const h = health.value;
986
- const lines = [
987
- `FFF v${h.version}`,
988
- `Mode: ${getMode()}`,
989
- `Git: ${h.git.repositoryFound ? `yes (${h.git.workdir ?? "unknown"})` : "no"}`,
990
- `Picker: ${h.filePicker.initialized ? `${h.filePicker.indexedFiles ?? 0} files` : "not initialized"}`,
991
- `Frecency: ${h.frecency.initialized ? "active" : "disabled"}`,
992
- `Query tracker: ${h.queryTracker.initialized ? "active" : "disabled"}`,
993
- ];
994
-
995
- const progress = finder.getScanProgress();
996
- if (progress.ok) {
997
- lines.push(
998
- `Scanning: ${progress.value.isScanning ? "yes" : "no"} (${progress.value.scannedFilesCount} files)`,
999
- );
1000
- }
1001
-
1002
- ctx.ui.notify(lines.join("\n"), "info");
1003
- },
1004
- });
1005
-
1006
- dm.registerCommand("fff-rescan", {
1007
- description: "Trigger FFF to rescan files",
1008
- handler: async (_args, ctx) => {
1009
- if (!finder || finder.isDestroyed) {
1010
- ctx.ui.notify("FFF not initialized", "warning");
1011
- return;
1012
- }
1013
-
1014
- const result = finder.scanFiles();
1015
- if (!result.ok) {
1016
- ctx.ui.notify(`Rescan failed: ${result.error}`, "error");
1017
- return;
1018
- }
1019
-
1020
- ctx.ui.notify("FFF rescan triggered", "info");
1021
- },
1022
- });
1023
- }