ai-helper-agent 2.8.3 → 2.8.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.
- package/dist/assets/{agent-store-CDvWEPZE.js → agent-store-BmOcvz_2.js} +1 -1
- package/dist/assets/background.js +70 -65
- package/dist/assets/{chat-export-BViVJfK1.js → chat-export-Df4FbELg.js} +1 -1
- package/dist/assets/content.js +18 -18
- package/dist/assets/{i18n-XJTStlKO.js → i18n-B1Q34rTV.js} +6 -6
- package/dist/assets/{markdown-render-C0rzRQ4M.js → markdown-render-B-UF5L3c.js} +9 -9
- package/dist/assets/{model-profiles-B-8HB7uC.js → model-profiles-Cq93mdbc.js} +1 -1
- package/dist/assets/options-DamSLmKe.css +1 -0
- package/dist/assets/options.js +72 -57
- package/dist/assets/{page-snapshot-renderer-BF9z-5DA.js → page-snapshot-renderer-I5Z-2PsZ.js} +1 -1
- package/dist/assets/{session-store-vZsITypR.js → session-store-KgAFlPe7.js} +4 -4
- package/dist/assets/side_panel.js +521 -498
- package/dist/assets/{utils-UyExxTOM.js → utils-kuoro4rx.js} +2 -2
- package/dist/assets/{version-jNC6oGN3.js → version-bJ7-5Neg.js} +1 -1
- package/dist/assets/{workspace-manager-BqgbuzqN.js → workspace-manager-LZpwqfIG.js} +1 -1
- package/dist/manifest.json +1 -1
- package/dist/offscreen/offscreen.js +6 -6
- package/dist/options.html +9 -5
- package/dist/side_panel.html +8 -8
- package/package.json +1 -1
- package/src/locales/en.json +2 -1
- package/src/locales/zh.json +2 -1
- package/src/memory/archive.js +169 -0
- package/src/memory/service.js +46 -18
- package/src/rag/export.js +202 -0
- package/src/rag/manager.js +63 -0
- package/src/rag/routes.js +44 -1
- package/src/search.js +134 -50
- package/src/server.js +60 -6
- package/src/skill/markdown-loader.js +20 -0
- package/dist/assets/options-CM9dPi9P.css +0 -1
package/src/rag/routes.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
// DELETE /api/rag/collections/{id} 删除知识库
|
|
13
13
|
// POST /api/rag/collections/{id}/toggle 切换启用/停用(停用:LLM 自主检索/导入排除,@ 手动引用仍可用)
|
|
14
14
|
// GET /api/rag/collections/{id}/stats 文档数/分块数统计
|
|
15
|
+
// GET /api/rag/collections/{id}/export 导出可恢复 ZIP 备份(原件 + 全文 + 元数据)
|
|
15
16
|
// POST /api/rag/collections/{id}/ingest 导入文档(text/file/url;同步执行)
|
|
16
17
|
// GET /api/rag/collections/{id}/ingest/status 导入进度快照(供导入弹窗轮询)
|
|
17
18
|
// GET /api/rag/collections/{id}/documents 文档列表
|
|
@@ -248,7 +249,7 @@ export async function ragRouter(req, res, pathname, url, t, body = {}, ctx = {})
|
|
|
248
249
|
|
|
249
250
|
// /api/rag/collections/{id}[/{sub}[/{docId}[/download]]]
|
|
250
251
|
const collectionMatch = pathname.match(
|
|
251
|
-
/^\/api\/rag\/collections\/([^/]+)(?:\/(stats|ingest|documents|search|toggle)(?:\/([^/]+)(?:\/(download))?)?)?$/
|
|
252
|
+
/^\/api\/rag\/collections\/([^/]+)(?:\/(stats|ingest|documents|search|toggle|export)(?:\/([^/]+)(?:\/(download))?)?)?$/
|
|
252
253
|
);
|
|
253
254
|
|
|
254
255
|
if (collectionMatch) {
|
|
@@ -291,6 +292,48 @@ export async function ragRouter(req, res, pathname, url, t, body = {}, ctx = {})
|
|
|
291
292
|
return handle(res, async () => ({ stats: await manager.getStats(collectionId) }));
|
|
292
293
|
}
|
|
293
294
|
|
|
295
|
+
// GET /api/rag/collections/{id}/export - 流式 ZIP;准备阶段失败仍返回 JSON 错误
|
|
296
|
+
if (method === 'GET' && sub === 'export' && !docId) {
|
|
297
|
+
let exported;
|
|
298
|
+
try {
|
|
299
|
+
exported = await manager.createCollectionExport(collectionId);
|
|
300
|
+
} catch (err) {
|
|
301
|
+
if (!(err instanceof RagError)) console.error('[RAG] export error:', err);
|
|
302
|
+
const { error, code } = translateRagError(err, t);
|
|
303
|
+
return jsonResponse(res, 400, { success: false, error, code });
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
try {
|
|
307
|
+
res.writeHead(200, {
|
|
308
|
+
...corsHeaders(res),
|
|
309
|
+
'Access-Control-Expose-Headers': 'Content-Disposition',
|
|
310
|
+
...attachmentHeaders('application/zip', exported.fileName),
|
|
311
|
+
});
|
|
312
|
+
exported.archive.on('error', (err) => {
|
|
313
|
+
console.error('[RAG] export stream failed:', err);
|
|
314
|
+
res.destroy(); // 头部已发出,只能中断下载,不能再改写 JSON 错误
|
|
315
|
+
});
|
|
316
|
+
// 客户端取消时停止读取原件,同时触发 archive close 释放知识库操作锁
|
|
317
|
+
res.once('close', () => {
|
|
318
|
+
if (!res.writableEnded) exported.archive.destroy();
|
|
319
|
+
});
|
|
320
|
+
exported.archive.pipe(res);
|
|
321
|
+
await exported.archive.finalize();
|
|
322
|
+
} catch (err) {
|
|
323
|
+
// 响应头可能已发出:此时只能中断连接,不能二次写 JSON
|
|
324
|
+
console.error('[RAG] export failed:', err);
|
|
325
|
+
exported.release();
|
|
326
|
+
exported.archive.destroy();
|
|
327
|
+
if (!res.headersSent) {
|
|
328
|
+
const { error, code } = translateRagError(err, t);
|
|
329
|
+
jsonResponse(res, 400, { success: false, error, code });
|
|
330
|
+
} else if (!res.writableEnded) {
|
|
331
|
+
res.destroy();
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
|
|
294
337
|
// POST /api/rag/collections/{id}/ingest - 导入文档(同步执行;执行期间进度经 /ingest/status 旁路轮询)
|
|
295
338
|
if (method === 'POST' && sub === 'ingest' && !docId) {
|
|
296
339
|
return handle(res, async () => {
|
package/src/search.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { spawn } from 'child_process';
|
|
3
3
|
import { readdir, stat, readFile } from 'fs/promises';
|
|
4
4
|
import { statSync } from 'fs';
|
|
5
|
-
import { join, basename, extname, resolve, isAbsolute } from 'path';
|
|
5
|
+
import { join, basename, extname, resolve, isAbsolute, relative, sep } from 'path';
|
|
6
6
|
import { checkPath } from './security.js';
|
|
7
7
|
import { t as translate } from './i18n.js';
|
|
8
8
|
|
|
@@ -88,6 +88,23 @@ const DEFAULT_IGNORE_DIRS = new Set([
|
|
|
88
88
|
'.idea', '.vscode', '.DS_Store'
|
|
89
89
|
]);
|
|
90
90
|
|
|
91
|
+
/**
|
|
92
|
+
* 命中任一排除 glob 时返回 true(用于回退实现,fd/rg 由原生参数处理)
|
|
93
|
+
* 支持目录型 glob(`dist/**`)与路径型 glob(`src/*.js`),与 fd/rg 语义对齐
|
|
94
|
+
*/
|
|
95
|
+
function isExcludedPath(relPath, name, excludeGlobs) {
|
|
96
|
+
if (!Array.isArray(excludeGlobs)) return false;
|
|
97
|
+
const normalized = relPath.split(sep).join('/');
|
|
98
|
+
return excludeGlobs.some((glob) => {
|
|
99
|
+
const stripped = glob.replace(/\/\*\*$/, '');
|
|
100
|
+
if (stripped !== glob) {
|
|
101
|
+
// 目录型 glob:命中目录自身或其下任意层级
|
|
102
|
+
return normalized === stripped || normalized.startsWith(`${stripped}/`);
|
|
103
|
+
}
|
|
104
|
+
return matchGlob(name, glob) || matchGlob(normalized, glob);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
91
108
|
/**
|
|
92
109
|
* 文件名模式匹配(支持 glob:*.js, test*.ts, ** / *.js 等)
|
|
93
110
|
*/
|
|
@@ -106,13 +123,17 @@ function matchGlob(filename, pattern) {
|
|
|
106
123
|
/**
|
|
107
124
|
* 使用 fd 搜索文件和目录(快速)
|
|
108
125
|
*/
|
|
109
|
-
function searchWithFd(rootPath, filePattern, recursive, maxResults) {
|
|
126
|
+
function searchWithFd(rootPath, filePattern, recursive, maxResults, excludeGlobs = []) {
|
|
110
127
|
return new Promise((resolve) => {
|
|
111
128
|
const args = ['--glob', filePattern, '--type', 'f', '--type', 'd', '--max-results', String(maxResults)];
|
|
112
129
|
// 排除默认忽略的目录
|
|
113
130
|
for (const dir of DEFAULT_IGNORE_DIRS) {
|
|
114
131
|
args.push('--exclude', dir);
|
|
115
132
|
}
|
|
133
|
+
// 调用方指定的排除 glob(fd 按名字匹配,目录型 glob 需去掉尾部 /**)
|
|
134
|
+
for (const glob of excludeGlobs) {
|
|
135
|
+
args.push('--exclude', glob.replace(/\/\*\*$/, ''));
|
|
136
|
+
}
|
|
116
137
|
if (!recursive) args.push('--max-depth', '1');
|
|
117
138
|
args.push(rootPath);
|
|
118
139
|
|
|
@@ -161,7 +182,7 @@ function yieldEventLoop() {
|
|
|
161
182
|
/**
|
|
162
183
|
* Node.js 原生递归搜索文件和目录(回退方案,异步 + 分片防止阻塞事件循环)
|
|
163
184
|
*/
|
|
164
|
-
async function searchFilesNative(rootPath, filePattern, recursive, maxResults) {
|
|
185
|
+
async function searchFilesNative(rootPath, filePattern, recursive, maxResults, excludeGlobs = []) {
|
|
165
186
|
const results = [];
|
|
166
187
|
|
|
167
188
|
async function walk(dir, depth) {
|
|
@@ -182,6 +203,7 @@ async function searchFilesNative(rootPath, filePattern, recursive, maxResults) {
|
|
|
182
203
|
if (entry.isDirectory()) {
|
|
183
204
|
if (DEFAULT_IGNORE_DIRS.has(entry.name)) continue;
|
|
184
205
|
if (entry.name.startsWith('.')) continue;
|
|
206
|
+
if (isExcludedPath(relative(rootPath, fullPath), entry.name, excludeGlobs)) continue;
|
|
185
207
|
// 目录也参与搜索匹配
|
|
186
208
|
if (matchGlob(entry.name, filePattern)) {
|
|
187
209
|
try {
|
|
@@ -193,6 +215,7 @@ async function searchFilesNative(rootPath, filePattern, recursive, maxResults) {
|
|
|
193
215
|
}
|
|
194
216
|
await walk(fullPath, depth + 1);
|
|
195
217
|
} else if (entry.isFile()) {
|
|
218
|
+
if (isExcludedPath(relative(rootPath, fullPath), entry.name, excludeGlobs)) continue;
|
|
196
219
|
if (matchGlob(entry.name, filePattern)) {
|
|
197
220
|
try {
|
|
198
221
|
const s = await stat(fullPath);
|
|
@@ -216,9 +239,10 @@ async function searchFilesNative(rootPath, filePattern, recursive, maxResults) {
|
|
|
216
239
|
* @param {boolean} recursive - 是否递归
|
|
217
240
|
* @param {number} maxResults - 最大结果数
|
|
218
241
|
* @param {Function} [tFn] - 可选的翻译函数(由 server.js 传入)
|
|
242
|
+
* @param {string[]} [excludeGlobs] - 排除的 glob 列表
|
|
219
243
|
* @returns {Array<{path, name, size, mtime}>}
|
|
220
244
|
*/
|
|
221
|
-
export async function searchFiles(rootPath, filePattern = '*', recursive = true, maxResults = 200, tFn, ctx = {}) {
|
|
245
|
+
export async function searchFiles(rootPath, filePattern = '*', recursive = true, maxResults = 200, tFn, ctx = {}, excludeGlobs = []) {
|
|
222
246
|
const pathCheck = await checkPath(rootPath, tFn, ctx);
|
|
223
247
|
if (!pathCheck.allowed) {
|
|
224
248
|
return { success: false, error: pathCheck.reason };
|
|
@@ -236,17 +260,24 @@ export async function searchFiles(rootPath, filePattern = '*', recursive = true,
|
|
|
236
260
|
return { success: false, error: tr('search.pathNotDir', undefined, tFn) };
|
|
237
261
|
}
|
|
238
262
|
|
|
239
|
-
|
|
263
|
+
// 按 mtime 倒序需要先在更大的集合里取,否则 fd 的预截断会让“最新文件”被随机排除
|
|
264
|
+
const fetchLimit = Math.min(Math.max(maxResults * 5, 500), 5000);
|
|
265
|
+
let raw;
|
|
240
266
|
if (fdAvailable) {
|
|
241
|
-
|
|
267
|
+
raw = await searchWithFd(resolved, filePattern, recursive, fetchLimit, excludeGlobs);
|
|
242
268
|
} else {
|
|
243
|
-
|
|
269
|
+
raw = await searchFilesNative(resolved, filePattern, recursive, fetchLimit, excludeGlobs);
|
|
244
270
|
}
|
|
271
|
+
raw.sort((a, b) => (b.mtime || 0) - (a.mtime || 0));
|
|
272
|
+
|
|
273
|
+
const truncated = raw.length > maxResults;
|
|
274
|
+
const results = truncated ? raw.slice(0, maxResults) : raw;
|
|
245
275
|
|
|
246
276
|
return {
|
|
247
277
|
success: true,
|
|
248
278
|
results,
|
|
249
279
|
total: results.length,
|
|
280
|
+
truncated,
|
|
250
281
|
engine: fdAvailable ? 'fd' : 'nodejs',
|
|
251
282
|
path: resolved,
|
|
252
283
|
pattern: filePattern
|
|
@@ -256,13 +287,17 @@ export async function searchFiles(rootPath, filePattern = '*', recursive = true,
|
|
|
256
287
|
/**
|
|
257
288
|
* 使用 rg 搜索文件内容(快速)
|
|
258
289
|
*/
|
|
259
|
-
function searchContentWithRg(rootPath, pattern, filePattern, caseSensitive, recursive, maxResults, contextLines) {
|
|
290
|
+
function searchContentWithRg(rootPath, pattern, filePattern, caseSensitive, recursive, maxResults, contextLines, excludeGlobs = []) {
|
|
260
291
|
return new Promise((resolve) => {
|
|
261
292
|
const args = [
|
|
262
|
-
|
|
263
|
-
'--
|
|
264
|
-
|
|
293
|
+
// --json 输出结构化事件,避免从文本行里区分「匹配行 / 上下文行」时的歧义
|
|
294
|
+
'--json',
|
|
295
|
+
// --max-count 是「每个文件」的上限;总量在调用方统一截断
|
|
296
|
+
'--max-count', String(maxResults + 1)
|
|
265
297
|
];
|
|
298
|
+
if (contextLines > 0) {
|
|
299
|
+
args.push('-C', String(contextLines));
|
|
300
|
+
}
|
|
266
301
|
// 大小写不敏感时添加 -i(与 searchContentNative 的 caseSensitive 语义对齐)
|
|
267
302
|
if (!caseSensitive) {
|
|
268
303
|
args.push('-i');
|
|
@@ -274,7 +309,21 @@ function searchContentWithRg(rootPath, pattern, filePattern, caseSensitive, recu
|
|
|
274
309
|
if (filePattern) {
|
|
275
310
|
args.push('--glob', filePattern);
|
|
276
311
|
}
|
|
277
|
-
|
|
312
|
+
// 默认忽略目录与 fd / Node 回退保持一致,不单纯依赖 .gitignore
|
|
313
|
+
for (const dir of DEFAULT_IGNORE_DIRS) {
|
|
314
|
+
args.push('--glob', `!**/${dir}`);
|
|
315
|
+
args.push('--glob', `!**/${dir}/**`);
|
|
316
|
+
}
|
|
317
|
+
// 调用方指定的排除 glob:同时覆盖 `dist/**` 与 `dist` 两种写法
|
|
318
|
+
for (const glob of excludeGlobs) {
|
|
319
|
+
args.push('--glob', `!${glob}`);
|
|
320
|
+
const stripped = glob.replace(/\/\*\*$/, '');
|
|
321
|
+
if (stripped !== glob) {
|
|
322
|
+
args.push('--glob', `!**/${stripped}/**`);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
// -e 显式指定模式,避免以 "-" 开头的 pattern 被当成命令行参数
|
|
326
|
+
args.push('-e', pattern, rootPath);
|
|
278
327
|
|
|
279
328
|
const proc = spawn('rg', args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
280
329
|
const stdout = [];
|
|
@@ -293,9 +342,9 @@ function searchContentWithRg(rootPath, pattern, filePattern, caseSensitive, recu
|
|
|
293
342
|
if (timedOut) return;
|
|
294
343
|
// 不再按退出码过滤:Windows 下 rg 可能返回退出码 2(错误)但仍带有效匹配结果,
|
|
295
344
|
// 原逻辑 `code !== 0 && code !== 1` 会把这种情况的输出一并丢弃,导致有匹配却返回 0 条。
|
|
296
|
-
// 只要 stdout 有内容就解析;stdout 为空时
|
|
345
|
+
// 只要 stdout 有内容就解析;stdout 为空时 parseRgJsonOutput 自然返回 []。
|
|
297
346
|
const output = Buffer.concat(stdout).toString('utf-8').trim();
|
|
298
|
-
resolve(
|
|
347
|
+
resolve(parseRgJsonOutput(output, contextLines));
|
|
299
348
|
});
|
|
300
349
|
|
|
301
350
|
proc.on('error', () => { clearTimeout(timeout); resolve([]); });
|
|
@@ -303,37 +352,59 @@ function searchContentWithRg(rootPath, pattern, filePattern, caseSensitive, recu
|
|
|
303
352
|
}
|
|
304
353
|
|
|
305
354
|
/**
|
|
306
|
-
* 解析 rg
|
|
307
|
-
*
|
|
308
|
-
*
|
|
355
|
+
* 解析 rg --json 输出(每行一个事件):
|
|
356
|
+
* match / context 事件都带 path、line_number、lines.text
|
|
357
|
+
* 先按文件收集行内容,再以命中的行号为基准取上下文窗口,
|
|
358
|
+
* 避免把内容里的 `:数字:` 误判成新的匹配行。
|
|
359
|
+
* 上下文结构与 Node.js 回退一致:context: [{ line, content, isMatch }]
|
|
309
360
|
*/
|
|
310
|
-
function
|
|
361
|
+
function parseRgJsonOutput(output, contextLines) {
|
|
311
362
|
if (!output) return [];
|
|
312
|
-
const lines = output.split('\n');
|
|
313
|
-
const results = [];
|
|
314
363
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
content: match[3]
|
|
326
|
-
});
|
|
364
|
+
const linesByFile = new Map(); // file -> Map<line, { content, isMatch }>
|
|
365
|
+
const matches = [];
|
|
366
|
+
|
|
367
|
+
for (const raw of output.split('\n')) {
|
|
368
|
+
if (!raw) continue;
|
|
369
|
+
let evt;
|
|
370
|
+
try {
|
|
371
|
+
evt = JSON.parse(raw);
|
|
372
|
+
} catch {
|
|
373
|
+
continue;
|
|
327
374
|
}
|
|
375
|
+
if (!evt || (evt.type !== 'match' && evt.type !== 'context')) continue;
|
|
376
|
+
|
|
377
|
+
const data = evt.data || {};
|
|
378
|
+
const file = data.path && data.path.text;
|
|
379
|
+
const line = data.line_number;
|
|
380
|
+
if (!file || !line) continue;
|
|
381
|
+
|
|
382
|
+
const content = ((data.lines && data.lines.text) || '').replace(/\n$/, '');
|
|
383
|
+
if (!linesByFile.has(file)) linesByFile.set(file, new Map());
|
|
384
|
+
linesByFile.get(file).set(line, { content, isMatch: evt.type === 'match' });
|
|
385
|
+
|
|
386
|
+
if (evt.type === 'match') matches.push({ file, line });
|
|
328
387
|
}
|
|
329
388
|
|
|
330
|
-
return
|
|
389
|
+
return matches.map(({ file, line }) => {
|
|
390
|
+
const map = linesByFile.get(file);
|
|
391
|
+
const item = { file, line, content: map.get(line).content };
|
|
392
|
+
if (contextLines > 0) {
|
|
393
|
+
const ctx = [];
|
|
394
|
+
for (let l = line - contextLines; l <= line + contextLines; l++) {
|
|
395
|
+
const entry = map.get(l);
|
|
396
|
+
if (entry) ctx.push({ line: l, content: entry.content, isMatch: l === line });
|
|
397
|
+
}
|
|
398
|
+
item.context = ctx;
|
|
399
|
+
}
|
|
400
|
+
return item;
|
|
401
|
+
});
|
|
331
402
|
}
|
|
332
403
|
|
|
333
404
|
/**
|
|
334
405
|
* Node.js 原生搜索文件内容(回退方案,异步 + 分片防止阻塞事件循环)
|
|
335
406
|
*/
|
|
336
|
-
async function searchContentNative(rootPath, pattern, filePattern, caseSensitive, recursive, maxResults, contextLines) {
|
|
407
|
+
async function searchContentNative(rootPath, pattern, filePattern, caseSensitive, recursive, maxResults, contextLines, excludeGlobs = []) {
|
|
337
408
|
const results = [];
|
|
338
409
|
const searchPattern = caseSensitive ? pattern : pattern.toLowerCase();
|
|
339
410
|
|
|
@@ -354,10 +425,12 @@ async function searchContentNative(rootPath, pattern, filePattern, caseSensitive
|
|
|
354
425
|
if (entry.isDirectory()) {
|
|
355
426
|
if (DEFAULT_IGNORE_DIRS.has(entry.name)) continue;
|
|
356
427
|
if (entry.name.startsWith('.')) continue;
|
|
428
|
+
if (isExcludedPath(relative(rootPath, fullPath), entry.name, excludeGlobs)) continue;
|
|
357
429
|
// 非递归搜索:跳过子目录,仅搜索当前目录下的文件
|
|
358
430
|
if (!recursive) continue;
|
|
359
431
|
await walk(fullPath);
|
|
360
432
|
} else if (entry.isFile()) {
|
|
433
|
+
if (isExcludedPath(relative(rootPath, fullPath), entry.name, excludeGlobs)) continue;
|
|
361
434
|
if (filePattern && !matchGlob(entry.name, filePattern)) continue;
|
|
362
435
|
// 跳过压缩和映射文件
|
|
363
436
|
if (entry.name.endsWith('.min.js')) continue;
|
|
@@ -374,18 +447,21 @@ async function searchContentNative(rootPath, pattern, filePattern, caseSensitive
|
|
|
374
447
|
if (results.length >= maxResults) break;
|
|
375
448
|
const line = caseSensitive ? fileLines[i] : fileLines[i].toLowerCase();
|
|
376
449
|
if (line.includes(searchPattern)) {
|
|
377
|
-
const
|
|
378
|
-
const start = Math.max(0, i - contextLines);
|
|
379
|
-
const end = Math.min(fileLines.length - 1, i + contextLines);
|
|
380
|
-
for (let j = start; j <= end; j++) {
|
|
381
|
-
ctx.push({ line: j + 1, content: fileLines[j], isMatch: j === i });
|
|
382
|
-
}
|
|
383
|
-
results.push({
|
|
450
|
+
const item = {
|
|
384
451
|
file: fullPath,
|
|
385
452
|
line: i + 1,
|
|
386
|
-
content: fileLines[i]
|
|
387
|
-
|
|
388
|
-
|
|
453
|
+
content: fileLines[i]
|
|
454
|
+
};
|
|
455
|
+
if (contextLines > 0) {
|
|
456
|
+
const ctx = [];
|
|
457
|
+
const start = Math.max(0, i - contextLines);
|
|
458
|
+
const end = Math.min(fileLines.length - 1, i + contextLines);
|
|
459
|
+
for (let j = start; j <= end; j++) {
|
|
460
|
+
ctx.push({ line: j + 1, content: fileLines[j], isMatch: j === i });
|
|
461
|
+
}
|
|
462
|
+
item.context = ctx;
|
|
463
|
+
}
|
|
464
|
+
results.push(item);
|
|
389
465
|
}
|
|
390
466
|
}
|
|
391
467
|
} catch {}
|
|
@@ -405,11 +481,12 @@ async function searchContentNative(rootPath, pattern, filePattern, caseSensitive
|
|
|
405
481
|
* @param {boolean} caseSensitive - 是否大小写敏感
|
|
406
482
|
* @param {boolean} recursive - 是否递归搜索子目录
|
|
407
483
|
* @param {number} maxResults - 最大结果数
|
|
408
|
-
* @param {number} contextLines -
|
|
484
|
+
* @param {number} contextLines - 上下文行数(0-5)
|
|
409
485
|
* @param {Function} [tFn] - 可选的翻译函数(由 server.js 传入)
|
|
410
|
-
* @
|
|
486
|
+
* @param {string[]} [excludeGlobs] - 排除的 glob 列表
|
|
487
|
+
* @returns {{ success: boolean, results: Array, total: number, truncated: boolean, engine: string }}
|
|
411
488
|
*/
|
|
412
|
-
export async function searchContent(rootPath, pattern, filePattern = null, caseSensitive = false, recursive = true, maxResults = 100, contextLines =
|
|
489
|
+
export async function searchContent(rootPath, pattern, filePattern = null, caseSensitive = false, recursive = true, maxResults = 100, contextLines = 0, tFn, ctx = {}, excludeGlobs = []) {
|
|
413
490
|
const pathCheck = await checkPath(rootPath, tFn, ctx);
|
|
414
491
|
if (!pathCheck.allowed) {
|
|
415
492
|
return { success: false, error: pathCheck.reason };
|
|
@@ -426,17 +503,24 @@ export async function searchContent(rootPath, pattern, filePattern = null, caseS
|
|
|
426
503
|
return { success: false, error: tr('search.emptyPattern', undefined, tFn) };
|
|
427
504
|
}
|
|
428
505
|
|
|
429
|
-
|
|
506
|
+
const ctxLines = Math.max(0, Math.min(Number(contextLines) || 0, 5));
|
|
507
|
+
|
|
508
|
+
let raw;
|
|
430
509
|
if (rgAvailable) {
|
|
431
|
-
|
|
510
|
+
raw = await searchContentWithRg(resolved, pattern, filePattern, caseSensitive, recursive, maxResults + 1, ctxLines, excludeGlobs);
|
|
432
511
|
} else {
|
|
433
|
-
|
|
512
|
+
raw = await searchContentNative(resolved, pattern, filePattern, caseSensitive, recursive, maxResults + 1, ctxLines, excludeGlobs);
|
|
434
513
|
}
|
|
435
514
|
|
|
515
|
+
// 统一按总量截断(rg 的 --max-count 只是单文件上限)
|
|
516
|
+
const truncated = raw.length > maxResults;
|
|
517
|
+
const results = truncated ? raw.slice(0, maxResults) : raw;
|
|
518
|
+
|
|
436
519
|
return {
|
|
437
520
|
success: true,
|
|
438
521
|
results,
|
|
439
522
|
total: results.length,
|
|
523
|
+
truncated,
|
|
440
524
|
engine: rgAvailable ? 'rg' : 'nodejs',
|
|
441
525
|
path: resolved,
|
|
442
526
|
pattern
|
package/src/server.js
CHANGED
|
@@ -67,7 +67,7 @@ import {
|
|
|
67
67
|
} from './skill/registry.js';
|
|
68
68
|
import { saveMarkdownSkill, importMarkdownSkillFromZip, importMarkdownSkillFromUrl, setSkillLoaderLang } from './skill/loader.js';
|
|
69
69
|
import { setSkillExecutorLang } from './skill/executor.js';
|
|
70
|
-
import { setMarkdownLoaderLang } from './skill/markdown-loader.js';
|
|
70
|
+
import { exportMarkdownSkillToZip, setMarkdownLoaderLang } from './skill/markdown-loader.js';
|
|
71
71
|
import { setMcpClientLang } from './mcp/client.js';
|
|
72
72
|
import { getRequestI18n, t, parseAcceptLanguage } from './i18n.js';
|
|
73
73
|
import { pickDirectoryNative, cancelPickDirectory } from './directory-picker.js';
|
|
@@ -157,6 +157,32 @@ const PID_FILE = join(homedir(), '.ai-helper-agent', 'agent.pid');
|
|
|
157
157
|
const DEFAULT_MAX_SIZE = 50 * 1024 * 1024; // 文件默认大小限制(read/list 等读取操作)
|
|
158
158
|
const MAX_UPLOAD_SIZE = 200 * 1024 * 1024; // 流式上传最大 200MB(与 MAX_BODY_SIZE 一致,流式无 base64 膨胀,实际可传 200MB 原文件)
|
|
159
159
|
|
|
160
|
+
/**
|
|
161
|
+
* 规范化调用方传入的排除 glob:仅接受字符串数组,限制数量与单条长度
|
|
162
|
+
* @param {*} raw
|
|
163
|
+
* @returns {string[]}
|
|
164
|
+
*/
|
|
165
|
+
function sanitizeExcludeGlobs(raw) {
|
|
166
|
+
// 兼容调用方误传单个字符串的情况
|
|
167
|
+
const list = Array.isArray(raw) ? raw : (typeof raw === 'string' ? [raw] : []);
|
|
168
|
+
return list
|
|
169
|
+
.filter(g => typeof g === 'string' && g.trim())
|
|
170
|
+
.map(g => g.trim().slice(0, 200))
|
|
171
|
+
.slice(0, 20);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* 规范化 maxResults:非数字/非正数回退默认值,并限制上限
|
|
176
|
+
* @param {*} raw
|
|
177
|
+
* @param {number} fallback
|
|
178
|
+
* @returns {number}
|
|
179
|
+
*/
|
|
180
|
+
function normalizeMaxResults(raw, fallback) {
|
|
181
|
+
const n = Number(raw);
|
|
182
|
+
if (!Number.isFinite(n) || n < 1) return fallback;
|
|
183
|
+
return Math.min(Math.floor(n), MAX_SEARCH_RESULTS);
|
|
184
|
+
}
|
|
185
|
+
|
|
160
186
|
function detectShell() {
|
|
161
187
|
const platform = os.platform();
|
|
162
188
|
const envShell = process.env.SHELL || process.env.COMSPEC || '';
|
|
@@ -1394,7 +1420,8 @@ export function startServer() {
|
|
|
1394
1420
|
|
|
1395
1421
|
// 搜索文件(按文件名模式)
|
|
1396
1422
|
if (pathname === '/api/fs/search_files') {
|
|
1397
|
-
const maxResults =
|
|
1423
|
+
const maxResults = normalizeMaxResults(body.maxResults, 200);
|
|
1424
|
+
const excludeGlobs = sanitizeExcludeGlobs(body.excludeGlobs);
|
|
1398
1425
|
try {
|
|
1399
1426
|
const result = await searchFiles(
|
|
1400
1427
|
body.path || '.',
|
|
@@ -1402,7 +1429,8 @@ export function startServer() {
|
|
|
1402
1429
|
body.recursive !== false,
|
|
1403
1430
|
maxResults,
|
|
1404
1431
|
t,
|
|
1405
|
-
scope
|
|
1432
|
+
scope,
|
|
1433
|
+
excludeGlobs
|
|
1406
1434
|
);
|
|
1407
1435
|
if (result.success) {
|
|
1408
1436
|
logFs('search_files', { path: result.path, pattern: body.pattern, total: result.total, engine: result.engine });
|
|
@@ -1418,7 +1446,9 @@ export function startServer() {
|
|
|
1418
1446
|
|
|
1419
1447
|
// 搜索文件内容
|
|
1420
1448
|
if (pathname === '/api/fs/search_content') {
|
|
1421
|
-
const maxResults =
|
|
1449
|
+
const maxResults = normalizeMaxResults(body.maxResults, 100);
|
|
1450
|
+
const contextLines = Math.max(0, Math.min(Number(body.contextLines) || 0, 5));
|
|
1451
|
+
const excludeGlobs = sanitizeExcludeGlobs(body.excludeGlobs);
|
|
1422
1452
|
try {
|
|
1423
1453
|
const result = await searchContent(
|
|
1424
1454
|
body.path || '.',
|
|
@@ -1427,9 +1457,10 @@ export function startServer() {
|
|
|
1427
1457
|
body.caseSensitive || false,
|
|
1428
1458
|
body.recursive !== false,
|
|
1429
1459
|
maxResults,
|
|
1430
|
-
|
|
1460
|
+
contextLines,
|
|
1431
1461
|
t,
|
|
1432
|
-
scope
|
|
1462
|
+
scope,
|
|
1463
|
+
excludeGlobs
|
|
1433
1464
|
);
|
|
1434
1465
|
if (result.success) {
|
|
1435
1466
|
logFs('search_content', { path: result.path, pattern: body.pattern, total: result.total, engine: result.engine });
|
|
@@ -2420,6 +2451,29 @@ export function startServer() {
|
|
|
2420
2451
|
return jsonResponse(res, result.success ? 200 : 404, result);
|
|
2421
2452
|
}
|
|
2422
2453
|
|
|
2454
|
+
// 导出 Agent Skill ZIP(base64 编码,包含 SKILL.md 与全部资源)
|
|
2455
|
+
if (req.method === 'GET' && pathname === '/api/skill/export') {
|
|
2456
|
+
const name = url.searchParams.get('name');
|
|
2457
|
+
if (!name) return jsonResponse(res, 400, { success: false, error: t('error.missingName') });
|
|
2458
|
+
const result = getSkill(name);
|
|
2459
|
+
if (!result.success) return jsonResponse(res, 404, result);
|
|
2460
|
+
const skill = result.skill;
|
|
2461
|
+
if (skill.type !== 'agent') {
|
|
2462
|
+
return jsonResponse(res, 400, { success: false, error: t('error.notAgentSkill') });
|
|
2463
|
+
}
|
|
2464
|
+
try {
|
|
2465
|
+
const zipBuffer = await exportMarkdownSkillToZip(skill.dirPath);
|
|
2466
|
+
const skillDirName = basename(skill.dirPath);
|
|
2467
|
+
return jsonResponse(res, 200, {
|
|
2468
|
+
success: true,
|
|
2469
|
+
fileName: `${skillDirName}.zip`,
|
|
2470
|
+
zipData: zipBuffer.toString('base64')
|
|
2471
|
+
});
|
|
2472
|
+
} catch (err) {
|
|
2473
|
+
return jsonResponse(res, 500, { success: false, error: t('error.packFailed', { message: err.message }) });
|
|
2474
|
+
}
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2423
2477
|
// Agent Skill 的 SKILL.md 内容
|
|
2424
2478
|
if (req.method === 'GET' && pathname === '/api/skill/markdown') {
|
|
2425
2479
|
const name = url.searchParams.get('name');
|
|
@@ -6,6 +6,7 @@ import { inflateRawSync } from 'zlib';
|
|
|
6
6
|
import { randomBytes } from 'crypto';
|
|
7
7
|
import { tmpdir } from 'os';
|
|
8
8
|
import { lookup as dnsLookup } from 'dns/promises';
|
|
9
|
+
import { ZipArchive } from 'archiver';
|
|
9
10
|
import https from 'https';
|
|
10
11
|
import http from 'http';
|
|
11
12
|
import { t as translate } from '../i18n.js';
|
|
@@ -473,6 +474,25 @@ function extractZipPureJs(zipBuffer, destDir) {
|
|
|
473
474
|
}
|
|
474
475
|
}
|
|
475
476
|
|
|
477
|
+
/**
|
|
478
|
+
* 将 Markdown Skill 目录打包为 ZIP,保留顶层技能目录与原始文件内容
|
|
479
|
+
* @param {string} skillDir - 技能根目录
|
|
480
|
+
* @returns {Promise<Buffer>} ZIP 文件 Buffer
|
|
481
|
+
*/
|
|
482
|
+
export async function exportMarkdownSkillToZip(skillDir) {
|
|
483
|
+
return new Promise((resolve, reject) => {
|
|
484
|
+
const archive = new ZipArchive({ zlib: { level: 9 } });
|
|
485
|
+
const chunks = [];
|
|
486
|
+
|
|
487
|
+
archive.on('data', chunk => chunks.push(chunk));
|
|
488
|
+
archive.on('end', () => resolve(Buffer.concat(chunks)));
|
|
489
|
+
archive.on('error', reject);
|
|
490
|
+
|
|
491
|
+
archive.directory(skillDir, basename(skillDir));
|
|
492
|
+
archive.finalize();
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
|
|
476
496
|
/**
|
|
477
497
|
* 从 Zip 文件导入 Skill
|
|
478
498
|
* 要求 zip 包内有一个顶层目录,目录中包含 SKILL.md
|