@sammysnake/fast-context-mcp 1.3.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +274 -0
- package/package.json +47 -0
- package/src/core.mjs +1906 -0
- package/src/directory-scorer.mjs +1059 -0
- package/src/executor.mjs +597 -0
- package/src/extract-key.mjs +93 -0
- package/src/protobuf.mjs +235 -0
- package/src/server.mjs +320 -0
package/src/executor.mjs
ADDED
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool executor for Windsurf's restricted commands.
|
|
3
|
+
*
|
|
4
|
+
* Uses @vscode/ripgrep for built-in rg binary — no system install needed.
|
|
5
|
+
* Matches Python ToolExecutor behavior exactly.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { execFileSync, execFile as execFileCb } from "node:child_process";
|
|
9
|
+
import { readdirSync, readFileSync, statSync, existsSync } from "node:fs";
|
|
10
|
+
import { join, resolve, relative, sep, basename } from "node:path";
|
|
11
|
+
import { promisify } from "node:util";
|
|
12
|
+
import { rgPath } from "@vscode/ripgrep";
|
|
13
|
+
import treeNodeCli from "tree-node-cli";
|
|
14
|
+
|
|
15
|
+
const execFileAsync = promisify(execFileCb);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Parse an integer env var with optional clamping.
|
|
19
|
+
* @param {string} name
|
|
20
|
+
* @param {number} defaultValue
|
|
21
|
+
* @param {{ min?: number, max?: number }} [opts]
|
|
22
|
+
* @returns {number}
|
|
23
|
+
*/
|
|
24
|
+
function readIntEnv(name, defaultValue, opts = {}) {
|
|
25
|
+
const raw = process.env[name];
|
|
26
|
+
const parsed = Number.parseInt(raw ?? "", 10);
|
|
27
|
+
if (!Number.isFinite(parsed)) return defaultValue;
|
|
28
|
+
const min = typeof opts.min === "number" ? opts.min : null;
|
|
29
|
+
const max = typeof opts.max === "number" ? opts.max : null;
|
|
30
|
+
let value = parsed;
|
|
31
|
+
if (min !== null) value = Math.max(min, value);
|
|
32
|
+
if (max !== null) value = Math.min(max, value);
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const RESULT_MAX_LINES = readIntEnv("FC_RESULT_MAX_LINES", 50, { min: 1, max: 500 });
|
|
37
|
+
const LINE_MAX_CHARS = readIntEnv("FC_LINE_MAX_CHARS", 250, { min: 20, max: 10000 });
|
|
38
|
+
|
|
39
|
+
export class ToolExecutor {
|
|
40
|
+
/**
|
|
41
|
+
* @param {string} projectRoot
|
|
42
|
+
*/
|
|
43
|
+
constructor(projectRoot) {
|
|
44
|
+
this.root = resolve(projectRoot);
|
|
45
|
+
/** @type {string[]} */
|
|
46
|
+
this.collectedRgPatterns = [];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Map virtual /codebase path to real filesystem path.
|
|
51
|
+
* @param {string} virtual
|
|
52
|
+
* @returns {string}
|
|
53
|
+
*/
|
|
54
|
+
_real(virtual) {
|
|
55
|
+
// Guard against undefined/null from malformed AI responses
|
|
56
|
+
if (virtual == null || typeof virtual !== "string") {
|
|
57
|
+
return this.root;
|
|
58
|
+
}
|
|
59
|
+
if (virtual.startsWith("/codebase") || virtual.startsWith("\\codebase")) {
|
|
60
|
+
const rel = virtual.slice("/codebase".length).replace(/^[\/\\]+/, "");
|
|
61
|
+
return join(this.root, rel);
|
|
62
|
+
}
|
|
63
|
+
return virtual;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Truncate output to match Windsurf behavior:
|
|
68
|
+
* 50 line limit, 250 char per-line silent truncation.
|
|
69
|
+
* @param {string} text
|
|
70
|
+
* @returns {string}
|
|
71
|
+
*/
|
|
72
|
+
static _truncate(text) {
|
|
73
|
+
const lines = text.split("\n");
|
|
74
|
+
const truncatedLines = [];
|
|
75
|
+
const limit = Math.min(lines.length, RESULT_MAX_LINES);
|
|
76
|
+
for (let i = 0; i < limit; i++) {
|
|
77
|
+
const line = lines[i];
|
|
78
|
+
truncatedLines.push(line.length > LINE_MAX_CHARS ? line.slice(0, LINE_MAX_CHARS) : line);
|
|
79
|
+
}
|
|
80
|
+
let result = truncatedLines.join("\n");
|
|
81
|
+
if (lines.length > RESULT_MAX_LINES) {
|
|
82
|
+
result += "\n... (lines truncated) ...";
|
|
83
|
+
}
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Replace real project root with /codebase in output.
|
|
89
|
+
* @param {string} text
|
|
90
|
+
* @returns {string}
|
|
91
|
+
*/
|
|
92
|
+
_remap(text) {
|
|
93
|
+
// Replace both forward-slash and native-sep versions
|
|
94
|
+
return text.replaceAll(this.root, "/codebase");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Check if a file matches any glob pattern (simplified fnmatch).
|
|
99
|
+
* @param {string} relPath
|
|
100
|
+
* @param {string} filename
|
|
101
|
+
* @param {string[]} patterns
|
|
102
|
+
* @returns {boolean}
|
|
103
|
+
*/
|
|
104
|
+
static _globMatch(relPath, filename, patterns) {
|
|
105
|
+
for (const pat of patterns) {
|
|
106
|
+
const normalized = pat.replace(/\\/g, "/");
|
|
107
|
+
if (normalized.startsWith("**/")) {
|
|
108
|
+
const sub = normalized.slice(3);
|
|
109
|
+
if (sub.includes("/**")) continue; // directory pattern, handled by skipDirs
|
|
110
|
+
if (_fnmatch(filename, sub)) return true;
|
|
111
|
+
} else if (_fnmatch(relPath, normalized)) {
|
|
112
|
+
return true;
|
|
113
|
+
} else if (_fnmatch(filename, normalized)) {
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Search for pattern using @vscode/ripgrep (async version).
|
|
122
|
+
* @param {string} pattern
|
|
123
|
+
* @param {string} path
|
|
124
|
+
* @param {string[]|null} [include]
|
|
125
|
+
* @param {string[]|null} [exclude]
|
|
126
|
+
* @returns {Promise<string>}
|
|
127
|
+
*/
|
|
128
|
+
async rgAsync(pattern, path, include = null, exclude = null) {
|
|
129
|
+
if (!pattern || typeof pattern !== "string") {
|
|
130
|
+
return "Error: missing or invalid pattern";
|
|
131
|
+
}
|
|
132
|
+
if (!path || typeof path !== "string") {
|
|
133
|
+
return "Error: missing or invalid path";
|
|
134
|
+
}
|
|
135
|
+
this.collectedRgPatterns.push(pattern);
|
|
136
|
+
const rp = this._real(path);
|
|
137
|
+
if (!existsSync(rp)) {
|
|
138
|
+
return `Error: path does not exist: ${path}`;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const args = ["--no-heading", "-n", "--max-count", "50", pattern, rp];
|
|
142
|
+
if (include) {
|
|
143
|
+
for (const g of include) {
|
|
144
|
+
args.push("--glob", g);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (exclude) {
|
|
148
|
+
for (const g of exclude) {
|
|
149
|
+
args.push("--glob", `!${g}`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
try {
|
|
154
|
+
const { stdout } = await execFileAsync(rgPath, args, {
|
|
155
|
+
timeout: 30000,
|
|
156
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
157
|
+
env: { ...process.env, RIPGREP_CONFIG_PATH: "" },
|
|
158
|
+
encoding: "utf-8",
|
|
159
|
+
});
|
|
160
|
+
return ToolExecutor._truncate(this._remap(stdout || "(no matches)"));
|
|
161
|
+
} catch (err) {
|
|
162
|
+
if (err.code === 1 || err.status === 1) {
|
|
163
|
+
return "(no matches)";
|
|
164
|
+
}
|
|
165
|
+
if (err.stderr) {
|
|
166
|
+
return ToolExecutor._truncate(this._remap(err.stderr));
|
|
167
|
+
}
|
|
168
|
+
return `Error: ${err.message}`;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Search for pattern using @vscode/ripgrep.
|
|
174
|
+
* @param {string} pattern
|
|
175
|
+
* @param {string} path
|
|
176
|
+
* @param {string[]|null} [include]
|
|
177
|
+
* @param {string[]|null} [exclude]
|
|
178
|
+
* @returns {string}
|
|
179
|
+
*/
|
|
180
|
+
rg(pattern, path, include = null, exclude = null) {
|
|
181
|
+
if (!pattern || typeof pattern !== "string") {
|
|
182
|
+
return "Error: missing or invalid pattern";
|
|
183
|
+
}
|
|
184
|
+
if (!path || typeof path !== "string") {
|
|
185
|
+
return "Error: missing or invalid path";
|
|
186
|
+
}
|
|
187
|
+
this.collectedRgPatterns.push(pattern);
|
|
188
|
+
const rp = this._real(path);
|
|
189
|
+
if (!existsSync(rp)) {
|
|
190
|
+
return `Error: path does not exist: ${path}`;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const args = ["--no-heading", "-n", "--max-count", "50", pattern, rp];
|
|
194
|
+
if (include) {
|
|
195
|
+
for (const g of include) {
|
|
196
|
+
args.push("--glob", g);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (exclude) {
|
|
200
|
+
for (const g of exclude) {
|
|
201
|
+
args.push("--glob", `!${g}`);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
try {
|
|
206
|
+
const stdout = execFileSync(rgPath, args, {
|
|
207
|
+
timeout: 30000,
|
|
208
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
209
|
+
env: { ...process.env, RIPGREP_CONFIG_PATH: "" },
|
|
210
|
+
encoding: "utf-8",
|
|
211
|
+
});
|
|
212
|
+
return ToolExecutor._truncate(this._remap(stdout || "(no matches)"));
|
|
213
|
+
} catch (err) {
|
|
214
|
+
// rg exits with code 1 when no matches found — that's normal
|
|
215
|
+
if (err.status === 1) {
|
|
216
|
+
return "(no matches)";
|
|
217
|
+
}
|
|
218
|
+
// rg exits with code 2 on errors
|
|
219
|
+
if (err.stderr) {
|
|
220
|
+
return ToolExecutor._truncate(this._remap(err.stderr));
|
|
221
|
+
}
|
|
222
|
+
return `Error: ${err.message}`;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Read file contents with optional line range (1-indexed, inclusive).
|
|
228
|
+
* @param {string} file
|
|
229
|
+
* @param {number|null} [startLine]
|
|
230
|
+
* @param {number|null} [endLine]
|
|
231
|
+
* @returns {string}
|
|
232
|
+
*/
|
|
233
|
+
readfile(file, startLine = null, endLine = null) {
|
|
234
|
+
if (!file || typeof file !== "string") {
|
|
235
|
+
return "Error: missing or invalid file path";
|
|
236
|
+
}
|
|
237
|
+
const rp = this._real(file);
|
|
238
|
+
try {
|
|
239
|
+
const stat = statSync(rp);
|
|
240
|
+
if (!stat.isFile()) {
|
|
241
|
+
return `Error: file not found: ${file}`;
|
|
242
|
+
}
|
|
243
|
+
} catch {
|
|
244
|
+
return `Error: file not found: ${file}`;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
let content;
|
|
248
|
+
try {
|
|
249
|
+
content = readFileSync(rp, "utf-8");
|
|
250
|
+
} catch (e) {
|
|
251
|
+
return `Error: ${e.message}`;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const allLines = content.split("\n");
|
|
255
|
+
// If the file ends with a newline, there'll be an empty string at the end
|
|
256
|
+
// Keep behavior consistent with Python readlines()
|
|
257
|
+
const s = (startLine || 1) - 1;
|
|
258
|
+
const e = endLine || allLines.length;
|
|
259
|
+
const selected = allLines.slice(s, e);
|
|
260
|
+
const out = selected.map((line, idx) => `${s + idx + 1}:${line}`).join("\n");
|
|
261
|
+
return ToolExecutor._truncate(out);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Display directory structure as a tree.
|
|
266
|
+
* @param {string} path
|
|
267
|
+
* @param {number|null} [levels]
|
|
268
|
+
* @returns {string}
|
|
269
|
+
*/
|
|
270
|
+
tree(path, levels = null) {
|
|
271
|
+
if (!path || typeof path !== "string") {
|
|
272
|
+
return "Error: missing or invalid path";
|
|
273
|
+
}
|
|
274
|
+
const rp = this._real(path);
|
|
275
|
+
try {
|
|
276
|
+
const stat = statSync(rp);
|
|
277
|
+
if (!stat.isDirectory()) {
|
|
278
|
+
return `Error: dir not found: ${path}`;
|
|
279
|
+
}
|
|
280
|
+
} catch {
|
|
281
|
+
return `Error: dir not found: ${path}`;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
try {
|
|
285
|
+
const opts = {};
|
|
286
|
+
if (levels) opts.maxDepth = levels;
|
|
287
|
+
let stdout = treeNodeCli(rp, opts);
|
|
288
|
+
// Two-step normalization:
|
|
289
|
+
// 1. _remap: replace absolute project root with /codebase globally
|
|
290
|
+
stdout = this._remap(stdout);
|
|
291
|
+
// 2. Handle basename root line: tree-node-cli outputs the directory
|
|
292
|
+
// basename as the first line (e.g. "supabase"), which _remap won't
|
|
293
|
+
// catch since it's not the full absolute path. Replace with the
|
|
294
|
+
// virtual path the AI requested (already /codebase/...).
|
|
295
|
+
const dirName = rp.split("/").pop() || rp.split("\\").pop() || rp;
|
|
296
|
+
const lines = stdout.split("\n");
|
|
297
|
+
if (lines[0] === dirName) {
|
|
298
|
+
lines[0] = path;
|
|
299
|
+
stdout = lines.join("\n");
|
|
300
|
+
}
|
|
301
|
+
return ToolExecutor._truncate(stdout);
|
|
302
|
+
} catch {
|
|
303
|
+
return `Error: failed to generate tree for ${path}`;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* List files in a directory.
|
|
309
|
+
* @param {string} path
|
|
310
|
+
* @param {boolean} [longFormat=false]
|
|
311
|
+
* @param {boolean} [allFiles=false]
|
|
312
|
+
* @returns {string}
|
|
313
|
+
*/
|
|
314
|
+
ls(path, longFormat = false, allFiles = false) {
|
|
315
|
+
if (!path || typeof path !== "string") {
|
|
316
|
+
return "Error: missing or invalid path";
|
|
317
|
+
}
|
|
318
|
+
const rp = this._real(path);
|
|
319
|
+
try {
|
|
320
|
+
const stat = statSync(rp);
|
|
321
|
+
if (!stat.isDirectory()) {
|
|
322
|
+
return `Error: not a directory: ${path}`;
|
|
323
|
+
}
|
|
324
|
+
} catch {
|
|
325
|
+
return `Error: dir not found: ${path}`;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
let entries;
|
|
329
|
+
try {
|
|
330
|
+
entries = readdirSync(rp).sort();
|
|
331
|
+
} catch (e) {
|
|
332
|
+
return `Error: ${e.message}`;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
if (!allFiles) {
|
|
336
|
+
entries = entries.filter((e) => !e.startsWith("."));
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
if (!longFormat) {
|
|
340
|
+
return ToolExecutor._truncate(entries.join("\n"));
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// Long format: emulate ls -l output
|
|
344
|
+
const lines = [`total ${entries.length}`];
|
|
345
|
+
for (const name of entries) {
|
|
346
|
+
const fp = join(rp, name);
|
|
347
|
+
try {
|
|
348
|
+
const st = statSync(fp);
|
|
349
|
+
const isDir = st.isDirectory();
|
|
350
|
+
const type = isDir ? "d" : "-";
|
|
351
|
+
const perm = "rwxr-xr-x";
|
|
352
|
+
const size = String(st.size).padStart(8);
|
|
353
|
+
const mtime = st.mtime;
|
|
354
|
+
const month = mtime.toLocaleString("en", { month: "short" });
|
|
355
|
+
const day = String(mtime.getDate()).padStart(2);
|
|
356
|
+
const hh = String(mtime.getHours()).padStart(2, "0");
|
|
357
|
+
const mm = String(mtime.getMinutes()).padStart(2, "0");
|
|
358
|
+
const dateStr = `${month} ${day} ${hh}:${mm}`;
|
|
359
|
+
lines.push(`${type}${perm} 1 user staff ${size} ${dateStr} ${name}`);
|
|
360
|
+
} catch {
|
|
361
|
+
lines.push(`?--------- ? ? ? ? ? ? ? ${name}`);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return ToolExecutor._truncate(this._remap(lines.join("\n")));
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Glob pattern matching.
|
|
369
|
+
* @param {string} pattern
|
|
370
|
+
* @param {string} path
|
|
371
|
+
* @param {string} [typeFilter="all"]
|
|
372
|
+
* @returns {string}
|
|
373
|
+
*/
|
|
374
|
+
glob(pattern, path, typeFilter = "all") {
|
|
375
|
+
if (!pattern || typeof pattern !== "string") {
|
|
376
|
+
return "Error: missing or invalid pattern";
|
|
377
|
+
}
|
|
378
|
+
if (!path || typeof path !== "string") {
|
|
379
|
+
return "Error: missing or invalid path";
|
|
380
|
+
}
|
|
381
|
+
const rp = this._real(path);
|
|
382
|
+
|
|
383
|
+
// Use recursive readdir + fnmatch since Node 22 globSync may not be available
|
|
384
|
+
const matches = [];
|
|
385
|
+
|
|
386
|
+
try {
|
|
387
|
+
_globWalk(rp, pattern, matches, typeFilter);
|
|
388
|
+
} catch {
|
|
389
|
+
// fallback: try simple readdir
|
|
390
|
+
try {
|
|
391
|
+
const entries = readdirSync(rp);
|
|
392
|
+
for (const entry of entries) {
|
|
393
|
+
const fp = join(rp, entry);
|
|
394
|
+
if (_fnmatch(entry, pattern)) {
|
|
395
|
+
try {
|
|
396
|
+
const st = statSync(fp);
|
|
397
|
+
if (typeFilter === "file" && !st.isFile()) continue;
|
|
398
|
+
if (typeFilter === "directory" && !st.isDirectory()) continue;
|
|
399
|
+
matches.push(fp);
|
|
400
|
+
} catch { /* skip */ }
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
} catch { /* skip */ }
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const sorted = matches.sort().slice(0, 100);
|
|
407
|
+
const out = sorted.map((m) => this._remap(m)).join("\n");
|
|
408
|
+
return out || "(no matches)";
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Dispatch a command dict to the appropriate method (async).
|
|
413
|
+
* Uses async rg for parallelism, sync for others (they are fast enough).
|
|
414
|
+
* @param {Object} cmd
|
|
415
|
+
* @returns {Promise<string>}
|
|
416
|
+
*/
|
|
417
|
+
async execCommandAsync(cmd) {
|
|
418
|
+
if (!cmd || typeof cmd !== "object") {
|
|
419
|
+
return "Error: missing or invalid command";
|
|
420
|
+
}
|
|
421
|
+
const t = cmd.type || "";
|
|
422
|
+
switch (t) {
|
|
423
|
+
case "rg":
|
|
424
|
+
return this.rgAsync(cmd.pattern, cmd.path, cmd.include || null, cmd.exclude || null);
|
|
425
|
+
case "readfile":
|
|
426
|
+
return this.readfile(cmd.file, cmd.start_line || null, cmd.end_line || null);
|
|
427
|
+
case "tree":
|
|
428
|
+
return this.tree(cmd.path, cmd.levels || null);
|
|
429
|
+
case "ls":
|
|
430
|
+
return this.ls(cmd.path, cmd.long_format || false, cmd.all || false);
|
|
431
|
+
case "glob":
|
|
432
|
+
return this.glob(cmd.pattern, cmd.path, cmd.type_filter || "all");
|
|
433
|
+
default:
|
|
434
|
+
return `Error: unknown command type '${t}'`;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* Dispatch a command dict to the appropriate method.
|
|
440
|
+
* @param {Object} cmd
|
|
441
|
+
* @returns {string}
|
|
442
|
+
*/
|
|
443
|
+
execCommand(cmd) {
|
|
444
|
+
if (!cmd || typeof cmd !== "object") {
|
|
445
|
+
return "Error: missing or invalid command";
|
|
446
|
+
}
|
|
447
|
+
const t = cmd.type || "";
|
|
448
|
+
switch (t) {
|
|
449
|
+
case "rg":
|
|
450
|
+
return this.rg(cmd.pattern, cmd.path, cmd.include || null, cmd.exclude || null);
|
|
451
|
+
case "readfile":
|
|
452
|
+
return this.readfile(cmd.file, cmd.start_line || null, cmd.end_line || null);
|
|
453
|
+
case "tree":
|
|
454
|
+
return this.tree(cmd.path, cmd.levels || null);
|
|
455
|
+
case "ls":
|
|
456
|
+
return this.ls(cmd.path, cmd.long_format || false, cmd.all || false);
|
|
457
|
+
case "glob":
|
|
458
|
+
return this.glob(cmd.pattern, cmd.path, cmd.type_filter || "all");
|
|
459
|
+
default:
|
|
460
|
+
return `Error: unknown command type '${t}'`;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Execute all commandN keys from a tool call args dict (parallel).
|
|
466
|
+
* @param {Object} args
|
|
467
|
+
* @returns {Promise<string>}
|
|
468
|
+
*/
|
|
469
|
+
async execToolCallAsync(args) {
|
|
470
|
+
if (!args || typeof args !== "object") {
|
|
471
|
+
return "Error: missing or invalid tool args";
|
|
472
|
+
}
|
|
473
|
+
const keys = Object.keys(args).filter((k) => k.startsWith("command")).sort();
|
|
474
|
+
const tasks = keys.map(async (key) => {
|
|
475
|
+
const output = await this.execCommandAsync(args[key]);
|
|
476
|
+
return `<${key}_result>\n${output}\n</${key}_result>`;
|
|
477
|
+
});
|
|
478
|
+
const results = await Promise.all(tasks);
|
|
479
|
+
return results.join("");
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Execute all commandN keys from a tool call args dict.
|
|
484
|
+
* @param {Object} args
|
|
485
|
+
* @returns {string}
|
|
486
|
+
*/
|
|
487
|
+
execToolCall(args) {
|
|
488
|
+
const parts = [];
|
|
489
|
+
if (!args || typeof args !== "object") {
|
|
490
|
+
return "Error: missing or invalid tool args";
|
|
491
|
+
}
|
|
492
|
+
const keys = Object.keys(args).filter((k) => k.startsWith("command")).sort();
|
|
493
|
+
for (const key of keys) {
|
|
494
|
+
const output = this.execCommand(args[key]);
|
|
495
|
+
parts.push(`<${key}_result>\n${output}\n</${key}_result>`);
|
|
496
|
+
}
|
|
497
|
+
return parts.join("");
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// ─── Helpers ───────────────────────────────────────────────
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* Simple fnmatch-like glob matching.
|
|
505
|
+
* Supports *, ?, and ** patterns.
|
|
506
|
+
* @param {string} str
|
|
507
|
+
* @param {string} pattern
|
|
508
|
+
* @returns {boolean}
|
|
509
|
+
*/
|
|
510
|
+
function _fnmatch(str, pattern) {
|
|
511
|
+
// Convert glob pattern to regex
|
|
512
|
+
let regex = "^";
|
|
513
|
+
let i = 0;
|
|
514
|
+
while (i < pattern.length) {
|
|
515
|
+
const c = pattern[i];
|
|
516
|
+
if (c === "*") {
|
|
517
|
+
if (pattern[i + 1] === "*") {
|
|
518
|
+
// ** matches everything including /
|
|
519
|
+
regex += ".*";
|
|
520
|
+
i += 2;
|
|
521
|
+
if (pattern[i] === "/") i++; // skip trailing /
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
regex += "[^/]*";
|
|
525
|
+
} else if (c === "?") {
|
|
526
|
+
regex += "[^/]";
|
|
527
|
+
} else if (c === "[") {
|
|
528
|
+
// Pass through character classes
|
|
529
|
+
const end = pattern.indexOf("]", i);
|
|
530
|
+
if (end === -1) {
|
|
531
|
+
regex += "\\[";
|
|
532
|
+
} else {
|
|
533
|
+
regex += pattern.slice(i, end + 1);
|
|
534
|
+
i = end;
|
|
535
|
+
}
|
|
536
|
+
} else if (".+^${}()|\\".includes(c)) {
|
|
537
|
+
regex += "\\" + c;
|
|
538
|
+
} else {
|
|
539
|
+
regex += c;
|
|
540
|
+
}
|
|
541
|
+
i++;
|
|
542
|
+
}
|
|
543
|
+
regex += "$";
|
|
544
|
+
try {
|
|
545
|
+
return new RegExp(regex).test(str);
|
|
546
|
+
} catch {
|
|
547
|
+
return false;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Recursive glob walk.
|
|
553
|
+
* @param {string} base
|
|
554
|
+
* @param {string} pattern
|
|
555
|
+
* @param {string[]} matches
|
|
556
|
+
* @param {string} typeFilter
|
|
557
|
+
*/
|
|
558
|
+
function _globWalk(base, pattern, matches, typeFilter) {
|
|
559
|
+
const isRecursive = pattern.includes("**");
|
|
560
|
+
|
|
561
|
+
const walk = (dir, depth) => {
|
|
562
|
+
if (matches.length >= 100) return;
|
|
563
|
+
if (!isRecursive && depth > 0) return;
|
|
564
|
+
|
|
565
|
+
let entries;
|
|
566
|
+
try {
|
|
567
|
+
entries = readdirSync(dir);
|
|
568
|
+
} catch {
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
for (const entry of entries) {
|
|
573
|
+
if (matches.length >= 100) return;
|
|
574
|
+
const fp = join(dir, entry);
|
|
575
|
+
const relFromBase = relative(base, fp).replace(/\\/g, "/");
|
|
576
|
+
|
|
577
|
+
let st;
|
|
578
|
+
try {
|
|
579
|
+
st = statSync(fp);
|
|
580
|
+
} catch {
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
if (_fnmatch(relFromBase, pattern) || _fnmatch(entry, pattern)) {
|
|
585
|
+
if (typeFilter === "file" && !st.isFile()) continue;
|
|
586
|
+
if (typeFilter === "directory" && !st.isDirectory()) continue;
|
|
587
|
+
matches.push(fp);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
if (st.isDirectory() && !entry.startsWith(".") && isRecursive) {
|
|
591
|
+
walk(fp, depth + 1);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
};
|
|
595
|
+
|
|
596
|
+
walk(base, 0);
|
|
597
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Windsurf API Key extraction from local installation.
|
|
3
|
+
*
|
|
4
|
+
* Cross-platform: macOS / Windows / Linux.
|
|
5
|
+
* Uses sql.js (pure JS/WASM) to read state.vscdb — no native compilation needed.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { homedir, platform } from "node:os";
|
|
11
|
+
import initSqlJs from "sql.js";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Get the platform-specific path to Windsurf's state.vscdb.
|
|
15
|
+
* @returns {string}
|
|
16
|
+
*/
|
|
17
|
+
export function getDbPath() {
|
|
18
|
+
const plat = platform();
|
|
19
|
+
const home = homedir();
|
|
20
|
+
|
|
21
|
+
if (plat === "darwin") {
|
|
22
|
+
return join(home, "Library", "Application Support", "Windsurf", "User", "globalStorage", "state.vscdb");
|
|
23
|
+
} else if (plat === "win32") {
|
|
24
|
+
const appdata = process.env.APPDATA || "";
|
|
25
|
+
if (!appdata) throw new Error("Cannot determine APPDATA path");
|
|
26
|
+
return join(appdata, "Windsurf", "User", "globalStorage", "state.vscdb");
|
|
27
|
+
} else {
|
|
28
|
+
// Linux
|
|
29
|
+
const config = process.env.XDG_CONFIG_HOME || join(home, ".config");
|
|
30
|
+
return join(config, "Windsurf", "User", "globalStorage", "state.vscdb");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Extract API Key from Windsurf state.vscdb.
|
|
36
|
+
* @param {string} [dbPath]
|
|
37
|
+
* @returns {Promise<{ api_key?: string, db_path: string, error?: string, hint?: string }>}
|
|
38
|
+
*/
|
|
39
|
+
export async function extractKey(dbPath) {
|
|
40
|
+
if (!dbPath) {
|
|
41
|
+
dbPath = getDbPath();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (!existsSync(dbPath)) {
|
|
45
|
+
return {
|
|
46
|
+
error: `Windsurf database not found: ${dbPath}`,
|
|
47
|
+
hint: "Ensure Windsurf is installed and logged in.",
|
|
48
|
+
db_path: dbPath,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let db;
|
|
53
|
+
try {
|
|
54
|
+
const SQL = await initSqlJs();
|
|
55
|
+
const buf = readFileSync(dbPath);
|
|
56
|
+
db = new SQL.Database(buf);
|
|
57
|
+
} catch (e) {
|
|
58
|
+
return { error: `Failed to open database: ${e.message}`, db_path: dbPath };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
try {
|
|
62
|
+
const stmt = db.prepare("SELECT value FROM ItemTable WHERE key = 'windsurfAuthStatus'");
|
|
63
|
+
if (!stmt.step()) {
|
|
64
|
+
stmt.free();
|
|
65
|
+
return {
|
|
66
|
+
error: "windsurfAuthStatus record not found",
|
|
67
|
+
hint: "Ensure Windsurf is logged in.",
|
|
68
|
+
db_path: dbPath,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const row = stmt.getAsObject();
|
|
73
|
+
stmt.free();
|
|
74
|
+
|
|
75
|
+
let data;
|
|
76
|
+
try {
|
|
77
|
+
data = JSON.parse(row.value);
|
|
78
|
+
} catch {
|
|
79
|
+
return { error: "windsurfAuthStatus data parse failed", db_path: dbPath };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const apiKey = data.apiKey || "";
|
|
83
|
+
if (!apiKey) {
|
|
84
|
+
return { error: "apiKey field is empty", db_path: dbPath };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return { api_key: apiKey, db_path: dbPath };
|
|
88
|
+
} catch (e) {
|
|
89
|
+
return { error: `Extraction failed: ${e.message}`, db_path: dbPath };
|
|
90
|
+
} finally {
|
|
91
|
+
db.close();
|
|
92
|
+
}
|
|
93
|
+
}
|