@aria-cli/tools 1.0.9 → 1.0.11

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 (241) hide show
  1. package/package.json +9 -5
  2. package/src/__tests__/web-fetch-download.test.ts +0 -433
  3. package/src/__tests__/web-tools.test.ts +0 -619
  4. package/src/ask-user-interaction.ts +0 -33
  5. package/src/cache/web-cache.ts +0 -110
  6. package/src/definitions/arion.ts +0 -118
  7. package/src/definitions/browser/browser.ts +0 -502
  8. package/src/definitions/browser/index.ts +0 -5
  9. package/src/definitions/browser/pw-downloads.ts +0 -142
  10. package/src/definitions/browser/pw-interactions.ts +0 -282
  11. package/src/definitions/browser/pw-responses.ts +0 -98
  12. package/src/definitions/browser/pw-session.ts +0 -405
  13. package/src/definitions/browser/pw-shared.ts +0 -85
  14. package/src/definitions/browser/pw-snapshot.ts +0 -383
  15. package/src/definitions/browser/pw-state.ts +0 -101
  16. package/src/definitions/browser/types.ts +0 -203
  17. package/src/definitions/code-intelligence.ts +0 -526
  18. package/src/definitions/core.ts +0 -118
  19. package/src/definitions/delegation.ts +0 -567
  20. package/src/definitions/deploy.ts +0 -73
  21. package/src/definitions/filesystem.ts +0 -217
  22. package/src/definitions/frg.ts +0 -67
  23. package/src/definitions/index.ts +0 -28
  24. package/src/definitions/memory.ts +0 -150
  25. package/src/definitions/messaging.ts +0 -734
  26. package/src/definitions/meta.ts +0 -392
  27. package/src/definitions/network.ts +0 -179
  28. package/src/definitions/outlook.ts +0 -318
  29. package/src/definitions/patch/apply-patch.ts +0 -235
  30. package/src/definitions/patch/fuzzy-match.ts +0 -217
  31. package/src/definitions/patch/index.ts +0 -1
  32. package/src/definitions/patch/patch-parser.ts +0 -297
  33. package/src/definitions/patch/sandbox-paths.ts +0 -129
  34. package/src/definitions/process/index.ts +0 -5
  35. package/src/definitions/process/process-registry.ts +0 -303
  36. package/src/definitions/process/process.ts +0 -456
  37. package/src/definitions/process/pty-keys.ts +0 -298
  38. package/src/definitions/process/session-slug.ts +0 -147
  39. package/src/definitions/quip.ts +0 -225
  40. package/src/definitions/search.ts +0 -67
  41. package/src/definitions/session-history.ts +0 -79
  42. package/src/definitions/shell.ts +0 -202
  43. package/src/definitions/slack.ts +0 -211
  44. package/src/definitions/web.ts +0 -119
  45. package/src/executors/apply-patch.ts +0 -1035
  46. package/src/executors/arion.ts +0 -199
  47. package/src/executors/code-intelligence.ts +0 -1179
  48. package/src/executors/deploy.ts +0 -1066
  49. package/src/executors/filesystem.ts +0 -1428
  50. package/src/executors/frg-freshness.ts +0 -743
  51. package/src/executors/frg.ts +0 -394
  52. package/src/executors/index.ts +0 -280
  53. package/src/executors/learning-meta.ts +0 -1367
  54. package/src/executors/lsp-client.ts +0 -355
  55. package/src/executors/memory.ts +0 -978
  56. package/src/executors/meta.ts +0 -293
  57. package/src/executors/process-registry.ts +0 -570
  58. package/src/executors/pty-session-store.ts +0 -43
  59. package/src/executors/pty.ts +0 -342
  60. package/src/executors/restart.ts +0 -133
  61. package/src/executors/search-freshness.ts +0 -249
  62. package/src/executors/search-types.ts +0 -98
  63. package/src/executors/search.ts +0 -89
  64. package/src/executors/self-diagnose.ts +0 -552
  65. package/src/executors/session-history.ts +0 -435
  66. package/src/executors/shell-safety.ts +0 -519
  67. package/src/executors/shell.ts +0 -1243
  68. package/src/executors/utils.ts +0 -40
  69. package/src/executors/web.ts +0 -786
  70. package/src/extraction/content-extraction.ts +0 -281
  71. package/src/extraction/index.ts +0 -5
  72. package/src/headless-control-contract.ts +0 -1149
  73. package/src/index.ts +0 -788
  74. package/src/local-control-http-auth.ts +0 -2
  75. package/src/mcp/client.ts +0 -218
  76. package/src/mcp/connection.ts +0 -568
  77. package/src/mcp/index.ts +0 -11
  78. package/src/mcp/jsonrpc.ts +0 -195
  79. package/src/mcp/types.ts +0 -199
  80. package/src/network-control-adapter.ts +0 -88
  81. package/src/network-runtime/address-types.ts +0 -218
  82. package/src/network-runtime/db-owner-fencing.ts +0 -91
  83. package/src/network-runtime/delivery-receipts.ts +0 -372
  84. package/src/network-runtime/direct-endpoint-authority.ts +0 -35
  85. package/src/network-runtime/index.ts +0 -316
  86. package/src/network-runtime/local-control-contract.ts +0 -784
  87. package/src/network-runtime/node-store-contract.ts +0 -46
  88. package/src/network-runtime/pair-route-contract.ts +0 -97
  89. package/src/network-runtime/peer-capabilities.ts +0 -48
  90. package/src/network-runtime/peer-principal-ref.ts +0 -20
  91. package/src/network-runtime/peer-state-machine.ts +0 -160
  92. package/src/network-runtime/protocol-schemas.ts +0 -265
  93. package/src/network-runtime/runtime-bootstrap-contract.ts +0 -83
  94. package/src/outlook/desktop-session.ts +0 -409
  95. package/src/policy.ts +0 -171
  96. package/src/providers/brave.ts +0 -80
  97. package/src/providers/duckduckgo.ts +0 -199
  98. package/src/providers/exa.ts +0 -85
  99. package/src/providers/firecrawl.ts +0 -77
  100. package/src/providers/index.ts +0 -8
  101. package/src/providers/jina.ts +0 -70
  102. package/src/providers/router.ts +0 -121
  103. package/src/providers/search-provider.ts +0 -74
  104. package/src/providers/tavily.ts +0 -74
  105. package/src/quip/desktop-session.ts +0 -435
  106. package/src/registry/index.ts +0 -1
  107. package/src/registry/registry.ts +0 -905
  108. package/src/runtime-socket-local-control-client.ts +0 -632
  109. package/src/security/dns-normalization.ts +0 -34
  110. package/src/security/dns-pinning.ts +0 -138
  111. package/src/security/external-content.ts +0 -129
  112. package/src/security/ssrf.ts +0 -207
  113. package/src/slack/desktop-session.ts +0 -493
  114. package/src/tool-factory.ts +0 -91
  115. package/src/types.ts +0 -1341
  116. package/src/utils/retry.ts +0 -163
  117. package/src/utils/safe-parse-json.ts +0 -176
  118. package/src/utils/url.ts +0 -20
  119. package/tests/benchmarks/registry.bench.ts +0 -57
  120. package/tests/cache/web-cache.test.ts +0 -147
  121. package/tests/critical-integration.test.ts +0 -1465
  122. package/tests/definitions/apply-patch.test.ts +0 -586
  123. package/tests/definitions/browser.test.ts +0 -495
  124. package/tests/definitions/delegation-pause-resume.test.ts +0 -758
  125. package/tests/definitions/execution.test.ts +0 -671
  126. package/tests/definitions/messaging-inbox-scope.test.ts +0 -229
  127. package/tests/definitions/messaging.test.ts +0 -1468
  128. package/tests/definitions/outlook.test.ts +0 -30
  129. package/tests/definitions/process.test.ts +0 -469
  130. package/tests/definitions/slack.test.ts +0 -28
  131. package/tests/definitions/tool-inventory.test.ts +0 -218
  132. package/tests/e2e/delegation-quest-orchestration.e2e.test.ts +0 -433
  133. package/tests/e2e/memory-tool-discovery-contract.e2e.test.ts +0 -81
  134. package/tests/executors/apply-patch.test.ts +0 -538
  135. package/tests/executors/arion.test.ts +0 -309
  136. package/tests/executors/conversation-primitives.test.ts +0 -250
  137. package/tests/executors/deploy.test.ts +0 -746
  138. package/tests/executors/filesystem-tools.test.ts +0 -357
  139. package/tests/executors/filesystem.test.ts +0 -959
  140. package/tests/executors/frg-freshness.test.ts +0 -136
  141. package/tests/executors/frg-merge.test.ts +0 -70
  142. package/tests/executors/frg-session-content.test.ts +0 -40
  143. package/tests/executors/frg.test.ts +0 -56
  144. package/tests/executors/memory-bugfixes.test.ts +0 -257
  145. package/tests/executors/memory-real-memoria.integration.test.ts +0 -316
  146. package/tests/executors/memory.test.ts +0 -853
  147. package/tests/executors/meta-tools.test.ts +0 -411
  148. package/tests/executors/meta.test.ts +0 -683
  149. package/tests/executors/path-containment.test.ts +0 -51
  150. package/tests/executors/process-registry.test.ts +0 -505
  151. package/tests/executors/pty.test.ts +0 -664
  152. package/tests/executors/quest-security.test.ts +0 -249
  153. package/tests/executors/read-file-media.test.ts +0 -230
  154. package/tests/executors/recall-knowledge-schema.test.ts +0 -209
  155. package/tests/executors/recall-tags.test.ts +0 -278
  156. package/tests/executors/remember-null-safety.contract.test.ts +0 -41
  157. package/tests/executors/restart.test.ts +0 -67
  158. package/tests/executors/search-unified.test.ts +0 -381
  159. package/tests/executors/session-history.test.ts +0 -340
  160. package/tests/executors/session-transcript.test.ts +0 -561
  161. package/tests/executors/shell-abort.test.ts +0 -416
  162. package/tests/executors/shell-env-blocklist.test.ts +0 -648
  163. package/tests/executors/shell-env-process.test.ts +0 -245
  164. package/tests/executors/shell-process-registry.test.ts +0 -334
  165. package/tests/executors/shell-tools.test.ts +0 -393
  166. package/tests/executors/shell.test.ts +0 -690
  167. package/tests/executors/web-abort-vs-timeout.test.ts +0 -213
  168. package/tests/executors/web-integration.test.ts +0 -633
  169. package/tests/executors/web-symlink.test.ts +0 -18
  170. package/tests/executors/web.test.ts +0 -1400
  171. package/tests/executors/write-stdin.test.ts +0 -145
  172. package/tests/extraction/content-extraction.test.ts +0 -153
  173. package/tests/guards/tools-default-test-lane.integration.test.ts +0 -21
  174. package/tests/guards/tools-package-test-commands.e2e.test.ts +0 -43
  175. package/tests/guards/tools-test-lane-manifest.contract.test.ts +0 -76
  176. package/tests/guards/tools-vitest-workspace-alias.contract.test.ts +0 -63
  177. package/tests/helpers/async-waits.ts +0 -53
  178. package/tests/integration/headless-control-contract.integration.test.ts +0 -153
  179. package/tests/integration/memory-tool-schema-parity.integration.test.ts +0 -67
  180. package/tests/integration/meta-tools-round-trip.integration.test.ts +0 -506
  181. package/tests/integration/quest-round-trip.test.ts +0 -303
  182. package/tests/integration/registry-executor-flow.test.ts +0 -85
  183. package/tests/integration.test.ts +0 -177
  184. package/tests/loading-tier.test.ts +0 -126
  185. package/tests/mcp/client-reconnect.test.ts +0 -267
  186. package/tests/mcp/connection.test.ts +0 -846
  187. package/tests/mcp/injectable-logger.test.ts +0 -83
  188. package/tests/mcp/jsonrpc.test.ts +0 -109
  189. package/tests/mcp/lifecycle.test.ts +0 -879
  190. package/tests/network-runtime/address-types.contract.test.ts +0 -143
  191. package/tests/network-runtime/continuity-bind-schema.contract.test.ts +0 -203
  192. package/tests/network-runtime/local-control-contract.test.ts +0 -869
  193. package/tests/network-runtime/local-control-invite-token.contract.test.ts +0 -146
  194. package/tests/network-runtime/node-store-contract.test.ts +0 -11
  195. package/tests/network-runtime/pair-protocol-nodeid.contract.test.ts +0 -15
  196. package/tests/network-runtime/peer-state-machine.contract.test.ts +0 -148
  197. package/tests/network-runtime/protocol-schemas.contract.test.ts +0 -512
  198. package/tests/network-runtime/relay-pending-nodeid.contract.test.ts +0 -62
  199. package/tests/network-runtime/runtime-bootstrap-contract.test.ts +0 -227
  200. package/tests/network-runtime/runtime-socket-local-control-client.test.ts +0 -621
  201. package/tests/network-runtime/wait-for-message-script.test.ts +0 -288
  202. package/tests/parallel.test.ts +0 -71
  203. package/tests/policy.test.ts +0 -184
  204. package/tests/print-default-test-lane.ts +0 -14
  205. package/tests/print-test-lane-manifest.ts +0 -22
  206. package/tests/providers/brave.test.ts +0 -159
  207. package/tests/providers/duckduckgo.test.ts +0 -207
  208. package/tests/providers/exa.test.ts +0 -175
  209. package/tests/providers/firecrawl.test.ts +0 -168
  210. package/tests/providers/jina.test.ts +0 -144
  211. package/tests/providers/router.test.ts +0 -328
  212. package/tests/providers/tavily.test.ts +0 -165
  213. package/tests/registry/discovery.test.ts +0 -154
  214. package/tests/registry/injectable-logger.test.ts +0 -230
  215. package/tests/registry/input-validation.test.ts +0 -361
  216. package/tests/registry/interface-completeness.test.ts +0 -85
  217. package/tests/registry/mcp-integration.test.ts +0 -103
  218. package/tests/registry/mcp-read-only-hint.test.ts +0 -60
  219. package/tests/registry/memoria-discovery.test.ts +0 -390
  220. package/tests/registry/nested-validation.test.ts +0 -283
  221. package/tests/registry/pseudo-tool-filtering.test.ts +0 -258
  222. package/tests/registry/registration-lifecycle.test.ts +0 -133
  223. package/tests/registry-validation.test.ts +0 -424
  224. package/tests/registry.test.ts +0 -460
  225. package/tests/security/dns-pinning.test.ts +0 -162
  226. package/tests/security/external-content.test.ts +0 -144
  227. package/tests/security/ssrf.test.ts +0 -118
  228. package/tests/shell-safety-integration.test.ts +0 -32
  229. package/tests/shell-safety.test.ts +0 -365
  230. package/tests/slack/desktop-session.test.ts +0 -50
  231. package/tests/test-lane-manifest.ts +0 -440
  232. package/tests/test-utils.ts +0 -27
  233. package/tests/tool-factory.test.ts +0 -188
  234. package/tests/utils/retry.test.ts +0 -231
  235. package/tests/utils/url.test.ts +0 -63
  236. package/tsconfig.cjs.json +0 -24
  237. package/tsconfig.json +0 -12
  238. package/vitest.config.ts +0 -55
  239. package/vitest.e2e.config.ts +0 -24
  240. package/vitest.integration.config.ts +0 -24
  241. package/vitest.native.config.ts +0 -24
