ai-helper-agent 2.5.1 → 2.5.2
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-D0oEv0PW.js → agent-store-TSvufiWG.js} +1 -1
- package/dist/assets/background.js +71 -70
- package/dist/assets/{chat-export-MTTSSIwM.js → chat-export-BFXv3fdM.js} +1 -1
- package/dist/assets/content.js +43 -43
- package/dist/{dist/assets/i18n-Br_sF5pb.js → assets/i18n-DJ3tjLY-.js} +4 -4
- package/dist/{dist/assets/markdown-render-lSSxW953.js → assets/markdown-render-C9SKCrR4.js} +4 -4
- package/dist/assets/{model-profiles-BdQaV4EZ.js → model-profiles-CfvHSLkL.js} +1 -1
- package/dist/{dist/assets/options-JtYgxtsc.css → assets/options-DU7Wz1w_.css} +1 -1
- package/dist/assets/options.js +89 -89
- package/dist/assets/{page-snapshot-renderer-Cl0qk7U1.js → page-snapshot-renderer-Cdzmf6hl.js} +1 -1
- package/dist/assets/session-store-CRTEYLCo.js +81 -0
- package/dist/assets/side_panel.css +1 -1
- package/dist/assets/side_panel.js +219 -215
- package/dist/{dist/assets/utils-ZJjxSlg_.js → assets/utils-DukUruXz.js} +26 -26
- package/dist/assets/{version-C0CY79zF.js → version-s8LDcTZ-.js} +1 -1
- package/dist/assets/voice-shortcut-Dtt3nhkz.js +1 -0
- package/dist/assets/workspace-manager-CgkNrxoo.js +1 -0
- package/dist/manifest.json +1 -1
- package/dist/offscreen/offscreen.js +6 -6
- package/dist/options.html +34 -4
- package/dist/side_panel.html +22 -13
- package/package.json +1 -1
- package/src/asr/install.js +26 -0
- package/src/documents/routes.js +4 -3
- package/src/locales/en.json +10 -1
- package/src/locales/zh.json +10 -1
- package/src/native-lib-guard.js +194 -0
- package/src/rag/embedding/embed-worker.mjs +182 -0
- package/src/rag/embedding/local.js +42 -62
- package/src/rag/embedding/worker-client.js +476 -0
- package/src/rag/errors.js +60 -2
- package/src/rag/install.js +27 -0
- package/src/rag/manager.js +5 -2
- package/src/rag/routes.js +4 -2
- package/src/search.js +4 -4
- package/src/security.js +97 -33
- package/src/server.js +284 -40
- package/src/session-workdirs.js +241 -0
- package/src/skill/executor.js +25 -9
- package/src/skill/registry.js +3 -2
- package/dist/assets/i18n-Br_sF5pb.js +0 -49
- package/dist/assets/markdown-render-Dq5F_dqP.js +0 -63
- package/dist/assets/options-JtYgxtsc.css +0 -1
- package/dist/assets/session-store-KkrAlIc6.js +0 -81
- package/dist/assets/utils-ZJjxSlg_.js +0 -112
- package/dist/dist/_locales/en/messages.json +0 -11
- package/dist/dist/_locales/zh_CN/messages.json +0 -11
- package/dist/dist/assets/__vite-browser-external-CM3Eme-n.js +0 -1
- package/dist/dist/assets/agent-store-D0oEv0PW.js +0 -1
- package/dist/dist/assets/background.js +0 -451
- package/dist/dist/assets/chat-export-7wjGjcA8.js +0 -37
- package/dist/dist/assets/chunk-CMxvf4Kt.js +0 -1
- package/dist/dist/assets/content.js +0 -985
- package/dist/dist/assets/dist-BUuoW_84.js +0 -24
- package/dist/dist/assets/dist-DuuG_8Br.js +0 -133
- package/dist/dist/assets/jszip.min-DO6SOhXU.js +0 -2
- package/dist/dist/assets/lib-YwkWjNcC.js +0 -220
- package/dist/dist/assets/marked.min.js-D2rXgLAQ.js +0 -56
- package/dist/dist/assets/marked.min.js-loader-tKH5SQVQ.js +0 -13
- package/dist/dist/assets/model-profiles-BdQaV4EZ.js +0 -24
- package/dist/dist/assets/network-scope-CNRYXk74.js +0 -1
- package/dist/dist/assets/options.js +0 -859
- package/dist/dist/assets/page-snapshot-renderer-Cl0qk7U1.js +0 -3
- package/dist/dist/assets/pdf-DnVqBaAN.js +0 -6
- package/dist/dist/assets/session-store-KkrAlIc6.js +0 -81
- package/dist/dist/assets/side_panel.css +0 -1
- package/dist/dist/assets/side_panel.js +0 -2595
- package/dist/dist/assets/theme-BRAX5X2F.css +0 -1
- package/dist/dist/assets/theme-CLwYsx9o.js +0 -1
- package/dist/dist/assets/version-C7x4HYX1.js +0 -1
- package/dist/dist/assets/xlsx-DGkz7cnk.js +0 -105
- package/dist/dist/icons/README.md +0 -11
- package/dist/dist/icons/design-philosophy.md +0 -41
- package/dist/dist/icons/icon128.png +0 -0
- package/dist/dist/icons/icon128.svg +0 -68
- package/dist/dist/icons/icon16.png +0 -0
- package/dist/dist/icons/icon16.svg +0 -32
- package/dist/dist/icons/icon48.png +0 -0
- package/dist/dist/icons/icon48.svg +0 -56
- package/dist/dist/libs/github-markdown-light.min.css +0 -8
- package/dist/dist/libs/html2canvas.min.js +0 -20
- package/dist/dist/libs/jspdf.min.js +0 -398
- package/dist/dist/libs/marked.min.js +0 -69
- package/dist/dist/libs/mermaid.min.js +0 -2024
- package/dist/dist/libs/pdf.worker.min.js +0 -22
- package/dist/dist/libs/qrcode.min.js +0 -7
- package/dist/dist/manifest.json +0 -94
- package/dist/dist/offscreen/offscreen.html +0 -11
- package/dist/dist/offscreen/offscreen.js +0 -49
- package/dist/dist/options.html +0 -1091
- package/dist/dist/service-worker-loader.js +0 -1
- package/dist/dist/side_panel.html +0 -1357
- package/dist/dist/styles/styles.css +0 -262
- package/dist/dist/voice-capture-worklet.js +0 -47
package/dist/options.html
CHANGED
|
@@ -5,13 +5,14 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
6
6
|
<title data-i18n="settings.docTitle">AI Helper - 配置</title>
|
|
7
7
|
<script type="module" crossorigin src="/assets/theme-CLwYsx9o.js"></script>
|
|
8
|
-
<script type="module" crossorigin src="/assets/i18n-
|
|
9
|
-
<script type="module" crossorigin src="/assets/model-profiles-
|
|
10
|
-
<script type="module" crossorigin src="/assets/version-
|
|
8
|
+
<script type="module" crossorigin src="/assets/i18n-DJ3tjLY-.js"></script>
|
|
9
|
+
<script type="module" crossorigin src="/assets/model-profiles-CfvHSLkL.js"></script>
|
|
10
|
+
<script type="module" crossorigin src="/assets/version-s8LDcTZ-.js"></script>
|
|
11
11
|
<script type="module" crossorigin src="/assets/network-scope-CNRYXk74.js"></script>
|
|
12
|
+
<script type="module" crossorigin src="/assets/voice-shortcut-Dtt3nhkz.js"></script>
|
|
12
13
|
<script type="module" crossorigin src="/assets/options.js"></script>
|
|
13
14
|
<link rel="stylesheet" crossorigin href="/assets/theme-BRAX5X2F.css">
|
|
14
|
-
<link rel="stylesheet" crossorigin href="/assets/options-
|
|
15
|
+
<link rel="stylesheet" crossorigin href="/assets/options-DU7Wz1w_.css">
|
|
15
16
|
</head>
|
|
16
17
|
<body>
|
|
17
18
|
<div class="container">
|
|
@@ -841,6 +842,35 @@
|
|
|
841
842
|
</div>
|
|
842
843
|
</div>
|
|
843
844
|
</div>
|
|
845
|
+
|
|
846
|
+
<!-- 快捷触发:纯扩展侧偏好(chrome.storage.local),不依赖代理端,所以独立成块、
|
|
847
|
+
不跟随语音总开关收起 —— 代理离线 / 还没装模型时也能先把键位配好
|
|
848
|
+
Alt+V 不在可配范围内:它是既定习惯,这里的勾选只决定「额外的单键」 -->
|
|
849
|
+
<div class="toolbox-section" id="asrShortcutSection">
|
|
850
|
+
<div class="toolbox-section-header">
|
|
851
|
+
<div class="toolbox-section-title-row">
|
|
852
|
+
<h2 class="toolbox-section-title" data-i18n="toolbox.asrShortcutTitle">⌨️ 快捷触发</h2>
|
|
853
|
+
</div>
|
|
854
|
+
<span class="toolbox-section-desc" data-i18n="toolbox.asrShortcutDesc">Alt+V 始终可用,不受下面勾选影响。勾上右侧单键后,单击(按下再松开)即可开始 / 结束录音;两个都勾 = 任一都能触发。侧边栏与网页里同时生效,改完立即生效、无需重启。</span>
|
|
855
|
+
</div>
|
|
856
|
+
<div class="asr-shortcut-list">
|
|
857
|
+
<label class="asr-shortcut-item">
|
|
858
|
+
<input type="checkbox" id="asrShortcutRightAlt">
|
|
859
|
+
<span class="asr-shortcut-text">
|
|
860
|
+
<span class="asr-shortcut-name" data-i18n="toolbox.asrShortcutRightAlt">右侧 Alt</span>
|
|
861
|
+
<span class="asr-shortcut-hint" data-i18n="toolbox.asrShortcutRightAltHint">macOS 上为右侧 Option ⌥;按住它再敲其它键不会触发</span>
|
|
862
|
+
</span>
|
|
863
|
+
</label>
|
|
864
|
+
<label class="asr-shortcut-item">
|
|
865
|
+
<input type="checkbox" id="asrShortcutRightCtrl">
|
|
866
|
+
<span class="asr-shortcut-text">
|
|
867
|
+
<span class="asr-shortcut-name" data-i18n="toolbox.asrShortcutRightCtrl">右侧 Ctrl</span>
|
|
868
|
+
<span class="asr-shortcut-hint" data-i18n="toolbox.asrShortcutRightCtrlHint">多数键盘的右侧 Ctrl 都是闲置的;同样只有单按才触发</span>
|
|
869
|
+
</span>
|
|
870
|
+
</label>
|
|
871
|
+
</div>
|
|
872
|
+
<div class="asr-shortcut-note" data-i18n="toolbox.asrShortcutNote">仅在语音输入已就绪(依赖 × 模型 × 开关)时响应;未就绪时按键不会开始录音。</div>
|
|
873
|
+
</div>
|
|
844
874
|
</div><!-- /tab-voice -->
|
|
845
875
|
|
|
846
876
|
<!-- 知识库管理 -->
|
package/dist/side_panel.html
CHANGED
|
@@ -6,13 +6,15 @@
|
|
|
6
6
|
<title data-i18n="header.docTitle">AI Helper - 模型问答</title>
|
|
7
7
|
<script type="module" crossorigin src="/assets/theme-CLwYsx9o.js"></script>
|
|
8
8
|
<script type="module" crossorigin src="/assets/chunk-CMxvf4Kt.js"></script>
|
|
9
|
-
<script type="module" crossorigin src="/assets/i18n-
|
|
10
|
-
<script type="module" crossorigin src="/assets/model-profiles-
|
|
11
|
-
<script type="module" crossorigin src="/assets/session-store-
|
|
12
|
-
<script type="module" crossorigin src="/assets/version-
|
|
13
|
-
<script type="module" crossorigin src="/assets/agent-store-
|
|
14
|
-
<script type="module" crossorigin src="/assets/utils-
|
|
15
|
-
<script type="module" crossorigin src="/assets/markdown-render-
|
|
9
|
+
<script type="module" crossorigin src="/assets/i18n-DJ3tjLY-.js"></script>
|
|
10
|
+
<script type="module" crossorigin src="/assets/model-profiles-CfvHSLkL.js"></script>
|
|
11
|
+
<script type="module" crossorigin src="/assets/session-store-CRTEYLCo.js"></script>
|
|
12
|
+
<script type="module" crossorigin src="/assets/version-s8LDcTZ-.js"></script>
|
|
13
|
+
<script type="module" crossorigin src="/assets/agent-store-TSvufiWG.js"></script>
|
|
14
|
+
<script type="module" crossorigin src="/assets/utils-DukUruXz.js"></script>
|
|
15
|
+
<script type="module" crossorigin src="/assets/markdown-render-C9SKCrR4.js"></script>
|
|
16
|
+
<script type="module" crossorigin src="/assets/voice-shortcut-Dtt3nhkz.js"></script>
|
|
17
|
+
<script type="module" crossorigin src="/assets/workspace-manager-CgkNrxoo.js"></script>
|
|
16
18
|
<script type="module" crossorigin src="/assets/side_panel.js"></script>
|
|
17
19
|
<link rel="stylesheet" crossorigin href="/assets/theme-BRAX5X2F.css">
|
|
18
20
|
<link rel="stylesheet" crossorigin href="/assets/side_panel.css">
|
|
@@ -767,12 +769,19 @@
|
|
|
767
769
|
<div id="fileAtList"></div>
|
|
768
770
|
</div>
|
|
769
771
|
</div>
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
<
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
772
|
+
<!-- 输入区信息带:上下文占用 / 本会话工作目录 / 免责声明 / 模型名,同一行 flex 排布 -->
|
|
773
|
+
<div class="input-meta-band" id="inputMetaBand">
|
|
774
|
+
<button id="contextUsageIndicator" class="context-usage-indicator" type="button" data-level="safe">
|
|
775
|
+
<span class="context-usage-ring" aria-hidden="true"></span>
|
|
776
|
+
<span class="context-usage-percent">--%</span>
|
|
777
|
+
</button>
|
|
778
|
+
<button id="workdirTag" class="workdir-tag" type="button" style="display: none;">
|
|
779
|
+
<svg class="workdir-tag-icon" viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h3.6l2 2H19a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"/></svg>
|
|
780
|
+
<span class="workdir-tag-name" id="workdirTagName"></span>
|
|
781
|
+
</button>
|
|
782
|
+
<div class="input-disclaimer" data-i18n="input.aiDisclaimer">内容由 AI 生成,仅供参考</div>
|
|
783
|
+
<button id="currentModelTag" class="current-model-tag" type="button"></button>
|
|
784
|
+
</div>
|
|
776
785
|
<div class="queue-strip" id="queueStrip" style="display:none;">
|
|
777
786
|
<div class="queue-strip-head">
|
|
778
787
|
<span class="queue-strip-icon" aria-hidden="true">⇥</span>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ai-helper-agent",
|
|
3
|
-
"version": "2.5.
|
|
3
|
+
"version": "2.5.2",
|
|
4
4
|
"description": "AI Helper Agent - Local file access and system command execution proxy for Chrome extension / AI Helper 代理服务,为 Chrome 扩展提供本地文件读写和系统命令执行",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/server.js",
|
package/src/asr/install.js
CHANGED
|
@@ -21,6 +21,7 @@ import { homedir } from 'os';
|
|
|
21
21
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
|
22
22
|
import { resetAsrDetection, detectAsrAvailable, getLastAsrProbeError } from './detect.js';
|
|
23
23
|
import { stopProcessTree } from '../process-tree.js';
|
|
24
|
+
import { pruneNativeDuplicates, summarizePruneReport } from '../native-lib-guard.js';
|
|
24
25
|
import { logSystem } from '../logger.js';
|
|
25
26
|
import { t as translate, parseAcceptLanguage } from '../i18n.js';
|
|
26
27
|
import { getRegistryUrl } from '../install-mode.js';
|
|
@@ -351,6 +352,31 @@ async function runInstall(task, t) {
|
|
|
351
352
|
return;
|
|
352
353
|
}
|
|
353
354
|
|
|
355
|
+
// 安装后收口(Windows 必做):ASR 安装会重算整个包目录的依赖树,可能把 onnxruntime-node
|
|
356
|
+
// 嵌套装进 @huggingface/transformers/node_modules;两份 onnxruntime.dll 同进程会抢句柄,
|
|
357
|
+
// 把知识库的本地向量打挂(cannot run %1)。详见 native-lib-guard.js 文件头。
|
|
358
|
+
//
|
|
359
|
+
// 先关掉 embedding 子进程:Windows 上已被映射的 onnxruntime.dll 在进程退出前删不掉,
|
|
360
|
+
// 子进程还活着(在途请求 / 空闲回收窗口内)时删除会拿到 EPERM/EBUSY,
|
|
361
|
+
// → 嵌套副本没清掉 → 用户「重启代理」也不收敛。
|
|
362
|
+
try {
|
|
363
|
+
const { closeEmbedWorker } = await import('../rag/embedding/worker-client.js');
|
|
364
|
+
await closeEmbedWorker();
|
|
365
|
+
} catch { /* 从未启动或已关闭 */ }
|
|
366
|
+
|
|
367
|
+
const repair = pruneNativeDuplicates(getAgentRoot());
|
|
368
|
+
const repairSummary = summarizePruneReport(repair);
|
|
369
|
+
if (repairSummary) {
|
|
370
|
+
task.logTail.push(`[deps] ${repairSummary}`);
|
|
371
|
+
if (task.logTail.length > LOG_TAIL_LIMIT) task.logTail = task.logTail.slice(-LOG_TAIL_LIMIT);
|
|
372
|
+
logSystem('asr_native_dedupe', { removed: repair.removed.length, failed: repair.failed.length });
|
|
373
|
+
}
|
|
374
|
+
if (repair.failed.length > 0) {
|
|
375
|
+
// 删除失败(文件被占/权限)不判安装失败,但必须留下可诊断痕迹:
|
|
376
|
+
// 否则安装显示 success、磁盘上依旧是两份,问题只能靠用户反馈才能发现
|
|
377
|
+
logSystem('asr_native_dedupe_failed', { failed: repair.failed });
|
|
378
|
+
}
|
|
379
|
+
|
|
354
380
|
// npm 退出码 0 → 子进程重新探测(以真实加载结果为准,避免假成功)
|
|
355
381
|
task.phase = 'verifying';
|
|
356
382
|
resetAsrDetection();
|
package/src/documents/routes.js
CHANGED
|
@@ -10,17 +10,18 @@ const EXTRACT_MAX_FILE_BYTES = 50 * 1024 * 1024;
|
|
|
10
10
|
/**
|
|
11
11
|
* POST /api/documents/extract-images 处理器
|
|
12
12
|
* @param {object} body { path, maxImages? }
|
|
13
|
-
* @param {{ t?: Function, checkPathOverride?: Function }} [opts]
|
|
13
|
+
* @param {{ t?: Function, checkPathOverride?: Function, sessionCtx?: { sessionId?: string, workdir?: string } }} [opts]
|
|
14
|
+
* checkPathOverride 仅供单测注入;sessionCtx 为请求级会话上下文(会话级工作目录)
|
|
14
15
|
* @returns {Promise<{ status: number, payload: object }>}
|
|
15
16
|
*/
|
|
16
|
-
export async function extractImagesHandler(body = {}, { t, checkPathOverride } = {}) {
|
|
17
|
+
export async function extractImagesHandler(body = {}, { t, checkPathOverride, sessionCtx } = {}) {
|
|
17
18
|
const tt = typeof t === 'function' ? t : (k) => k;
|
|
18
19
|
const path = body.path;
|
|
19
20
|
if (!path || typeof path !== 'string') return { status: 400, payload: { success: false, error: 'missingPath' } };
|
|
20
21
|
const ext = extname(path).toLowerCase();
|
|
21
22
|
if (ext !== '.docx') return { status: 400, payload: { success: false, error: 'unsupportedFormat' } };
|
|
22
23
|
|
|
23
|
-
const check = await (checkPathOverride || checkPath)(path, tt);
|
|
24
|
+
const check = await (checkPathOverride || checkPath)(path, tt, sessionCtx || {});
|
|
24
25
|
if (!check.allowed) return { status: 403, payload: { success: false, error: check.reason } };
|
|
25
26
|
const resolved = check.resolved;
|
|
26
27
|
|
package/src/locales/en.json
CHANGED
|
@@ -7,8 +7,13 @@
|
|
|
7
7
|
"operationInProgress": "An operation is already in progress, please try again later",
|
|
8
8
|
"missingPath": "Missing path parameter",
|
|
9
9
|
"missingWorkdir": "Missing workdir parameter",
|
|
10
|
+
"invalidSessionId": "Invalid session identifier",
|
|
11
|
+
"invalidScope": "scope must be either session or global",
|
|
12
|
+
"workdirNotInSessionScope": "Path is outside this session's working directory ({workdir})",
|
|
10
13
|
"workdirNotAbsolute": "workdir must be an absolute path",
|
|
11
14
|
"workdirIsSystemDir": "Cannot set the Agent system directory as working directory",
|
|
15
|
+
"workdirNotDirectory": "The target path exists but is not a directory",
|
|
16
|
+
"sessionWorkdirMissing": "This session's working directory no longer exists ({workdir}), please pick another one",
|
|
12
17
|
"pathNotAbsolute": "path must be an absolute path",
|
|
13
18
|
"cannotRemoveWorkdir": "Cannot remove the current working directory, please switch to another directory first",
|
|
14
19
|
"pathNotInAllowedList": "This directory is not in the allowed list",
|
|
@@ -123,13 +128,17 @@
|
|
|
123
128
|
"err_invalidEmbeddingMode": "Unsupported embedding mode: {mode}",
|
|
124
129
|
"err_invalidEmbeddingEndpoint": "Invalid remote embedding endpoint (must be an http/https base URL, e.g. https://api.siliconflow.cn/v1)",
|
|
125
130
|
"err_invalidEmbeddingDimensions": "Invalid embedding dimensions: {dimensions}",
|
|
126
|
-
"err_embeddingDimensionMismatch": "Embedding dimension mismatch: configured {expected}, got {actual}. Check the embedding model and dimension settings"
|
|
131
|
+
"err_embeddingDimensionMismatch": "Embedding dimension mismatch: configured {expected}, got {actual}. Check the embedding model and dimension settings",
|
|
132
|
+
"err_ortConflict": "Local embedding engine failed to load: two copies of the onnxruntime native library ended up in one process (Windows reports cannot run %1). Restart the agent and retry — loaded DLLs cannot be unloaded before the process exits, so a hot fix cannot work. If it still fails after restarting, reinstall the knowledge-base dependencies (installation removes the duplicate copy)",
|
|
133
|
+
"err_embedWorkerFailed": "Local embedding subprocess failed: {message}. Check network and disk space; reinstall the knowledge-base dependencies if it persists"
|
|
127
134
|
},
|
|
128
135
|
"message": {
|
|
129
136
|
"shuttingDown": "Agent is shutting down...",
|
|
130
137
|
"restarting": "Agent is restarting...",
|
|
131
138
|
"updateSuccess": "Update successful, Agent is restarting...",
|
|
132
139
|
"workdirSwitched": "Working directory switched",
|
|
140
|
+
"workdirBoundToSession": "Bound to this session only (other sessions are unaffected)",
|
|
141
|
+
"workdirUnbound": "This session now follows the agent default directory",
|
|
133
142
|
"removedFromAllowedList": "Removed from allowed list",
|
|
134
143
|
"movedToTrash": "Moved to trash (auto-cleaned after 7 days)",
|
|
135
144
|
"mcpCommandConfirm": "MCP command needs confirmation: {reason}"
|
package/src/locales/zh.json
CHANGED
|
@@ -7,8 +7,13 @@
|
|
|
7
7
|
"operationInProgress": "已有操作正在进行中,请稍后再试",
|
|
8
8
|
"missingPath": "缺少 path 参数",
|
|
9
9
|
"missingWorkdir": "缺少 workdir 参数",
|
|
10
|
+
"invalidSessionId": "会话标识格式无效",
|
|
11
|
+
"invalidScope": "scope 只能是 session 或 global",
|
|
12
|
+
"workdirNotInSessionScope": "路径不在本会话的工作目录内({workdir})",
|
|
10
13
|
"workdirNotAbsolute": "workdir 必须是绝对路径",
|
|
11
14
|
"workdirIsSystemDir": "不能将 Agent 系统目录设为工作目录",
|
|
15
|
+
"workdirNotDirectory": "目标路径已存在但不是目录",
|
|
16
|
+
"sessionWorkdirMissing": "本会话的工作目录不存在或已被删除({workdir}),请重新选择目录",
|
|
12
17
|
"pathNotAbsolute": "path 必须是绝对路径",
|
|
13
18
|
"cannotRemoveWorkdir": "不能移除当前工作目录,请先切换到其它目录",
|
|
14
19
|
"pathNotInAllowedList": "该目录不在允许列表中",
|
|
@@ -123,13 +128,17 @@
|
|
|
123
128
|
"err_invalidEmbeddingMode": "不支持的向量模式: {mode}",
|
|
124
129
|
"err_invalidEmbeddingEndpoint": "远端向量服务地址无效(须为 http/https 的 Base URL,如 https://api.siliconflow.cn/v1)",
|
|
125
130
|
"err_invalidEmbeddingDimensions": "向量维度无效: {dimensions}",
|
|
126
|
-
"err_embeddingDimensionMismatch": "向量维度不匹配:配置 {expected} 维,实际返回 {actual} 维,请检查向量模型与维度设置"
|
|
131
|
+
"err_embeddingDimensionMismatch": "向量维度不匹配:配置 {expected} 维,实际返回 {actual} 维,请检查向量模型与维度设置",
|
|
132
|
+
"err_ortConflict": "本地向量引擎加载失败:进程里同时存在两份 onnxruntime 原生库(Windows 报 cannot run %1)。重启代理后再试——已加载的 DLL 在进程退出前无法卸载,热修复无效;若重启后仍失败,请重新安装一次知识库依赖(安装时会清理重复副本)",
|
|
133
|
+
"err_embedWorkerFailed": "本地向量子进程调用失败:{message}。请检查网络与磁盘空间;持续失败可重新安装知识库依赖"
|
|
127
134
|
},
|
|
128
135
|
"message": {
|
|
129
136
|
"shuttingDown": "Agent 正在关闭...",
|
|
130
137
|
"restarting": "Agent 正在重启...",
|
|
131
138
|
"updateSuccess": "更新成功,Agent 正在重启...",
|
|
132
139
|
"workdirSwitched": "工作目录已切换",
|
|
140
|
+
"workdirBoundToSession": "已绑定到本会话(其他会话不受影响)",
|
|
141
|
+
"workdirUnbound": "本会话已恢复跟随代理默认目录",
|
|
133
142
|
"removedFromAllowedList": "已从允许列表中移除",
|
|
134
143
|
"movedToTrash": "已移至回收站(7天后自动清理)",
|
|
135
144
|
"mcpCommandConfirm": "MCP 命令需要确认: {reason}"
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
// agent/src/native-lib-guard.js - node_modules 原生库副本清理(同一进程只允许一份 onnxruntime)
|
|
2
|
+
//
|
|
3
|
+
// 背景(Windows 实测,2026-10):
|
|
4
|
+
// Windows 的 LoadLibrary 按「模块基名」复用模块 —— 同一进程里出现第二份 onnxruntime.dll 时,
|
|
5
|
+
// 后来者直接拿到先加载那份的句柄。若两份版本不同,onnxruntime_binding.node 要求的 API 版本
|
|
6
|
+
// 在旧 dll 里不存在,加载即失败:
|
|
7
|
+
// The operating system cannot run %1. ...\onnxruntime_binding.node
|
|
8
|
+
// 现实中会出现两份的原因:transformers 精确依赖某个 onnxruntime-node 版本,而我们在
|
|
9
|
+
// package.json 用 overrides 钉了另一个版本(Intel Mac 必须钉 1.23.x,≥1.24 无 darwin/x64
|
|
10
|
+
// 二进制)。npm 在部分版本/安装顺序下不把两者合并,而是把冲突版本嵌套装到
|
|
11
|
+
// node_modules/@huggingface/transformers/node_modules/onnxruntime-node。
|
|
12
|
+
//
|
|
13
|
+
// 因此每次一键安装(RAG / ASR 都会重算整个包目录依赖树)之后统一做一次「去重收口」:
|
|
14
|
+
// 保留顶层副本(overrides 指定的那个),删掉嵌套副本。这是确定性的磁盘操作,不依赖
|
|
15
|
+
// npm 对 overrides 的处理细节。
|
|
16
|
+
//
|
|
17
|
+
// 另一层隔离在代码侧:本地 embedding 跑在子进程(rag/embedding/embed-worker.mjs),
|
|
18
|
+
// 与语音输入的 sherpa-onnx 不共享地址空间。两条一起才完整 —— 子进程里若也有两份副本,
|
|
19
|
+
// 一样会撞。
|
|
20
|
+
|
|
21
|
+
import { existsSync, readdirSync, readFileSync, rmSync, statSync } from 'fs';
|
|
22
|
+
import { join } from 'path';
|
|
23
|
+
|
|
24
|
+
// 需要做「全树唯一」的原生依赖:只收 onnxruntime-node —— 它会加载 onnxruntime.dll,
|
|
25
|
+
// 同进程两份就抢句柄。onnxruntime-common 是纯 JS 胶水层(不带 dll),且 onnxruntime-web
|
|
26
|
+
// 会正常地嵌套一份自己钉的 dev 版,删它只会制造风险,不做。
|
|
27
|
+
export const NATIVE_DEDUPE_PACKAGES = ['onnxruntime-node'];
|
|
28
|
+
|
|
29
|
+
// 依赖树扫描深度上限(最多深入 6 层嵌套 node_modules;再深的依赖树极罕见,也避免异常目录把扫描拖死)
|
|
30
|
+
const MAX_DEPTH = 6;
|
|
31
|
+
|
|
32
|
+
// 隐藏目录(.pnpm / .bin / .cache / .yarn 等)一律不进入:
|
|
33
|
+
// pnpm 的 .pnpm 是内容寻址存储,删里面的副本会破坏链接;其余是缓存/工具目录。
|
|
34
|
+
// 实现上直接按「名字以 . 开头」跳过(见 scanNodeModules)。
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 目录判断(读取失败按非目录处理)
|
|
38
|
+
* @param {string} path
|
|
39
|
+
* @returns {boolean}
|
|
40
|
+
*/
|
|
41
|
+
function isDirectory(path) {
|
|
42
|
+
try {
|
|
43
|
+
return statSync(path).isDirectory();
|
|
44
|
+
} catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 读取包版本(读不到返回 null)
|
|
51
|
+
* @param {string} dir
|
|
52
|
+
* @returns {string|null}
|
|
53
|
+
*/
|
|
54
|
+
function readPackageVersion(dir) {
|
|
55
|
+
try {
|
|
56
|
+
return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8')).version || null;
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 扫描一个 node_modules 目录,收集目标包的副本路径
|
|
64
|
+
* @param {string} nodeModulesDir
|
|
65
|
+
* @param {Set<string>} targets
|
|
66
|
+
* @param {Array<{ path: string, name: string }>} found
|
|
67
|
+
* @param {number} depth
|
|
68
|
+
*/
|
|
69
|
+
function scanNodeModules(nodeModulesDir, targets, found, depth) {
|
|
70
|
+
let entries;
|
|
71
|
+
try {
|
|
72
|
+
entries = readdirSync(nodeModulesDir);
|
|
73
|
+
} catch {
|
|
74
|
+
return; // 目录不存在/不可读:没有副本
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
for (const entry of entries) {
|
|
78
|
+
if (!entry || entry.startsWith('.')) continue;
|
|
79
|
+
const fullPath = join(nodeModulesDir, entry);
|
|
80
|
+
if (!isDirectory(fullPath)) continue;
|
|
81
|
+
|
|
82
|
+
if (entry.startsWith('@')) {
|
|
83
|
+
// scope 目录:下一层才是包
|
|
84
|
+
let scoped;
|
|
85
|
+
try {
|
|
86
|
+
scoped = readdirSync(fullPath);
|
|
87
|
+
} catch {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
for (const name of scoped) {
|
|
91
|
+
const pkgDir = join(fullPath, name);
|
|
92
|
+
if (!isDirectory(pkgDir)) continue;
|
|
93
|
+
if (targets.has(name)) found.push({ path: pkgDir, name });
|
|
94
|
+
else scanNested(pkgDir, targets, found, depth);
|
|
95
|
+
}
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (targets.has(entry)) {
|
|
100
|
+
found.push({ path: fullPath, name: entry });
|
|
101
|
+
continue; // 命中即不再深入:包自己的 node_modules 由上层去重逻辑处理
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
scanNested(fullPath, targets, found, depth);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 递归进入包的 node_modules
|
|
110
|
+
* @param {string} packageDir
|
|
111
|
+
* @param {Set<string>} targets
|
|
112
|
+
* @param {Array<{ path: string, name: string }>} found
|
|
113
|
+
* @param {number} depth
|
|
114
|
+
*/
|
|
115
|
+
function scanNested(packageDir, targets, found, depth) {
|
|
116
|
+
if (depth >= MAX_DEPTH) return;
|
|
117
|
+
const nested = join(packageDir, 'node_modules');
|
|
118
|
+
if (!existsSync(nested)) return;
|
|
119
|
+
scanNodeModules(nested, targets, found, depth + 1);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 列出全部副本(含顶层),按路径深度升序(浅者优先保留)
|
|
124
|
+
* @param {string} agentRoot - agent 包根目录(含 node_modules)
|
|
125
|
+
* @param {{ packages?: string[] }} [opts] 仅测试注入
|
|
126
|
+
* @returns {Array<{ path: string, name: string, version: string|null }>}
|
|
127
|
+
*/
|
|
128
|
+
export function listNativeCopies(agentRoot, opts = {}) {
|
|
129
|
+
const names = Array.isArray(opts.packages) && opts.packages.length ? opts.packages : NATIVE_DEDUPE_PACKAGES;
|
|
130
|
+
const targets = new Set(names);
|
|
131
|
+
const rootNodeModules = join(agentRoot, 'node_modules');
|
|
132
|
+
if (!isDirectory(rootNodeModules)) return [];
|
|
133
|
+
|
|
134
|
+
const found = [];
|
|
135
|
+
scanNodeModules(rootNodeModules, targets, found, 0);
|
|
136
|
+
return found
|
|
137
|
+
.map((entry) => ({ ...entry, version: readPackageVersion(entry.path) }))
|
|
138
|
+
.sort((a, b) => a.path.split(/[\\/]/).length - b.path.split(/[\\/]/).length);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* 清理嵌套重复副本:每个包只保留最浅的一份(通常是顶层 = overrides 指定的版本)
|
|
143
|
+
*
|
|
144
|
+
* 只删 node_modules 内、包名精确匹配的目录;删除失败(Windows 文件被占用等)不抛错,
|
|
145
|
+
* 落到 failed 里由调用方写进安装日志 —— 安装本身不该因为清理失败而判定失败。
|
|
146
|
+
* @param {string} agentRoot - agent 包根目录
|
|
147
|
+
* @param {{ packages?: string[], dryRun?: boolean }} [opts]
|
|
148
|
+
* @returns {{ removed: Array<{ path: string, name: string, version: string|null }>,
|
|
149
|
+
* failed: Array<{ path: string, name: string, error: string }>,
|
|
150
|
+
* kept: Array<{ path: string, name: string, version: string|null }> }}
|
|
151
|
+
*/
|
|
152
|
+
export function pruneNativeDuplicates(agentRoot, opts = {}) {
|
|
153
|
+
const copies = listNativeCopies(agentRoot, opts);
|
|
154
|
+
const kept = [];
|
|
155
|
+
const removed = [];
|
|
156
|
+
const failed = [];
|
|
157
|
+
const seen = new Set();
|
|
158
|
+
|
|
159
|
+
for (const entry of copies) {
|
|
160
|
+
if (!seen.has(entry.name)) {
|
|
161
|
+
seen.add(entry.name);
|
|
162
|
+
kept.push(entry); // 最浅的一份保留
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (opts.dryRun) {
|
|
166
|
+
removed.push(entry);
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
rmSync(entry.path, { recursive: true, force: true });
|
|
171
|
+
removed.push(entry);
|
|
172
|
+
} catch (err) {
|
|
173
|
+
failed.push({ ...entry, error: err?.message || String(err) });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return { removed, failed, kept };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 生成一行可读的清理摘要(供安装日志)
|
|
182
|
+
* @param {{ removed: Array<{name: string, version: string|null}>, failed: Array<{name: string, error: string}> }} report
|
|
183
|
+
* @returns {string|null}
|
|
184
|
+
*/
|
|
185
|
+
export function summarizePruneReport(report) {
|
|
186
|
+
const parts = [];
|
|
187
|
+
for (const entry of report?.removed || []) {
|
|
188
|
+
parts.push(`removed duplicate ${entry.name}@${entry.version || '?'}`);
|
|
189
|
+
}
|
|
190
|
+
for (const entry of report?.failed || []) {
|
|
191
|
+
parts.push(`failed to remove ${entry.name} (${entry.error})`);
|
|
192
|
+
}
|
|
193
|
+
return parts.length ? parts.join('; ') : null;
|
|
194
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// agent/src/rag/embedding/embed-worker.mjs - 本地 embedding 子进程(transformers 只允许在子进程里加载)
|
|
2
|
+
//
|
|
3
|
+
// 为什么必须是「独立进程」(Windows,2026-10 实测):
|
|
4
|
+
// 语音输入(sherpa-onnx-node)与本地向量(onnxruntime-node)各自捆绑一份 onnxruntime
|
|
5
|
+
// 原生库。Windows 的 LoadLibrary 按「模块基名」复用模块:同一进程里出现第二份
|
|
6
|
+
// onnxruntime.dll 时,后来者直接拿到先加载那份的句柄 —— 若两份版本不同,binding 要求的
|
|
7
|
+
// API 版本在旧 dll 里不存在,就报
|
|
8
|
+
// The operating system cannot run %1. ...\onnxruntime_binding.node
|
|
9
|
+
// (Win32 193 ERROR_BAD_EXE_FORMAT / "API version [N] is not available")。
|
|
10
|
+
// 用户先装知识库、后装语音输入就必现:ASR 在线识别在主进程加载 sherpa 的 dll,随后
|
|
11
|
+
// RAG 的 embedding 在主进程加载 onnxruntime-node 的 dll → 冲突。
|
|
12
|
+
// worker_threads 与主线程共享地址空间,隔离不了,只能用子进程(ASR 的 offline 线程同理,
|
|
13
|
+
// 但它加载的是同一份 sherpa,不构成冲突)。
|
|
14
|
+
// 推论:transformers 只能在独立子进程里加载 —— 本文件负责推理,probe-child.mjs 负责
|
|
15
|
+
// 可用性探测(它在 detect.js 起的临时子进程里跑);主进程(以及 ASR 的 worker 线程)
|
|
16
|
+
// 任何地方 import 都会把第二份 dll 拽回主进程,把这个修复打回原形。这条不变式由单测
|
|
17
|
+
// rag-no-mainprocess-transformers 锁着(静态扫描 + 子进程运行时取证)。
|
|
18
|
+
//
|
|
19
|
+
// 协议(stdin/stdout 均为单行 JSON,stdout 只允许出现协议数据):
|
|
20
|
+
// 请求 {"id":1,"method":"load|embed|countTokens","params":{...}}
|
|
21
|
+
// 响应 {"id":1,"ok":true,"result":...} | {"id":1,"ok":false,"error":{"message":"...","code":null}}
|
|
22
|
+
// 方法:
|
|
23
|
+
// load {modelName?, remoteHost?, cacheDir?} → {model, window}
|
|
24
|
+
// embed {texts:[string], modelName?, ...} → number[][](与 texts 同序)
|
|
25
|
+
// countTokens {texts:[string], ...} → {counts:number[], window:number}
|
|
26
|
+
|
|
27
|
+
import { createInterface } from 'readline';
|
|
28
|
+
import { MODELS_DIR } from '../config.js';
|
|
29
|
+
|
|
30
|
+
const DEFAULT_MODEL = 'Xenova/bge-small-zh-v1.5';
|
|
31
|
+
const DEFAULT_REMOTE_HOST = 'https://hf-mirror.com/';
|
|
32
|
+
|
|
33
|
+
// stdout 是协议通道:transformers 与底层库会往 console 写日志(下载进度、形状告警),
|
|
34
|
+
// 必须在 import 之前把 console 改道到 stderr,否则父进程按行 JSON.parse 必然失败。
|
|
35
|
+
for (const level of ['log', 'info', 'debug', 'warn']) {
|
|
36
|
+
console[level] = (...args) => console.error(...args);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// pipeline 单例(模型加载昂贵;换模型才重新加载)
|
|
40
|
+
let extractor = null;
|
|
41
|
+
let extractorModel = null;
|
|
42
|
+
// 加载锁:并发请求不要重复加载同一模型
|
|
43
|
+
let loading = null;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 取(或加载)feature-extraction pipeline,按模型名缓存
|
|
47
|
+
* @param {{ modelName?: string, remoteHost?: string, cacheDir?: string }} params
|
|
48
|
+
* @returns {Promise<object>} transformers pipeline
|
|
49
|
+
*/
|
|
50
|
+
async function getExtractor(params = {}) {
|
|
51
|
+
const modelName = String(params.modelName || DEFAULT_MODEL);
|
|
52
|
+
const remoteHost = String(params.remoteHost || DEFAULT_REMOTE_HOST);
|
|
53
|
+
const cacheDir = String(params.cacheDir || MODELS_DIR);
|
|
54
|
+
|
|
55
|
+
if (extractor && extractorModel === modelName) return extractor;
|
|
56
|
+
|
|
57
|
+
if (loading) {
|
|
58
|
+
await loading.catch(() => {});
|
|
59
|
+
if (extractor && extractorModel === modelName) return extractor;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
loading = (async () => {
|
|
63
|
+
const { env, pipeline } = await import('@huggingface/transformers');
|
|
64
|
+
// 端点与缓存目录必须在模型加载前设置(缓存目录独立于 node_modules,重装不丢模型)
|
|
65
|
+
env.remoteHost = remoteHost;
|
|
66
|
+
env.cacheDir = cacheDir;
|
|
67
|
+
console.error(`[RAG][embed-worker] loading model: ${modelName} (cache: ${cacheDir})`);
|
|
68
|
+
const next = await pipeline('feature-extraction', modelName, { dtype: 'q8' });
|
|
69
|
+
extractor = next;
|
|
70
|
+
extractorModel = modelName;
|
|
71
|
+
console.error(`[RAG][embed-worker] model ready: ${modelName}`);
|
|
72
|
+
})();
|
|
73
|
+
|
|
74
|
+
try {
|
|
75
|
+
await loading;
|
|
76
|
+
} finally {
|
|
77
|
+
loading = null;
|
|
78
|
+
}
|
|
79
|
+
return extractor;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 模型上下文窗口(以 tokenizer 为准,不自己写常量)
|
|
84
|
+
* @param {object} ex pipeline
|
|
85
|
+
* @returns {number}
|
|
86
|
+
*/
|
|
87
|
+
function modelWindow(ex) {
|
|
88
|
+
return Number(ex?.tokenizer?.model_max_length) || 0;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const handlers = {
|
|
92
|
+
async load(params) {
|
|
93
|
+
const ex = await getExtractor(params);
|
|
94
|
+
return { model: extractorModel, window: modelWindow(ex) };
|
|
95
|
+
},
|
|
96
|
+
|
|
97
|
+
async embed(params) {
|
|
98
|
+
const texts = Array.isArray(params.texts) ? params.texts : [];
|
|
99
|
+
if (texts.length === 0) return [];
|
|
100
|
+
const ex = await getExtractor(params);
|
|
101
|
+
// 单次批量推理:pipeline 支持数组输入,输出为 [batch, seq, dim] 张量
|
|
102
|
+
const output = await ex(texts.map((t) => String(t ?? '')), { pooling: 'mean', normalize: true });
|
|
103
|
+
return output.tolist();
|
|
104
|
+
},
|
|
105
|
+
|
|
106
|
+
async countTokens(params) {
|
|
107
|
+
const texts = Array.isArray(params.texts) ? params.texts : [];
|
|
108
|
+
if (texts.length === 0) return { counts: [], window: 0 };
|
|
109
|
+
const ex = await getExtractor(params);
|
|
110
|
+
const tokenizer = ex.tokenizer;
|
|
111
|
+
const window = modelWindow(ex);
|
|
112
|
+
// 必须 truncation: false —— 跟着 pipeline 的口径数只会永远数到窗口值,看不见被截掉多少
|
|
113
|
+
const counts = texts.map((t) => {
|
|
114
|
+
const encoded = tokenizer(String(t ?? ''), { padding: false, truncation: false });
|
|
115
|
+
const dims = encoded?.input_ids?.dims;
|
|
116
|
+
return Array.isArray(dims) && dims.length ? Number(dims[dims.length - 1]) : 0;
|
|
117
|
+
});
|
|
118
|
+
return { counts, window };
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 写一行协议响应(stdout 只写协议数据)
|
|
124
|
+
* @param {{ id: number|null, ok: boolean, result?: any, error?: object }} payload
|
|
125
|
+
*/
|
|
126
|
+
function writeLine(payload) {
|
|
127
|
+
process.stdout.write(`${JSON.stringify(payload)}\n`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function handle(request) {
|
|
131
|
+
const id = Number.isFinite(request?.id) ? request.id : null;
|
|
132
|
+
const method = String(request?.method || '');
|
|
133
|
+
const fn = handlers[method];
|
|
134
|
+
if (!fn) {
|
|
135
|
+
writeLine({ id, ok: false, error: { message: `unknown method: ${method}`, code: null } });
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
try {
|
|
139
|
+
const result = await fn(request?.params || {});
|
|
140
|
+
writeLine({ id, ok: true, result });
|
|
141
|
+
} catch (err) {
|
|
142
|
+
const message = err?.message ? String(err.message) : String(err);
|
|
143
|
+
// 原始 message 必须原样透传:父进程靠它识别 onnxruntime dll 冲突(cannot run %1)等原生错误
|
|
144
|
+
writeLine({ id, ok: false, error: { message, code: err?.code ?? null } });
|
|
145
|
+
console.error(`[RAG][embed-worker] ${method} failed: ${message}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// 串行处理:一次只跑一个请求,避免两个批量推理交错抢同一份会话内存
|
|
150
|
+
let chain = Promise.resolve();
|
|
151
|
+
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
152
|
+
rl.on('line', (line) => {
|
|
153
|
+
const trimmed = line.trim();
|
|
154
|
+
if (!trimmed) return;
|
|
155
|
+
let request;
|
|
156
|
+
try {
|
|
157
|
+
request = JSON.parse(trimmed);
|
|
158
|
+
} catch {
|
|
159
|
+
writeLine({ id: null, ok: false, error: { message: 'invalid json request', code: null } });
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
chain = chain.then(() => handle(request), () => handle(request));
|
|
163
|
+
});
|
|
164
|
+
// 父进程关闭 stdin(正常退出/空闲回收)即收工:不留原生句柄让进程挂住。
|
|
165
|
+
// 不能用 process.exit(0):模型加载后进程里有 onnxruntime 的原生线程,强退会在静态析构
|
|
166
|
+
// 阶段撞 "mutex lock failed: Invalid argument" 并以 SIGABRT 结束(macOS 实测,退出码 134),
|
|
167
|
+
// 日志里看起来像崩溃,父进程那边也是 signal 而不是 code 0。改为让事件循环自己排空;
|
|
168
|
+
// 万一有残留句柄把进程吊住,再用兜底定时器强退(那时已经没有别的选择了)。
|
|
169
|
+
rl.on('close', () => {
|
|
170
|
+
process.exitCode = 0;
|
|
171
|
+
const timer = setTimeout(() => process.exit(0), 5000);
|
|
172
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
process.on('uncaughtException', (err) => {
|
|
176
|
+
console.error(`[RAG][embed-worker] uncaught: ${err?.stack || err?.message || err}`);
|
|
177
|
+
process.exit(1);
|
|
178
|
+
});
|
|
179
|
+
process.on('unhandledRejection', (err) => {
|
|
180
|
+
console.error(`[RAG][embed-worker] unhandled rejection: ${err?.stack || err?.message || err}`);
|
|
181
|
+
process.exit(1);
|
|
182
|
+
});
|