@@ -1,1179 +0,0 @@
1
- /**
2
- * @aria/tools - Code intelligence executors
3
- *
4
- * 7 native tools wrapping external CLI binaries:
5
- * rg (ripgrep), ug (ugrep), probe, sg (ast-grep),
6
- * cbm (codebase-memory-mcp), serena, fff
7
- */
8
-
9
- import { execFile, spawn as cpSpawn } from "node:child_process";
10
- import { promisify } from "node:util";
11
- import { existsSync, readdirSync, statSync } from "node:fs";
12
- import { resolve as pathResolve, dirname, join as pathJoin } from "node:path";
13
- import { createConnection } from "node:net";
14
- import type { ToolContext, ToolResult } from "../types.js";
15
- import { success, fail } from "./utils.js";
16
-
17
- const execFileAsync = promisify(execFile);
18
-
19
- // ---------------------------------------------------------------------------
20
- // Shared helpers
21
- // ---------------------------------------------------------------------------
22
-
23
- const binaryCache = new Map<string, boolean>();
24
-
25
- async function hasBinary(name: string): Promise<boolean> {
26
- if (binaryCache.has(name)) return binaryCache.get(name)!;
27
- try {
28
- await execFileAsync("which", [name]);
29
- binaryCache.set(name, true);
30
- } catch {
31
- binaryCache.set(name, false);
32
- }
33
- return binaryCache.get(name)!;
34
- }
35
-
36
- async function shellExec(
37
- cmd: string,
38
- args: string[],
39
- opts: { cwd?: string; timeout?: number; signal?: AbortSignal },
40
- ): Promise<{ stdout: string; stderr: string }> {
41
- return execFileAsync(cmd, args, {
42
- cwd: opts.cwd,
43
- timeout: opts.timeout ?? 30_000,
44
- signal: opts.signal,
45
- maxBuffer: 10 * 1024 * 1024, // 10MB
46
- });
47
- }
48
-
49
- function pushIf(args: string[], condition: unknown, ...flags: string[]): void {
50
- if (condition) args.push(...flags);
51
- }
52
-
53
- function mergeExtraArgs(args: string[], extra?: string[]): void {
54
- if (extra?.length) args.push(...extra);
55
- }
56
-
57
- function escapeRegex(str: string): string {
58
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
59
- }
60
-
61
- interface ExecError {
62
- code?: number;
63
- stderr?: string;
64
- message?: string;
65
- }
66
-
67
- function asExecError(err: unknown): ExecError {
68
- if (err && typeof err === "object") return err as ExecError;
69
- return { message: String(err) };
70
- }
71
-
72
- // ---------------------------------------------------------------------------
73
- // Input types
74
- // ---------------------------------------------------------------------------
75
-
76
- export interface RgInput {
77
- pattern: string;
78
- path?: string;
79
- ignore_case?: boolean;
80
- smart_case?: boolean;
81
- fixed_strings?: boolean;
82
- word_regexp?: boolean;
83
- file_type?: string;
84
- glob?: string;
85
- context?: number;
86
- max_count?: number;
87
- invert?: boolean;
88
- files_only?: boolean;
89
- count?: boolean;
90
- extra_args?: string[];
91
- }
92
-
93
- export interface UgInput {
94
- pattern: string;
95
- path?: string;
96
- ignore_case?: boolean;
97
- smart_case?: boolean;
98
- fixed_strings?: boolean;
99
- word_regexp?: boolean;
100
- file_type?: string;
101
- glob?: string;
102
- context?: number;
103
- max_count?: number;
104
- fuzzy?: boolean | number;
105
- bool?: boolean;
106
- neg_pattern?: string;
107
- files_only?: boolean;
108
- count?: boolean;
109
- decompress?: boolean;
110
- extra_args?: string[];
111
- }
112
-
113
- export interface ProbeInput {
114
- command?: "search" | "extract" | "symbols" | "query";
115
- query?: string;
116
- path?: string;
117
- exact?: boolean;
118
- max_tokens?: number;
119
- max_results?: number;
120
- session?: string;
121
- language?: string;
122
- reranker?: string;
123
- allow_tests?: boolean;
124
- files?: string[];
125
- extra_args?: string[];
126
- }
127
-
128
- export interface SgInput {
129
- command?: "run" | "scan";
130
- pattern?: string;
131
- language?: string;
132
- rewrite?: string;
133
- strictness?: "cst" | "smart" | "ast" | "relaxed" | "signature";
134
- globs?: string;
135
- rule?: string;
136
- inline_rules?: string;
137
- path?: string;
138
- update_all?: boolean;
139
- context?: number;
140
- extra_args?: string[];
141
- }
142
-
143
- export interface CbmInput {
144
- action:
145
- | "index"
146
- | "search"
147
- | "trace"
148
- | "impact"
149
- | "context"
150
- | "snippet"
151
- | "code_search"
152
- | "architecture"
153
- | "schema"
154
- | "cypher"
155
- | "list_projects"
156
- | "delete_project"
157
- | "status";
158
- path?: string;
159
- mode?: "full" | "fast";
160
- name?: string;
161
- label?: string;
162
- file?: string;
163
- direction?: "inbound" | "outbound" | "both";
164
- depth?: number;
165
- edge_types?: string[];
166
- scope?: string;
167
- base_branch?: string;
168
- qualified_name?: string;
169
- include_neighbors?: boolean;
170
- code_pattern?: string;
171
- regex?: boolean;
172
- code_mode?: "compact" | "full" | "files";
173
- query?: string;
174
- max_rows?: number;
175
- project?: string;
176
- limit?: number;
177
- context?: number;
178
- }
179
-
180
- export interface LspInput {
181
- action: "definition" | "references" | "hover" | "symbols" | "rename";
182
- file: string;
183
- line?: number;
184
- character?: number;
185
- new_name?: string;
186
- }
187
-
188
- export interface SerenaInput {
189
- action:
190
- | "find_symbol"
191
- | "find_references"
192
- | "overview"
193
- | "replace_body"
194
- | "insert_after"
195
- | "insert_before"
196
- | "rename"
197
- | "search";
198
- name_path?: string;
199
- relative_path?: string;
200
- include_body?: boolean;
201
- include_info?: boolean;
202
- depth?: number;
203
- body?: string;
204
- new_name?: string;
205
- pattern?: string;
206
- context_before?: number;
207
- context_after?: number;
208
- paths_include?: string;
209
- paths_exclude?: string;
210
- extra_args?: Record<string, unknown>;
211
- }
212
-
213
- export interface FffInput {
214
- action: "grep" | "find_files" | "multi_grep";
215
- query?: string;
216
- patterns?: string[];
217
- constraints?: string;
218
- path?: string;
219
- }
220
-
221
- // ---------------------------------------------------------------------------
222
- // Output types
223
- // ---------------------------------------------------------------------------
224
-
225
- export interface RgMatch {
226
- file: string;
227
- line: number;
228
- text: string;
229
- submatches: string[];
230
- }
231
-
232
- // ---------------------------------------------------------------------------
233
- // 1. rg — ripgrep
234
- // ---------------------------------------------------------------------------
235
-
236
- export async function executeRg(input: RgInput, ctx: ToolContext): Promise<ToolResult> {
237
- if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
238
- if (!(await hasBinary("rg")))
239
- return fail("ripgrep (rg) not installed. Install: brew install ripgrep");
240
-
241
- // When count mode is active, rg -c outputs plain text (file:count) even with --json.
242
- // We omit --json and parse the plain-text output instead.
243
- const rgCountMode = !!input.count;
244
- const args = rgCountMode
245
- ? ["--line-number", "--color", "never"]
246
- : ["--json", "--line-number", "--color", "never"];
247
-
248
- pushIf(args, input.ignore_case, "-i");
249
- pushIf(args, input.smart_case, "-S");
250
- pushIf(args, input.fixed_strings, "-F");
251
- pushIf(args, input.word_regexp, "-w");
252
- pushIf(args, input.invert, "-v");
253
- pushIf(args, input.files_only, "-l");
254
- pushIf(args, input.count, "-c");
255
- if (input.file_type) args.push("-t", input.file_type);
256
- if (input.glob) args.push("-g", input.glob);
257
- if (input.context != null) args.push("-C", String(input.context));
258
- if (input.max_count != null) args.push("-m", String(input.max_count));
259
-
260
- mergeExtraArgs(args, input.extra_args);
261
- args.push("--", input.pattern);
262
- args.push(input.path ?? ctx.workingDir);
263
-
264
- try {
265
- const { stdout } = await shellExec("rg", args, {
266
- cwd: ctx.workingDir,
267
- signal: ctx.abortSignal,
268
- });
269
- if (rgCountMode) {
270
- const counts = parseRipgrepCount(stdout);
271
- const total = counts.reduce((s, c) => s + c.count, 0);
272
- return success(
273
- `Found ${total} matches across ${counts.length} files for "${input.pattern}"`,
274
- { counts, total },
275
- );
276
- }
277
- const matches = parseRipgrepJson(stdout);
278
- return success(`Found ${matches.length} matches for "${input.pattern}"`, { matches });
279
- } catch (err: unknown) {
280
- const e = asExecError(err);
281
- if (e.code === 1) return success("No matches found", { matches: [] });
282
- return fail(`rg failed: ${e.stderr || e.message}`);
283
- }
284
- }
285
-
286
- function parseRipgrepJson(stdout: string): RgMatch[] {
287
- const matches: RgMatch[] = [];
288
- for (const line of stdout.split("\n")) {
289
- if (!line.trim()) continue;
290
- try {
291
- const obj = JSON.parse(line);
292
- if (obj.type === "match") {
293
- matches.push({
294
- file: obj.data.path.text,
295
- line: obj.data.line_number,
296
- text: obj.data.lines.text.trimEnd(),
297
- submatches:
298
- obj.data.submatches?.map(
299
- (s: Record<string, unknown>) => (s.match as Record<string, unknown>)?.text,
300
- ) ?? [],
301
- });
302
- }
303
- } catch {
304
- // Skip malformed lines
305
- }
306
- }
307
- return matches;
308
- }
309
-
310
- /** Parse rg/ug plain-text count output: `file:count` per line.
311
- * Filters out files with 0 matches (ug -c outputs 0-count lines, rg doesn't). */
312
- function parseRipgrepCount(stdout: string): Array<{ file: string; count: number }> {
313
- const counts: Array<{ file: string; count: number }> = [];
314
- for (const line of stdout.split("\n")) {
315
- if (!line.trim()) continue;
316
- const lastColon = line.lastIndexOf(":");
317
- if (lastColon === -1) continue;
318
- const file = line.slice(0, lastColon);
319
- const count = parseInt(line.slice(lastColon + 1), 10);
320
- if (!isNaN(count) && count > 0) counts.push({ file, count });
321
- }
322
- return counts;
323
- }
324
-
325
- // ---------------------------------------------------------------------------
326
- // 2. ug — ugrep
327
- // ---------------------------------------------------------------------------
328
-
329
- export async function executeUg(input: UgInput, ctx: ToolContext): Promise<ToolResult> {
330
- if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
331
- if (!(await hasBinary("ug")))
332
- return fail("ugrep (ug) not installed. Install: brew install ugrep");
333
-
334
- // --ignore-files: respect .gitignore / .ignore (parity with rg default behaviour).
335
- // --ignore-binary: skip binary files (tar, images, etc.) — rg skips them by default.
336
- // Without these flags ug searches dist/, node_modules/, .tar archives, etc.
337
- const ugCountMode = !!input.count;
338
- const args = ugCountMode
339
- ? ["--line-number", "--color=never", "-r", "--ignore-files", "--ignore-binary"]
340
- : ["--json", "--line-number", "--color=never", "-r", "--ignore-files", "--ignore-binary"];
341
-
342
- pushIf(args, input.ignore_case, "-i");
343
- pushIf(args, input.smart_case, "-j");
344
- pushIf(args, input.fixed_strings, "-F");
345
- pushIf(args, input.word_regexp, "-w");
346
- pushIf(args, input.files_only, "-l");
347
- pushIf(args, input.count, "-c");
348
- pushIf(args, input.decompress, "-z");
349
- if (input.file_type) args.push("-t", input.file_type);
350
- if (input.glob) args.push("-g", input.glob);
351
- if (input.context != null) args.push("-C", String(input.context));
352
- if (input.max_count != null) args.push("-m", String(input.max_count));
353
- if (input.neg_pattern) args.push("-N", input.neg_pattern);
354
-
355
- // Fuzzy matching
356
- if (input.fuzzy === true) {
357
- args.push("-Z");
358
- } else if (typeof input.fuzzy === "number") {
359
- args.push(`-Z${input.fuzzy}`);
360
- }
361
-
362
- // Boolean query mode
363
- if (input.bool) args.push("-%%");
364
-
365
- mergeExtraArgs(args, input.extra_args);
366
- args.push("--", input.pattern);
367
- args.push(input.path ?? ctx.workingDir);
368
-
369
- try {
370
- const { stdout } = await shellExec("ug", args, {
371
- cwd: ctx.workingDir,
372
- signal: ctx.abortSignal,
373
- });
374
- if (ugCountMode) {
375
- const counts = parseRipgrepCount(stdout); // same file:count format
376
- const total = counts.reduce((s, c) => s + c.count, 0);
377
- return success(
378
- `Found ${total} matches across ${counts.length} files for "${input.pattern}"`,
379
- { counts, total },
380
- );
381
- }
382
- const matches = parseUgrepJson(stdout);
383
- return success(`Found ${matches.length} matches for "${input.pattern}"`, { matches });
384
- } catch (err: unknown) {
385
- const e = asExecError(err);
386
- if (e.code === 1) return success("No matches found", { matches: [] });
387
- return fail(`ug failed: ${e.stderr || e.message}`);
388
- }
389
- }
390
-
391
- function parseUgrepJson(stdout: string): RgMatch[] {
392
- // ugrep --json outputs: [{ file, matches: [{ line, match }] }]
393
- // This is a JSON array, NOT NDJSON like ripgrep
394
- const results: RgMatch[] = [];
395
- try {
396
- const parsed = JSON.parse(stdout) as Array<{
397
- file: string;
398
- matches: Array<{ line: number; match: string }>;
399
- }>;
400
- for (const fileGroup of parsed) {
401
- for (const m of fileGroup.matches) {
402
- results.push({
403
- file: fileGroup.file,
404
- line: m.line,
405
- text: m.match.trimEnd(),
406
- submatches: [],
407
- });
408
- }
409
- }
410
- } catch {
411
- // Fallback: try NDJSON parsing in case format varies
412
- for (const line of stdout.split("\n")) {
413
- if (!line.trim()) continue;
414
- try {
415
- const obj = JSON.parse(line);
416
- if (obj.file && obj.matches) {
417
- for (const m of obj.matches) {
418
- results.push({
419
- file: obj.file,
420
- line: m.line,
421
- text: m.match?.trimEnd() ?? "",
422
- submatches: [],
423
- });
424
- }
425
- }
426
- } catch {
427
- // Skip
428
- }
429
- }
430
- }
431
- return results;
432
- }
433
-
434
- // ---------------------------------------------------------------------------
435
- // 3. probe
436
- // ---------------------------------------------------------------------------
437
-
438
- export async function executeProbe(input: ProbeInput, ctx: ToolContext): Promise<ToolResult> {
439
- if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
440
- if (!(await hasBinary("probe")))
441
- return fail("probe not installed. Install: npm install -g @probelabs/probe");
442
-
443
- const cmd = input.command ?? "search";
444
- const args: string[] = [cmd];
445
-
446
- switch (cmd) {
447
- case "search": {
448
- if (!input.query) return fail("query required for search");
449
- pushIf(args, input.exact, "--exact");
450
- pushIf(args, input.allow_tests, "--allow-tests");
451
- if (input.max_tokens != null) args.push("--max-tokens", String(input.max_tokens));
452
- if (input.max_results != null) args.push("--max-results", String(input.max_results));
453
- if (input.session) args.push("--session", input.session);
454
- if (input.language) args.push("--language", input.language);
455
- if (input.reranker) args.push("--reranker", input.reranker);
456
- args.push("--format", "json");
457
- mergeExtraArgs(args, input.extra_args);
458
- args.push("--", input.query);
459
- if (input.path) args.push(input.path);
460
- break;
461
- }
462
- case "extract": {
463
- if (!input.files?.length) return fail("files required for extract");
464
- args.push("--format", "json");
465
- mergeExtraArgs(args, input.extra_args);
466
- args.push(...input.files);
467
- break;
468
- }
469
- case "symbols": {
470
- // Accept files via `files` array or fall back to `query` as a file path
471
- const symbolFiles = input.files?.length ? input.files : input.query ? [input.query] : [];
472
- if (!symbolFiles.length)
473
- return fail("files required for symbols (pass via 'files' or 'query')");
474
- args.push("--format", "json");
475
- mergeExtraArgs(args, input.extra_args);
476
- args.push(...symbolFiles);
477
- break;
478
- }
479
- case "query": {
480
- if (!input.query) return fail("query (AST pattern) required for query command");
481
- if (input.language) args.push("--language", input.language);
482
- if (input.max_results != null) args.push("--max-results", String(input.max_results));
483
- pushIf(args, input.allow_tests, "--allow-tests");
484
- args.push("--format", "json");
485
- mergeExtraArgs(args, input.extra_args);
486
- args.push("--", input.query);
487
- if (input.path) args.push(input.path);
488
- break;
489
- }
490
- }
491
-
492
- try {
493
- const { stdout } = await shellExec("probe", args, {
494
- cwd: ctx.workingDir,
495
- signal: ctx.abortSignal,
496
- timeout: 60_000,
497
- });
498
- try {
499
- const data = JSON.parse(stdout);
500
- return success(`probe ${cmd} completed`, data);
501
- } catch {
502
- // If not valid JSON, return raw output
503
- return success(`probe ${cmd} completed`, { raw: stdout });
504
- }
505
- } catch (err: unknown) {
506
- const e = asExecError(err);
507
- return fail(`probe ${cmd} failed: ${e.stderr || e.message}`);
508
- }
509
- }
510
-
511
- // ---------------------------------------------------------------------------
512
- // 4. sg — ast-grep
513
- // ---------------------------------------------------------------------------
514
-
515
- export async function executeSg(input: SgInput, ctx: ToolContext): Promise<ToolResult> {
516
- if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
517
- if (!(await hasBinary("sg")))
518
- return fail("ast-grep (sg) not installed. Install: cargo install ast-grep --locked");
519
-
520
- const cmd = input.command ?? "run";
521
- const isMutation = !!(input.rewrite || input.update_all);
522
-
523
- // Require confirmation for mutations
524
- if (isMutation && !input.update_all && ctx.confirm) {
525
- const approved = await ctx.confirm(
526
- `Rewrite code matching \`${input.pattern}\` to \`${input.rewrite}\` in ${input.language || "auto-detected"} files?`,
527
- );
528
- if (!approved) return fail("Rewrite cancelled by user");
529
- }
530
-
531
- const args: string[] = [cmd];
532
-
533
- if (cmd === "run") {
534
- if (!input.pattern) return fail("pattern required for sg run");
535
- args.push("--pattern", input.pattern);
536
- if (input.language) args.push("--lang", input.language);
537
- if (input.rewrite) args.push("--rewrite", input.rewrite);
538
- if (input.strictness) args.push("--strictness", input.strictness);
539
- pushIf(args, input.update_all, "-U");
540
- } else if (cmd === "scan") {
541
- if (input.rule) args.push("--rule", input.rule);
542
- if (input.inline_rules) args.push("--inline-rules", input.inline_rules);
543
- }
544
-
545
- // Shared flags
546
- if (input.globs) args.push("--globs", input.globs);
547
- if (input.context != null) args.push("-C", String(input.context));
548
-
549
- // Always JSON for machine parsing, skip color
550
- if (!isMutation) {
551
- args.push("--json=compact");
552
- }
553
- args.push("--color", "never");
554
-
555
- mergeExtraArgs(args, input.extra_args);
556
- args.push(input.path ?? ctx.workingDir);
557
-
558
- try {
559
- const { stdout } = await shellExec("sg", args, {
560
- cwd: ctx.workingDir,
561
- signal: ctx.abortSignal,
562
- });
563
- if (isMutation) {
564
- return success(`sg ${cmd}: rewrites applied`, { raw: stdout });
565
- }
566
- try {
567
- const data = JSON.parse(stdout);
568
- const count = Array.isArray(data) ? data.length : 0;
569
- return success(`Found ${count} matches`, { matches: data });
570
- } catch {
571
- return success(`sg ${cmd} completed`, { raw: stdout });
572
- }
573
- } catch (err: unknown) {
574
- // Exit code 1 = no matches for run
575
- const e = asExecError(err);
576
- if (e.code === 1 && cmd === "run") return success("No matches found", { matches: [] });
577
- return fail(`sg ${cmd} failed: ${e.stderr || e.message}`);
578
- }
579
- }
580
-
581
- // ---------------------------------------------------------------------------
582
- // 5. cbm — codebase-memory-mcp
583
- // ---------------------------------------------------------------------------
584
-
585
- // Internal helper to call cbm CLI
586
- async function cbmCall(
587
- tool: string,
588
- params: Record<string, unknown>,
589
- ctx: ToolContext,
590
- timeout?: number,
591
- ): Promise<unknown> {
592
- // Remove undefined/null values from params
593
- const clean: Record<string, unknown> = {};
594
- for (const [k, v] of Object.entries(params)) {
595
- if (v !== undefined && v !== null) clean[k] = v;
596
- }
597
- const { stdout } = await shellExec("codebase-memory-mcp", ["cli", tool, JSON.stringify(clean)], {
598
- cwd: ctx.workingDir,
599
- signal: ctx.abortSignal,
600
- timeout: timeout ?? 30_000,
601
- });
602
- // cbm cli returns MCP content format: { content: [{ type: "text", text: "..." }] }
603
- // Filter log lines (level=info ...) and parse
604
- const jsonLines = stdout.split("\n").filter((l) => l.trim() && !l.startsWith("level="));
605
- const parsed = JSON.parse(jsonLines.join("\n")) as Record<string, unknown>;
606
- if (Array.isArray(parsed.content)) {
607
- const textBlocks = (parsed.content as Array<{ type: string; text: string }>)
608
- .filter((c) => c.type === "text")
609
- .map((c) => c.text);
610
- const combined = textBlocks.join("\n");
611
- try {
612
- return JSON.parse(combined);
613
- } catch {
614
- return { text: combined };
615
- }
616
- }
617
- return parsed;
618
- }
619
-
620
- export async function executeCbm(input: CbmInput, ctx: ToolContext): Promise<ToolResult> {
621
- if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
622
- if (!(await hasBinary("codebase-memory-mcp")))
623
- return fail(
624
- "codebase-memory-mcp not installed. Install:\ncurl -fsSL https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/scripts/setup.sh | bash",
625
- );
626
-
627
- // Auto-detect project name: cbm slugifies repo_path by replacing / with -
628
- // and stripping the leading separator: /Users/hole/aria → Users-hole-aria
629
- const p = input.project ?? (input.path ?? ctx.workingDir).replace(/^\//, "").replace(/\//g, "-");
630
-
631
- // Auto-index: if the action requires an indexed project and no project exists,
632
- // transparently run a fast index first so queries don't silently return empty.
633
- const queryActions = new Set([
634
- "search",
635
- "trace",
636
- "impact",
637
- "context",
638
- "snippet",
639
- "code_search",
640
- "architecture",
641
- "schema",
642
- "cypher",
643
- ]);
644
- if (queryActions.has(input.action)) {
645
- let needsIndex = false;
646
- try {
647
- const statusResult = (await cbmCall("index_status", { project: p }, ctx)) as Record<
648
- string,
649
- unknown
650
- >;
651
- // If status indicates no project or empty graph, auto-index
652
- if (
653
- statusResult?.status === "no_project" ||
654
- statusResult?.node_count === 0 ||
655
- statusResult?.error
656
- ) {
657
- needsIndex = true;
658
- }
659
- } catch {
660
- // index_status failed — likely no project
661
- needsIndex = true;
662
- }
663
- if (needsIndex) {
664
- try {
665
- await cbmCall(
666
- "index_repository",
667
- { repo_path: input.path ?? ctx.workingDir, mode: "full" },
668
- ctx,
669
- 300_000,
670
- );
671
- } catch {
672
- // If auto-index fails, continue — let the actual action produce the error
673
- }
674
- }
675
- }
676
-
677
- switch (input.action) {
678
- case "index":
679
- return success(
680
- "Indexed",
681
- await cbmCall(
682
- "index_repository",
683
- { repo_path: input.path ?? ctx.workingDir, mode: input.mode ?? "full" },
684
- ctx,
685
- 300_000, // 5 min timeout for indexing
686
- ),
687
- );
688
-
689
- case "search":
690
- return success(
691
- "Search results",
692
- await cbmCall(
693
- "search_graph",
694
- {
695
- project: p,
696
- name_pattern: input.name,
697
- label: input.label,
698
- file_pattern: input.file,
699
- limit: input.limit ?? 20,
700
- },
701
- ctx,
702
- ),
703
- );
704
-
705
- case "trace": {
706
- if (!input.name) return fail("name required for trace");
707
- return success(
708
- `Call chain: ${input.name}`,
709
- await cbmCall(
710
- "trace_call_path",
711
- {
712
- project: p,
713
- function_name: input.name,
714
- direction: input.direction ?? "both",
715
- depth: input.depth ?? 3,
716
- edge_types: input.edge_types,
717
- },
718
- ctx,
719
- ),
720
- );
721
- }
722
-
723
- case "impact":
724
- return success(
725
- "Impact analysis",
726
- await cbmCall(
727
- "detect_changes",
728
- {
729
- project: p,
730
- scope: input.scope,
731
- depth: input.depth ?? 2,
732
- base_branch: input.base_branch ?? "main",
733
- },
734
- ctx,
735
- ),
736
- );
737
-
738
- case "context": {
739
- if (!input.name) return fail("name required for context");
740
- const [sym, callers, callees] = await Promise.all([
741
- cbmCall(
742
- "search_graph",
743
- { project: p, name_pattern: `^${escapeRegex(input.name)}$`, limit: 1 },
744
- ctx,
745
- ),
746
- cbmCall(
747
- "trace_call_path",
748
- { project: p, function_name: input.name, direction: "inbound", depth: 2 },
749
- ctx,
750
- ),
751
- cbmCall(
752
- "trace_call_path",
753
- { project: p, function_name: input.name, direction: "outbound", depth: 2 },
754
- ctx,
755
- ),
756
- ]);
757
- return success(`360° context: ${input.name}`, {
758
- definition: (sym as Record<string, unknown[]>).results?.[0],
759
- callers,
760
- callees,
761
- });
762
- }
763
-
764
- case "snippet": {
765
- if (!input.qualified_name) return fail("qualified_name required for snippet");
766
- return success(
767
- "Code snippet",
768
- await cbmCall(
769
- "get_code_snippet",
770
- {
771
- project: p,
772
- qualified_name: input.qualified_name,
773
- include_neighbors: input.include_neighbors,
774
- },
775
- ctx,
776
- ),
777
- );
778
- }
779
-
780
- case "code_search":
781
- return success(
782
- "Code search",
783
- await cbmCall(
784
- "search_code",
785
- {
786
- project: p,
787
- pattern: input.code_pattern,
788
- mode: input.code_mode ?? "compact",
789
- regex: input.regex,
790
- limit: input.limit ?? 10,
791
- file_pattern: input.file,
792
- context: input.context,
793
- },
794
- ctx,
795
- ),
796
- );
797
-
798
- case "architecture":
799
- return success("Architecture", await cbmCall("get_architecture", { project: p }, ctx));
800
-
801
- case "schema":
802
- return success("Schema", await cbmCall("get_graph_schema", { project: p }, ctx));
803
-
804
- case "cypher": {
805
- if (!input.query) return fail("query required for cypher");
806
- return success(
807
- "Cypher result",
808
- await cbmCall(
809
- "query_graph",
810
- { project: p, query: input.query, max_rows: input.max_rows },
811
- ctx,
812
- ),
813
- );
814
- }
815
-
816
- case "list_projects":
817
- return success("Projects", await cbmCall("list_projects", {}, ctx));
818
-
819
- case "delete_project": {
820
- if (!input.project) return fail("project required for delete_project");
821
- if (ctx.confirm) {
822
- const ok = await ctx.confirm(`Delete project "${input.project}" from cbm index?`);
823
- if (!ok) return fail("Cancelled");
824
- }
825
- return success("Deleted", await cbmCall("delete_project", { project: p }, ctx));
826
- }
827
-
828
- case "status":
829
- return success("Status", await cbmCall("index_status", { project: p }, ctx));
830
-
831
- default:
832
- return fail(`Unknown cbm action: ${input.action}`);
833
- }
834
- }
835
-
836
- // ---------------------------------------------------------------------------
837
- // 6. lsp — native LSP client (direct JSON-RPC to language servers, no Serena, no MCP, no HTTP)
838
- // ---------------------------------------------------------------------------
839
-
840
- // Dynamic import for ESM-only lsp-client (allows CJS build to succeed)
841
- // Type is loose to avoid pulling lsp-client.ts into CJS build graph
842
- interface LspClientModule {
843
- getServerForFile: (file: string) => string | undefined;
844
- getOrCreateServer: (
845
- serverName: string,
846
- rootPath: string,
847
- ) => {
848
- start: () => Promise<void>;
849
- definition: (file: string, line: number, char: number) => Promise<unknown>;
850
- references: (file: string, line: number, char: number) => Promise<unknown>;
851
- hover: (file: string, line: number, char: number) => Promise<unknown>;
852
- documentSymbols: (file: string) => Promise<unknown>;
853
- rename: (file: string, line: number, char: number, newName: string) => Promise<unknown>;
854
- };
855
- LSP_SERVERS: Record<string, { extensionToLanguage: Record<string, string> }>;
856
- }
857
- let _lspClient: LspClientModule | undefined;
858
- async function getLspClient(): Promise<LspClientModule> {
859
- if (!_lspClient) {
860
- // Use variable to prevent TypeScript from following the import in CJS build
861
- const modulePath = "./lsp-client.js";
862
- _lspClient = (await import(/* webpackIgnore: true */ modulePath)) as LspClientModule;
863
- }
864
- return _lspClient;
865
- }
866
-
867
- export async function executeLsp(input: LspInput, ctx: ToolContext): Promise<ToolResult> {
868
- if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
869
-
870
- if (!input.file) return fail("file required");
871
-
872
- const { getServerForFile, getOrCreateServer, LSP_SERVERS } = await getLspClient();
873
-
874
- const serverName = getServerForFile(input.file);
875
- if (!serverName) {
876
- const ext = input.file.slice(input.file.lastIndexOf("."));
877
- const supported = Object.entries(LSP_SERVERS)
878
- .map(([name, cfg]) => `${name}: ${Object.keys(cfg.extensionToLanguage).join(", ")}`)
879
- .join("\n ");
880
- return fail(`No language server for extension "${ext}". Supported:\n ${supported}`);
881
- }
882
-
883
- // Rename requires confirmation
884
- if (input.action === "rename" && ctx.confirm) {
885
- const ok = await ctx.confirm(
886
- `Rename symbol at ${input.file}:${input.line}:${input.character} to "${input.new_name}"?`,
887
- );
888
- if (!ok) return fail("Cancelled by user");
889
- }
890
-
891
- const server = getOrCreateServer(serverName, ctx.workingDir);
892
-
893
- try {
894
- await server.start();
895
-
896
- switch (input.action) {
897
- case "definition": {
898
- if (input.line == null || input.character == null)
899
- return fail("line and character required for definition");
900
- const result = await server.definition(input.file, input.line, input.character);
901
- return success(`lsp definition`, result);
902
- }
903
-
904
- case "references": {
905
- if (input.line == null || input.character == null)
906
- return fail("line and character required for references");
907
- const result = await server.references(input.file, input.line, input.character);
908
- return success(`lsp references`, result);
909
- }
910
-
911
- case "hover": {
912
- if (input.line == null || input.character == null)
913
- return fail("line and character required for hover");
914
- const result = await server.hover(input.file, input.line, input.character);
915
- return success(`lsp hover`, result);
916
- }
917
-
918
- case "symbols": {
919
- const result = await server.documentSymbols(input.file);
920
- return success(`lsp symbols`, result);
921
- }
922
-
923
- case "rename": {
924
- if (input.line == null || input.character == null || !input.new_name)
925
- return fail("line, character, and new_name required for rename");
926
- const result = await server.rename(input.file, input.line, input.character, input.new_name);
927
- return success(`lsp rename`, result);
928
- }
929
-
930
- default:
931
- return fail(
932
- `Unknown lsp action: ${input.action}. Use: definition, references, hover, symbols, rename`,
933
- );
934
- }
935
- } catch (err: unknown) {
936
- const e = asExecError(err);
937
- return fail(`lsp ${input.action} failed: ${e.message}`);
938
- }
939
- }
940
-
941
- // ---------------------------------------------------------------------------
942
- // 7. serena — HTTP project server (kept alongside native LSP for full Serena API)
943
- // ---------------------------------------------------------------------------
944
-
945
- const SERENA_PORT = 9750;
946
- const SERENA_BASE = `http://127.0.0.1:${SERENA_PORT}`;
947
- const SERENA_PROJECT = "aria";
948
-
949
- const SERENA_TOOL_MAP: Record<string, string> = {
950
- find_symbol: "find_symbol",
951
- find_references: "find_referencing_symbols",
952
- overview: "get_symbols_overview",
953
- replace_body: "replace_symbol_body",
954
- insert_after: "insert_after_symbol",
955
- insert_before: "insert_before_symbol",
956
- rename: "rename_symbol",
957
- search: "search_for_pattern",
958
- };
959
-
960
- // ---------------------------------------------------------------------------
961
- // Serena auto-start: spawn the HTTP project server on demand
962
- // ---------------------------------------------------------------------------
963
-
964
- let serenaStarting: Promise<boolean> | null = null;
965
-
966
- async function isSerenaAlive(): Promise<boolean> {
967
- // Lightweight TCP probe — just check if something is listening on the port.
968
- // A full HTTP request is too heavy during startup (Serena takes seconds to load projects).
969
- return new Promise<boolean>((resolve) => {
970
- const sock = createConnection({ host: "127.0.0.1", port: SERENA_PORT }, () => {
971
- sock.destroy();
972
- resolve(true);
973
- });
974
- sock.setTimeout(2_000);
975
- sock.on("error", () => resolve(false));
976
- sock.on("timeout", () => {
977
- sock.destroy();
978
- resolve(false);
979
- });
980
- });
981
- }
982
-
983
- function findSerenaProjectRoot(): string {
984
- // Walk up from cwd looking for .serena/project.yml
985
- let dir = pathResolve(process.cwd());
986
- while (dir !== dirname(dir)) {
987
- if (existsSync(pathJoin(dir, ".serena", "project.yml"))) return dir;
988
- dir = dirname(dir);
989
- }
990
- // Fallback: walk up from this file's directory
991
- // (compiled JS lives in packages/tools/dist/executors/)
992
- // __dirname is available since the build target is CJS
993
- dir = typeof __dirname === "string" ? pathResolve(__dirname) : pathResolve(".");
994
- while (dir !== dirname(dir)) {
995
- if (existsSync(pathJoin(dir, ".serena", "project.yml"))) return dir;
996
- dir = dirname(dir);
997
- }
998
- return process.cwd();
999
- }
1000
-
1001
- let cachedSerenaBin: string | null | undefined;
1002
-
1003
- function resolveSerenaBin(): string | null {
1004
- if (cachedSerenaBin !== undefined) return cachedSerenaBin as string | null;
1005
-
1006
- // Find the serena binary from uv's cache directory.
1007
- // We avoid `uvx --from git+... which serena` because it triggers a blocking
1008
- // git fetch that hangs inside a detached spawn context.
1009
- const cacheBase = pathJoin(process.env.HOME ?? "/tmp", ".cache", "uv", "archive-v0");
1010
- try {
1011
- const entries = readdirSync(cacheBase)
1012
- .map((d: string) => pathJoin(cacheBase, d, "bin", "serena"))
1013
- .filter((p: string) => existsSync(p))
1014
- .sort((a: string, b: string) => statSync(b).mtimeMs - statSync(a).mtimeMs);
1015
- cachedSerenaBin = entries.length > 0 ? entries[0] : null;
1016
- } catch {
1017
- cachedSerenaBin = null;
1018
- }
1019
-
1020
- return cachedSerenaBin ?? null;
1021
- }
1022
-
1023
- function spawnSerenaServer(): void {
1024
- const projectRoot = findSerenaProjectRoot();
1025
- const serenaBin = resolveSerenaBin();
1026
- if (!serenaBin) return;
1027
-
1028
- // Spawn the cached Python binary directly with stdio:'ignore' + detached.
1029
- // Using 'uvx --from git+...' does NOT work because uvx triggers a blocking
1030
- // git fetch that hangs/dies with closed file descriptors.
1031
- const child = cpSpawn(serenaBin, ["start-project-server", "--port", String(SERENA_PORT)], {
1032
- cwd: projectRoot,
1033
- detached: true,
1034
- stdio: "ignore",
1035
- env: { ...process.env },
1036
- });
1037
- child.unref();
1038
- }
1039
-
1040
- async function ensureSerenaServer(): Promise<boolean> {
1041
- if (await isSerenaAlive()) return true;
1042
-
1043
- // Deduplicate concurrent start attempts
1044
- if (serenaStarting) return serenaStarting;
1045
-
1046
- serenaStarting = (async () => {
1047
- spawnSerenaServer();
1048
-
1049
- // Poll for readiness (serena can take a few seconds to initialize)
1050
- const deadline = Date.now() + 30_000;
1051
- const interval = 500;
1052
- while (Date.now() < deadline) {
1053
- await new Promise((r) => setTimeout(r, interval));
1054
- if (await isSerenaAlive()) {
1055
- serenaStarting = null;
1056
- return true;
1057
- }
1058
- }
1059
- serenaStarting = null;
1060
- return false;
1061
- })();
1062
-
1063
- return serenaStarting;
1064
- }
1065
-
1066
- export async function executeSerena(input: SerenaInput, ctx: ToolContext): Promise<ToolResult> {
1067
- if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
1068
-
1069
- const toolName = SERENA_TOOL_MAP[input.action];
1070
- if (!toolName) return fail(`Unknown serena action: ${input.action}`);
1071
-
1072
- const isMutation = ["replace_body", "insert_after", "insert_before", "rename"].includes(
1073
- input.action,
1074
- );
1075
- if (isMutation && ctx.confirm) {
1076
- const desc =
1077
- input.action === "rename"
1078
- ? `Rename "${input.name_path}" to "${input.new_name}"?`
1079
- : `${input.action} on "${input.name_path}"?`;
1080
- const ok = await ctx.confirm(desc);
1081
- if (!ok) return fail("Cancelled by user");
1082
- }
1083
-
1084
- // Auto-start the Serena project server if not running
1085
- const alive = await ensureSerenaServer();
1086
- if (!alive) {
1087
- return fail(
1088
- "Failed to auto-start Serena project server after 30s. " +
1089
- "Check logs or start manually:\n" +
1090
- `uvx --from "git+https://github.com/oraios/serena" serena start-project-server --port ${SERENA_PORT}`,
1091
- );
1092
- }
1093
-
1094
- const params: Record<string, unknown> = { ...input.extra_args };
1095
- if (input.name_path) {
1096
- if (input.action === "find_symbol") {
1097
- params.name_path_pattern = input.name_path;
1098
- } else {
1099
- params.name_path = input.name_path;
1100
- }
1101
- }
1102
- if (input.relative_path) params.relative_path = input.relative_path;
1103
- if (input.include_body != null) params.include_body = input.include_body;
1104
- if (input.include_info != null) params.include_info = input.include_info;
1105
- if (input.depth != null) params.depth = input.depth;
1106
- if (input.body) params.body = input.body;
1107
- if (input.new_name) params.new_name = input.new_name;
1108
- if (input.pattern) params.substring_pattern = input.pattern;
1109
- if (input.context_before != null) params.context_lines_before = input.context_before;
1110
- if (input.context_after != null) params.context_lines_after = input.context_after;
1111
- if (input.paths_include) params.paths_include_glob = input.paths_include;
1112
- if (input.paths_exclude) params.paths_exclude_glob = input.paths_exclude;
1113
-
1114
- try {
1115
- const body = JSON.stringify({
1116
- project_name: SERENA_PROJECT,
1117
- tool_name: toolName,
1118
- tool_params_json: JSON.stringify(params),
1119
- });
1120
- const response = await fetch(`${SERENA_BASE}/query_project`, {
1121
- method: "POST",
1122
- headers: { "Content-Type": "application/json" },
1123
- body,
1124
- signal: ctx.abortSignal,
1125
- });
1126
- if (!response.ok) {
1127
- const text = await response.text();
1128
- return fail(`serena ${input.action}: HTTP ${response.status} — ${text.slice(0, 200)}`);
1129
- }
1130
- const text = await response.text();
1131
- try {
1132
- return success(`serena ${input.action} completed`, JSON.parse(text));
1133
- } catch {
1134
- return success(`serena ${input.action} completed`, { raw: text });
1135
- }
1136
- } catch (err: unknown) {
1137
- const e = asExecError(err);
1138
- return fail(`serena ${input.action} failed: ${e.message}`);
1139
- }
1140
- }
1141
-
1142
- // ---------------------------------------------------------------------------
1143
- // 8. fff — native CLI (fff-cli binary, zero MCP)
1144
- // ---------------------------------------------------------------------------
1145
-
1146
- export async function executeFff(input: FffInput, ctx: ToolContext): Promise<ToolResult> {
1147
- if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
1148
- if (!(await hasBinary("fff-cli")))
1149
- return fail(
1150
- "fff-cli not installed. Build: cd vendor/fff-cli && cargo build --release && cp target/release/fff-cli ~/.local/bin/",
1151
- );
1152
-
1153
- const args: string[] = [input.action];
1154
-
1155
- // Query or patterns. Native fff-cli supports positional query terms; constraints are
1156
- // appended as additional terms for grep/find_files and patterns for multi_grep.
1157
- if (input.action === "multi_grep" && input.patterns?.length) {
1158
- args.push(...input.patterns);
1159
- if (input.constraints) args.push(input.constraints);
1160
- } else {
1161
- if (input.query) args.push(input.query);
1162
- if (input.constraints) args.push(input.constraints);
1163
- }
1164
-
1165
- // Path
1166
- args.push("--path", input.path ?? ctx.workingDir);
1167
-
1168
- try {
1169
- const { stdout } = await shellExec("fff-cli", args, {
1170
- cwd: ctx.workingDir,
1171
- signal: ctx.abortSignal,
1172
- timeout: 30_000,
1173
- });
1174
- return success(`fff ${input.action} completed`, JSON.parse(stdout));
1175
- } catch (err: unknown) {
1176
- const e = asExecError(err);
1177
- return fail(`fff ${input.action} failed: ${e.stderr || e.message}`);
1178
- }
1179
- }