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.
Files changed (94) hide show
  1. package/dist/assets/{agent-store-D0oEv0PW.js → agent-store-TSvufiWG.js} +1 -1
  2. package/dist/assets/background.js +71 -70
  3. package/dist/assets/{chat-export-MTTSSIwM.js → chat-export-BFXv3fdM.js} +1 -1
  4. package/dist/assets/content.js +43 -43
  5. package/dist/{dist/assets/i18n-Br_sF5pb.js → assets/i18n-DJ3tjLY-.js} +4 -4
  6. package/dist/{dist/assets/markdown-render-lSSxW953.js → assets/markdown-render-C9SKCrR4.js} +4 -4
  7. package/dist/assets/{model-profiles-BdQaV4EZ.js → model-profiles-CfvHSLkL.js} +1 -1
  8. package/dist/{dist/assets/options-JtYgxtsc.css → assets/options-DU7Wz1w_.css} +1 -1
  9. package/dist/assets/options.js +89 -89
  10. package/dist/assets/{page-snapshot-renderer-Cl0qk7U1.js → page-snapshot-renderer-Cdzmf6hl.js} +1 -1
  11. package/dist/assets/session-store-CRTEYLCo.js +81 -0
  12. package/dist/assets/side_panel.css +1 -1
  13. package/dist/assets/side_panel.js +219 -215
  14. package/dist/{dist/assets/utils-ZJjxSlg_.js → assets/utils-DukUruXz.js} +26 -26
  15. package/dist/assets/{version-C0CY79zF.js → version-s8LDcTZ-.js} +1 -1
  16. package/dist/assets/voice-shortcut-Dtt3nhkz.js +1 -0
  17. package/dist/assets/workspace-manager-CgkNrxoo.js +1 -0
  18. package/dist/manifest.json +1 -1
  19. package/dist/offscreen/offscreen.js +6 -6
  20. package/dist/options.html +34 -4
  21. package/dist/side_panel.html +22 -13
  22. package/package.json +1 -1
  23. package/src/asr/install.js +26 -0
  24. package/src/documents/routes.js +4 -3
  25. package/src/locales/en.json +10 -1
  26. package/src/locales/zh.json +10 -1
  27. package/src/native-lib-guard.js +194 -0
  28. package/src/rag/embedding/embed-worker.mjs +182 -0
  29. package/src/rag/embedding/local.js +42 -62
  30. package/src/rag/embedding/worker-client.js +476 -0
  31. package/src/rag/errors.js +60 -2
  32. package/src/rag/install.js +27 -0
  33. package/src/rag/manager.js +5 -2
  34. package/src/rag/routes.js +4 -2
  35. package/src/search.js +4 -4
  36. package/src/security.js +97 -33
  37. package/src/server.js +284 -40
  38. package/src/session-workdirs.js +241 -0
  39. package/src/skill/executor.js +25 -9
  40. package/src/skill/registry.js +3 -2
  41. package/dist/assets/i18n-Br_sF5pb.js +0 -49
  42. package/dist/assets/markdown-render-Dq5F_dqP.js +0 -63
  43. package/dist/assets/options-JtYgxtsc.css +0 -1
  44. package/dist/assets/session-store-KkrAlIc6.js +0 -81
  45. package/dist/assets/utils-ZJjxSlg_.js +0 -112
  46. package/dist/dist/_locales/en/messages.json +0 -11
  47. package/dist/dist/_locales/zh_CN/messages.json +0 -11
  48. package/dist/dist/assets/__vite-browser-external-CM3Eme-n.js +0 -1
  49. package/dist/dist/assets/agent-store-D0oEv0PW.js +0 -1
  50. package/dist/dist/assets/background.js +0 -451
  51. package/dist/dist/assets/chat-export-7wjGjcA8.js +0 -37
  52. package/dist/dist/assets/chunk-CMxvf4Kt.js +0 -1
  53. package/dist/dist/assets/content.js +0 -985
  54. package/dist/dist/assets/dist-BUuoW_84.js +0 -24
  55. package/dist/dist/assets/dist-DuuG_8Br.js +0 -133
  56. package/dist/dist/assets/jszip.min-DO6SOhXU.js +0 -2
  57. package/dist/dist/assets/lib-YwkWjNcC.js +0 -220
  58. package/dist/dist/assets/marked.min.js-D2rXgLAQ.js +0 -56
  59. package/dist/dist/assets/marked.min.js-loader-tKH5SQVQ.js +0 -13
  60. package/dist/dist/assets/model-profiles-BdQaV4EZ.js +0 -24
  61. package/dist/dist/assets/network-scope-CNRYXk74.js +0 -1
  62. package/dist/dist/assets/options.js +0 -859
  63. package/dist/dist/assets/page-snapshot-renderer-Cl0qk7U1.js +0 -3
  64. package/dist/dist/assets/pdf-DnVqBaAN.js +0 -6
  65. package/dist/dist/assets/session-store-KkrAlIc6.js +0 -81
  66. package/dist/dist/assets/side_panel.css +0 -1
  67. package/dist/dist/assets/side_panel.js +0 -2595
  68. package/dist/dist/assets/theme-BRAX5X2F.css +0 -1
  69. package/dist/dist/assets/theme-CLwYsx9o.js +0 -1
  70. package/dist/dist/assets/version-C7x4HYX1.js +0 -1
  71. package/dist/dist/assets/xlsx-DGkz7cnk.js +0 -105
  72. package/dist/dist/icons/README.md +0 -11
  73. package/dist/dist/icons/design-philosophy.md +0 -41
  74. package/dist/dist/icons/icon128.png +0 -0
  75. package/dist/dist/icons/icon128.svg +0 -68
  76. package/dist/dist/icons/icon16.png +0 -0
  77. package/dist/dist/icons/icon16.svg +0 -32
  78. package/dist/dist/icons/icon48.png +0 -0
  79. package/dist/dist/icons/icon48.svg +0 -56
  80. package/dist/dist/libs/github-markdown-light.min.css +0 -8
  81. package/dist/dist/libs/html2canvas.min.js +0 -20
  82. package/dist/dist/libs/jspdf.min.js +0 -398
  83. package/dist/dist/libs/marked.min.js +0 -69
  84. package/dist/dist/libs/mermaid.min.js +0 -2024
  85. package/dist/dist/libs/pdf.worker.min.js +0 -22
  86. package/dist/dist/libs/qrcode.min.js +0 -7
  87. package/dist/dist/manifest.json +0 -94
  88. package/dist/dist/offscreen/offscreen.html +0 -11
  89. package/dist/dist/offscreen/offscreen.js +0 -49
  90. package/dist/dist/options.html +0 -1091
  91. package/dist/dist/service-worker-loader.js +0 -1
  92. package/dist/dist/side_panel.html +0 -1357
  93. package/dist/dist/styles/styles.css +0 -262
  94. package/dist/dist/voice-capture-worklet.js +0 -47
@@ -1,29 +1,31 @@
1
- // agent/src/rag/embedding/local.js - 本地 embedding(transformers.js)
1
+ // agent/src/rag/embedding/local.js - 本地 embedding(transformers.js,跑在独立子进程里)
2
2
  // 默认模型 Xenova/bge-small-zh-v1.5(中文优化,512 维,q8 量化约 95MB)
3
3
  // 关键约束(实测):
4
4
  // 1. 模型下载端点须走 hf-mirror 镜像(huggingface.co 国内直连超时)
5
5
  // 2. 缓存目录指向 ~/.ai-helper-agent/rag/models(默认在 node_modules 内,重装即丢)
6
+ // 3. 推理必须在 embed-worker 子进程里做:主进程一旦 import transformers,就会和语音输入
7
+ // 的 sherpa-onnx 抢同一份 onnxruntime.dll(Windows 报 "cannot run %1"),详见
8
+ // embed-worker.mjs 文件头的根因说明。本文件因此不出现任何 transformers 引用。
9
+ //
10
+ // 对外接口保持不变:embed(texts) / countTokens(texts),调用方(RAG 检索、长期记忆)无感。
6
11
 
7
- import { MODELS_DIR } from '../config.js';
8
-
9
- // pipeline 单例(模型加载昂贵,进程内复用;按模型名缓存)
10
- let _pipeline = null;
11
- let _pipelineModel = null;
12
- // 加载锁:并发首次调用时避免重复加载同一模型
13
- let _loadingPromise = null;
12
+ import { getEmbedWorker } from './worker-client.js';
13
+ import { toEmbeddingError } from '../errors.js';
14
14
 
15
15
  /**
16
- * 本地 embedding 后端(transformers.js feature-extraction pipeline)
16
+ * 本地 embedding 后端(子进程内的 transformers.js feature-extraction pipeline)
17
17
  */
18
18
  export class LocalEmbedding {
19
19
  /**
20
20
  * @param {object} config - embedding 配置
21
21
  * @param {string} config.modelName - 模型名(如 Xenova/bge-small-zh-v1.5)
22
22
  * @param {string} [config.remoteHost] - 模型下载端点(默认 hf-mirror)
23
+ * @param {object} [deps] - 仅测试注入:{ worker }
23
24
  */
24
- constructor(config = {}) {
25
+ constructor(config = {}, deps = {}) {
25
26
  this.modelName = config.modelName || 'Xenova/bge-small-zh-v1.5';
26
27
  this.remoteHost = config.remoteHost || 'https://hf-mirror.com/';
28
+ this.worker = deps.worker || null;
27
29
  }
28
30
 
29
31
  /**
@@ -33,73 +35,51 @@ export class LocalEmbedding {
33
35
  */
34
36
  async embed(texts) {
35
37
  if (!Array.isArray(texts) || texts.length === 0) return [];
36
-
37
- const extractor = await this._getPipeline();
38
-
39
- // 单次批量推理:pipeline 支持数组输入,输出为 [batch, seq, dim] 张量
40
- const output = await extractor(texts, { pooling: 'mean', normalize: true });
41
- // tolist() 转为嵌套数组;v4 中 Tensor 直接可迭代,但 tolist 语义更明确
42
- return output.tolist();
38
+ try {
39
+ const vectors = await this._getWorker().embed(texts, this._workerParams());
40
+ return Array.isArray(vectors) ? vectors : [];
41
+ } catch (err) {
42
+ throw toEmbeddingError(err);
43
+ }
43
44
  }
44
45
 
45
46
  /**
46
47
  * 统计文本的真实 token 长度与模型上下文窗口(供调用方发现「会被截多」)。
47
48
  *
48
- * 必须 `truncation: false`:feature-extraction pipeline 内部用的是 `truncation: true`,
49
- * 实测在 `model_max_length`(本模型 512)处静默砍尾——跟着它的口径数只会永远数到窗口值,
50
- * 看不见损失了多少。也不走 `embed()` 的反推:tolist 只给向量,给不出长度。
49
+ * 子进程侧必须 truncation: false:feature-extraction pipeline 内部用的是 truncation: true,
50
+ * 实测在 model_max_length(本模型 512)处静默砍尾——跟着它的口径数只会永远数到窗口值,
51
+ * 看不见损失了多少。也不走 embed() 的反推:只给向量,给不出长度。
51
52
  * 纯 tokenization 不跑推理,成本远低于嵌入本身。
52
53
  * @param {string[]} texts
53
54
  * @returns {Promise<{counts: number[], window: number}>} counts 与入参同序
54
55
  */
55
56
  async countTokens(texts) {
56
57
  if (!Array.isArray(texts) || texts.length === 0) return { counts: [], window: 0 };
57
-
58
- const extractor = await this._getPipeline();
59
- const tokenizer = extractor.tokenizer;
60
- // 窗口值以 tokenizer 为准(实测 = tokenizer_config.model_max_length = 512),不自己写常量
61
- const window = Number(tokenizer.model_max_length) || 0;
62
- const counts = texts.map((t) => {
63
- const encoded = tokenizer(String(t ?? ''), { padding: false, truncation: false });
64
- const dims = encoded?.input_ids?.dims;
65
- return Array.isArray(dims) && dims.length ? Number(dims[dims.length - 1]) : 0;
66
- });
67
- return { counts, window };
58
+ try {
59
+ const result = await this._getWorker().countTokens(texts, this._workerParams());
60
+ return {
61
+ counts: Array.isArray(result?.counts) ? result.counts : [],
62
+ window: Number(result?.window) || 0,
63
+ };
64
+ } catch (err) {
65
+ throw toEmbeddingError(err);
66
+ }
68
67
  }
69
68
 
70
69
  /**
71
- * 获取(或加载)pipeline 单例
70
+ * 子进程请求参数(模型名与下载端点是每次请求都带的:子进程按模型名缓存 pipeline)
71
+ * @returns {{ modelName: string, remoteHost: string }}
72
72
  */
73
- async _getPipeline() {
74
- if (_pipeline && _pipelineModel === this.modelName) return _pipeline;
75
-
76
- // 加载中:等待现有加载完成(换模型时串行等待后重新加载)
77
- if (_loadingPromise) {
78
- await _loadingPromise.catch(() => {});
79
- if (_pipeline && _pipelineModel === this.modelName) return _pipeline;
80
- }
81
-
82
- _loadingPromise = (async () => {
83
- const { env, pipeline } = await import('@huggingface/transformers');
84
-
85
- // 端点与缓存目录必须在模型加载前设置
86
- env.remoteHost = this.remoteHost;
87
- env.cacheDir = MODELS_DIR;
88
-
89
- console.log(`[RAG] loading embedding model: ${this.modelName} (cache: ${MODELS_DIR})`);
90
- const extractor = await pipeline('feature-extraction', this.modelName, {
91
- dtype: 'q8', // v3+ 用 dtype 指定量化精度(替代已废弃的 quantized: true)
92
- });
93
- _pipeline = extractor;
94
- _pipelineModel = this.modelName;
95
- console.log(`[RAG] embedding model ready: ${this.modelName}`);
96
- })();
73
+ _workerParams() {
74
+ return { modelName: this.modelName, remoteHost: this.remoteHost };
75
+ }
97
76
 
98
- try {
99
- await _loadingPromise;
100
- } finally {
101
- _loadingPromise = null;
102
- }
103
- return _pipeline;
77
+ /**
78
+ * 取子进程客户端(进程级单例:RAG 与长期记忆共用,模型只加载一份)
79
+ * @returns {import('./worker-client.js').EmbedWorkerClient}
80
+ */
81
+ _getWorker() {
82
+ if (!this.worker) this.worker = getEmbedWorker();
83
+ return this.worker;
104
84
  }
105
85
  }
@@ -0,0 +1,476 @@
1
+ // agent/src/rag/embedding/worker-client.js - 本地 embedding 子进程的客户端(父进程侧)
2
+ //
3
+ // 职责:把「加载模型 / 算向量 / 数 token」三个动作转发给 embed-worker.mjs(独立进程),
4
+ // 主进程因此从不 import transformers —— onnxruntime-node 的 dll 只活在子进程里,不会和
5
+ // 语音输入(sherpa-onnx)的 onnxruntime.dll 在同一个 Windows 进程里抢句柄(见
6
+ // embed-worker.mjs 文件头的根因说明)。
7
+ //
8
+ // 治理策略(与 asr/offline-pool.js 同源,但这里是子进程不是线程):
9
+ // - 懒启动:首个请求才 spawn,未用 RAG/记忆向量的用户零成本
10
+ // - 串行队列:一次只跑一个请求(原生会话不能被两个批量推理交错使用)
11
+ // - 超时:未加载过 180s(含首次下载模型 95MB),已加载 60s;超时即杀子进程
12
+ // - 熔断:连续 3 次失败后冷却 5 分钟,避免在坏依赖上反复 spawn 打转
13
+ // - 空闲回收:默认空闲 10 分钟杀掉子进程,把几百 MB 原生内存还给系统
14
+ // - 子进程异常退出:拒绝所有在途请求(错误码 embed_worker_crashed),下次请求重新 spawn
15
+
16
+ import { spawn } from 'child_process';
17
+ import { fileURLToPath } from 'url';
18
+
19
+ // 测试注入点:指向假的 worker 脚本(避免真的 import transformers)
20
+ export const WORKER_PATH_ENV = 'AI_HELPER_RAG_EMBED_WORKER';
21
+
22
+ const DEFAULT_WORKER_PATH = fileURLToPath(new URL('./embed-worker.mjs', import.meta.url));
23
+
24
+ /** @param {string} name @param {number} fallback @returns {number} */
25
+ function envMs(name, fallback) {
26
+ const raw = Number(process.env[name]);
27
+ return Number.isFinite(raw) && raw > 0 ? raw : fallback;
28
+ }
29
+
30
+ // 首次请求要等模型加载(含下载),给足余量
31
+ const DEFAULT_LOAD_TIMEOUT_MS = 180 * 1000;
32
+ // 模型已就绪后的单次请求上限(批量 10 条中文短文本在慢机上也只需几百毫秒)
33
+ const DEFAULT_OP_TIMEOUT_MS = 60 * 1000;
34
+ // 空闲多久杀掉子进程
35
+ const DEFAULT_IDLE_MS = 10 * 60 * 1000;
36
+ // 连续失败达到该次数进入冷却
37
+ const MAX_CONSECUTIVE_FAILURES = 3;
38
+ // 冷却时长(期间直接失败,不再 spawn)
39
+ const COOLDOWN_MS = 5 * 60 * 1000;
40
+ // 子进程 stderr 单行长度上限(防止进度条把日志刷爆)
41
+ const STDERR_LINE_MAX = 500;
42
+ // 协议行长度上限:超过即视为协议错乱(正常响应远小于此),直接丢子进程而不是静默吞数据
43
+ const PROTOCOL_LINE_MAX = 1_000_000;
44
+ // close() 的宽限:先关 stdin 让子进程自己退,超时才强杀。
45
+ // 安装期去重要删被这个进程映射着的 onnxruntime.dll(Windows 上没退就删不掉),
46
+ // 所以 close() 必须等到进程真的没了才返回,不能只是「发起了退出」
47
+ const CLOSE_GRACE_MS = 2000;
48
+
49
+ export class EmbedWorkerClient {
50
+ /**
51
+ * @param {{ workerPath?: string, idleMs?: number, loadTimeoutMs?: number, opTimeoutMs?: number }} [opts]
52
+ */
53
+ constructor(opts = {}) {
54
+ this._workerPath = opts.workerPath || process.env[WORKER_PATH_ENV] || DEFAULT_WORKER_PATH;
55
+ this._idleMs = Number.isFinite(opts.idleMs) ? opts.idleMs : envMs('AI_HELPER_RAG_EMBED_IDLE_MS', DEFAULT_IDLE_MS);
56
+ this._loadTimeoutMs = Number(opts.loadTimeoutMs) > 0
57
+ ? Number(opts.loadTimeoutMs)
58
+ : envMs('AI_HELPER_RAG_EMBED_LOAD_TIMEOUT_MS', DEFAULT_LOAD_TIMEOUT_MS);
59
+ this._opTimeoutMs = Number(opts.opTimeoutMs) > 0
60
+ ? Number(opts.opTimeoutMs)
61
+ : envMs('AI_HELPER_RAG_EMBED_TIMEOUT_MS', DEFAULT_OP_TIMEOUT_MS);
62
+
63
+ this._child = null;
64
+ this._buffer = '';
65
+ this._nextId = 1;
66
+ /** @type {Map<number, { method: string, resolve: Function, reject: Function, timer: any }>} */
67
+ this._pending = new Map();
68
+ // 串行队列:每个请求挂在上一个请求之后(失败不阻断后续)
69
+ this._chain = Promise.resolve();
70
+ // 是否已经成功加载过模型(决定单次请求用哪个超时)
71
+ this._loaded = false;
72
+ this._failures = 0;
73
+ this._cooldownUntil = 0;
74
+ this._idleTimer = null;
75
+ }
76
+
77
+ /**
78
+ * 子进程是否存活
79
+ * @returns {boolean}
80
+ */
81
+ get alive() {
82
+ return Boolean(this._child);
83
+ }
84
+
85
+ /**
86
+ * 当前子进程 pid(未启动为 null)——排查泄漏/残留进程用
87
+ * @returns {number|null}
88
+ */
89
+ get pid() {
90
+ return this._child ? this._child.pid : null;
91
+ }
92
+
93
+ /**
94
+ * 加载(或确认已加载)模型
95
+ * @param {{ modelName?: string, remoteHost?: string, cacheDir?: string }} [params]
96
+ * @returns {Promise<{ model: string, window: number }>}
97
+ */
98
+ load(params = {}) {
99
+ return this._request('load', params);
100
+ }
101
+
102
+ /**
103
+ * 批量生成向量
104
+ * @param {string[]} texts
105
+ * @param {{ modelName?: string, remoteHost?: string, cacheDir?: string }} [params]
106
+ * @returns {Promise<number[][]>}
107
+ */
108
+ embed(texts, params = {}) {
109
+ return this._request('embed', { ...params, texts });
110
+ }
111
+
112
+ /**
113
+ * 统计 token 长度与窗口
114
+ * @param {string[]} texts
115
+ * @param {{ modelName?: string, remoteHost?: string, cacheDir?: string }} [params]
116
+ * @returns {Promise<{ counts: number[], window: number }>}
117
+ */
118
+ countTokens(texts, params = {}) {
119
+ return this._request('countTokens', { ...params, texts });
120
+ }
121
+
122
+ /**
123
+ * 关闭子进程(停服 / 安装前清理):先关 stdin 让它自己退,2s 未退再强杀,
124
+ * **返回时子进程已经退出**(或已被强杀)—— 调用方可以放心去删它映射过的 dll。
125
+ * @returns {Promise<void>}
126
+ */
127
+ async close() {
128
+ this._clearIdle();
129
+ const child = this._child;
130
+ this._child = null;
131
+ this._loaded = false;
132
+ this._buffer = '';
133
+ this._rejectAll(this._makeError('embed_worker_closed', 'embedding worker closed'));
134
+ if (!child) return;
135
+ // 已经退出(exitCode/signalCode 已置)就不必再等
136
+ if (child.exitCode !== null || child.signalCode !== null) return;
137
+ const exited = new Promise((resolve) => {
138
+ const timer = setTimeout(() => {
139
+ // 异常平台/极端场景下别把调用方吊死:发出强杀后即视为已关闭
140
+ try { child.kill('SIGKILL'); } catch { /* 已退出 */ }
141
+ resolve();
142
+ }, CLOSE_GRACE_MS);
143
+ if (typeof timer.unref === 'function') timer.unref();
144
+ child.once('exit', () => {
145
+ clearTimeout(timer);
146
+ resolve();
147
+ });
148
+ });
149
+ // 队列空了之后子进程是被 unref 的(空闲的子进程不该吊住 daemon),但 close() 承诺
150
+ // 「返回时进程已退出」—— 这里必须临时 ref 回来:否则事件循环会在等 exit 时直接排空,
151
+ // 进程带着「unsettled top-level await」退出(退出码 13),子进程根本没被杀。
152
+ this._refChild(child);
153
+ try { child.stdin.end(); } catch { /* 管道已断 */ }
154
+ await exited;
155
+ }
156
+
157
+ /**
158
+ * 排进串行队列
159
+ * @param {string} method
160
+ * @param {object} params
161
+ * @returns {Promise<any>}
162
+ */
163
+ _request(method, params) {
164
+ const run = this._chain.then(() => this._exec(method, params), () => this._exec(method, params));
165
+ this._chain = run.then(() => {}, () => {});
166
+ return run;
167
+ }
168
+
169
+ /**
170
+ * 真正发起一次往返
171
+ * @param {string} method
172
+ * @param {object} params
173
+ * @returns {Promise<any>}
174
+ */
175
+ async _exec(method, params) {
176
+ const remaining = this._cooldownUntil - Date.now();
177
+ if (remaining > 0) {
178
+ throw this._makeError(
179
+ 'embed_worker_cooldown',
180
+ `embedding worker paused after ${MAX_CONSECUTIVE_FAILURES} consecutive failures, retry in ${Math.ceil(remaining / 1000)}s`
181
+ );
182
+ }
183
+ if (this._cooldownUntil) {
184
+ // 冷却到点:计数必须一起归零。否则「连续 3 次」会退化成
185
+ // 「冷却结束后第一次失败就再锁 5 分钟」(计数已停在 3,一失败就是 4)
186
+ this._cooldownUntil = 0;
187
+ this._failures = 0;
188
+ }
189
+
190
+ const child = this._ensureChild();
191
+ const id = this._nextId++;
192
+ const timeoutMs = this._loaded ? this._opTimeoutMs : this._loadTimeoutMs;
193
+
194
+ try {
195
+ const result = await this._roundtrip(child, id, method, params, timeoutMs);
196
+ this._loaded = true;
197
+ this._failures = 0;
198
+ this._scheduleIdle();
199
+ return result;
200
+ } catch (err) {
201
+ this._noteFailure(err);
202
+ throw err;
203
+ }
204
+ }
205
+
206
+ /**
207
+ * 写一条请求并等对应 id 的响应
208
+ * @param {import('child_process').ChildProcess} child
209
+ * @param {number} id
210
+ * @param {string} method
211
+ * @param {object} params
212
+ * @param {number} timeoutMs
213
+ * @returns {Promise<any>}
214
+ */
215
+ _roundtrip(child, id, method, params, timeoutMs) {
216
+ this._clearIdle();
217
+ // 已有子进程时 _ensureChild 不会再 ref 一次,这里补上:在途请求必须持住事件循环
218
+ this._refChild(child);
219
+ return new Promise((resolve, reject) => {
220
+ const timer = setTimeout(() => {
221
+ // 子进程大概率卡在原生调用/下载里:杀掉,让下次请求重新 spawn
222
+ this._settle(id, this._makeError('embed_worker_timeout', `embedding worker ${method} timeout (${timeoutMs}ms)`));
223
+ this._dropChild('embed_worker_timeout');
224
+ }, timeoutMs);
225
+ if (typeof timer.unref === 'function') timer.unref();
226
+ this._pending.set(id, { method, resolve, reject, timer });
227
+ try {
228
+ child.stdin.write(`${JSON.stringify({ id, method, params })}\n`);
229
+ } catch (err) {
230
+ this._settle(id, this._makeError('embed_worker_write_failed', err.message || String(err)));
231
+ }
232
+ });
233
+ }
234
+
235
+ /**
236
+ * 懒启动子进程
237
+ * @returns {import('child_process').ChildProcess}
238
+ */
239
+ _ensureChild() {
240
+ if (this._child) return this._child;
241
+
242
+ const child = spawn(process.execPath, [this._workerPath], {
243
+ stdio: ['pipe', 'pipe', 'pipe'],
244
+ env: { ...process.env },
245
+ windowsHide: true,
246
+ });
247
+ child.stdout.setEncoding('utf8');
248
+ child.stderr.setEncoding('utf8');
249
+ child.stdout.on('data', (chunk) => { if (this._child === child) this._onStdout(chunk); });
250
+ child.stderr.on('data', (chunk) => this._forwardStderr(chunk));
251
+ // 管道断裂是以**异步 'error' 事件**报的(EPIPE / ERR_STREAM_DESTROYED),try/catch 拦不住;
252
+ // 三条管道任一没有 error 监听就会升级成 uncaughtException,把整个 daemon 带走。
253
+ // 真正的失败由 exit / _dropChild 统一收敛,这里只负责不让它升级成进程级异常。
254
+ for (const pipe of [child.stdin, child.stdout, child.stderr]) {
255
+ pipe.on('error', () => {});
256
+ }
257
+ // 监听器必须按「哪一个子进程」判定:close()/超时丢弃后可能已经起了新子进程,
258
+ // 旧进程的退出事件不能把新进程当成崩溃处理(否则下一次请求会被错误拒绝)
259
+ child.on('error', (err) => { if (this._child === child) this._dropChild('embed_worker_spawn_failed', err); });
260
+ child.on('exit', (code, signal) => { if (this._child === child) this._onExit(code, signal); });
261
+ // 子进程与三条管道默认持住事件循环:在途请求必须让父进程活着等结果
262
+ // (空闲时由 _unrefChild 释放,不阻止 daemon 正常退出)
263
+ this._refChild(child);
264
+
265
+ this._child = child;
266
+ this._buffer = '';
267
+ this._loaded = false;
268
+ console.log(`[RAG] embedding worker started (pid: ${child.pid})`);
269
+ return child;
270
+ }
271
+
272
+ /**
273
+ * 持住事件循环(有在途请求时)
274
+ * @param {import('child_process').ChildProcess} [target]
275
+ */
276
+ _refChild(target) {
277
+ for (const handle of [target, target?.stdin, target?.stdout, target?.stderr]) {
278
+ if (handle && typeof handle.ref === 'function') handle.ref();
279
+ }
280
+ }
281
+
282
+ /**
283
+ * 释放事件循环(空闲时):daemon 的存活不应由空闲的 embedding 子进程决定
284
+ */
285
+ _unrefChild() {
286
+ const child = this._child;
287
+ if (!child) return;
288
+ for (const handle of [child, child.stdin, child.stdout, child.stderr]) {
289
+ if (handle && typeof handle.unref === 'function') handle.unref();
290
+ }
291
+ }
292
+
293
+ /**
294
+ * 解析子进程 stdout 的 NDJSON 响应
295
+ * @param {string} chunk
296
+ */
297
+ _onStdout(chunk) {
298
+ this._buffer += chunk;
299
+ let index = this._buffer.indexOf('\n');
300
+ while (index >= 0) {
301
+ const line = this._buffer.slice(0, index).trim();
302
+ this._buffer = this._buffer.slice(index + 1);
303
+ if (line) this._handleLine(line);
304
+ index = this._buffer.indexOf('\n');
305
+ }
306
+ // 单行过长 = 协议错乱(正常响应远小于此):直接丢子进程,让在途请求立刻失败,
307
+ // 而不是留着半截 buffer 一直等到超时(那会表现为「检索卡 60s」而非「报错」)
308
+ if (this._buffer.length > PROTOCOL_LINE_MAX) {
309
+ this._dropChild('embed_worker_protocol_overflow');
310
+ }
311
+ }
312
+
313
+ /**
314
+ * 处理一行响应
315
+ * @param {string} line
316
+ */
317
+ _handleLine(line) {
318
+ let message;
319
+ try {
320
+ message = JSON.parse(line);
321
+ } catch {
322
+ console.error(`[RAG][embed] invalid protocol line: ${line.slice(0, STDERR_LINE_MAX)}`);
323
+ return;
324
+ }
325
+ const entry = this._pending.get(message?.id);
326
+ if (!entry) return;
327
+ if (message.ok) {
328
+ this._settle(message.id, null, message.result);
329
+ return;
330
+ }
331
+ const err = this._makeError(
332
+ message?.error?.code || 'embed_worker_failed',
333
+ message?.error?.message || 'embedding worker failed'
334
+ );
335
+ this._settle(message.id, err);
336
+ }
337
+
338
+ /**
339
+ * 转发子进程 stderr(模型加载/原生库报错都在这条通道)
340
+ * @param {string} chunk
341
+ */
342
+ _forwardStderr(chunk) {
343
+ for (const raw of chunk.split('\n')) {
344
+ const line = raw.trim();
345
+ if (line) console.error(`[RAG][embed] ${line.slice(0, STDERR_LINE_MAX)}`);
346
+ }
347
+ }
348
+
349
+ /**
350
+ * 子进程退出:拒绝所有在途请求
351
+ * @param {number|null} code
352
+ * @param {string|null} signal
353
+ */
354
+ _onExit(code, signal) {
355
+ const detail = signal ? `signal ${signal}` : `code ${code}`;
356
+ this._dropChild(code === 0 ? 'embed_worker_exited' : 'embed_worker_crashed', new Error(detail));
357
+ }
358
+
359
+ /**
360
+ * 结算单个请求(ok / 失败二选一,重复调用无副作用)
361
+ * @param {number} id
362
+ * @param {Error|null} err
363
+ * @param {any} [result]
364
+ */
365
+ _settle(id, err, result) {
366
+ const entry = this._pending.get(id);
367
+ if (!entry) return;
368
+ this._pending.delete(id);
369
+ clearTimeout(entry.timer);
370
+ if (this._pending.size === 0) {
371
+ // 队列空了:释放事件循环,下次请求前再由 _ensureChild 持住
372
+ this._unrefChild();
373
+ this._scheduleIdle();
374
+ }
375
+ if (err) entry.reject(err);
376
+ else entry.resolve(result);
377
+ }
378
+
379
+ /**
380
+ * 丢弃当前子进程:拒绝在途请求并强杀
381
+ * @param {string} code
382
+ * @param {Error} [cause]
383
+ */
384
+ _dropChild(code, cause) {
385
+ const child = this._child;
386
+ this._child = null;
387
+ this._loaded = false;
388
+ this._buffer = '';
389
+ this._clearIdle();
390
+ this._rejectAll(this._makeError(code, cause?.message ? `${code}: ${cause.message}` : code));
391
+ if (!child) return;
392
+ try { child.stdin.end(); } catch { /* 管道已断 */ }
393
+ try { child.kill('SIGKILL'); } catch { /* 已退出 */ }
394
+ }
395
+
396
+ /**
397
+ * 拒绝全部在途请求
398
+ * @param {Error} err
399
+ */
400
+ _rejectAll(err) {
401
+ const entries = Array.from(this._pending.values());
402
+ this._pending.clear();
403
+ for (const entry of entries) {
404
+ clearTimeout(entry.timer);
405
+ entry.reject(err);
406
+ }
407
+ }
408
+
409
+ /**
410
+ * 记一次失败(连续失败到阈值进入冷却)
411
+ * @param {Error} err
412
+ */
413
+ _noteFailure(err) {
414
+ this._failures += 1;
415
+ if (this._failures < MAX_CONSECUTIVE_FAILURES) return;
416
+ this._cooldownUntil = Date.now() + COOLDOWN_MS;
417
+ console.error(
418
+ `[RAG] embedding worker disabled for ${Math.round(COOLDOWN_MS / 60000)}min after ${this._failures} consecutive failures: ${err?.message || err}`
419
+ );
420
+ }
421
+
422
+ /**
423
+ * 空闲回收:无在途请求时挂一个 kill 定时器
424
+ */
425
+ _scheduleIdle() {
426
+ this._clearIdle();
427
+ if (!this._child || this._pending.size > 0) return;
428
+ if (!(this._idleMs > 0)) return;
429
+ this._idleTimer = setTimeout(() => {
430
+ this._idleTimer = null;
431
+ this.close().catch(() => {});
432
+ }, this._idleMs);
433
+ if (typeof this._idleTimer.unref === 'function') this._idleTimer.unref();
434
+ }
435
+
436
+ _clearIdle() {
437
+ if (!this._idleTimer) return;
438
+ clearTimeout(this._idleTimer);
439
+ this._idleTimer = null;
440
+ }
441
+
442
+ /**
443
+ * 构造带错误码的 Error
444
+ * @param {string} code
445
+ * @param {string} message
446
+ * @returns {Error}
447
+ */
448
+ _makeError(code, message) {
449
+ const err = new Error(message);
450
+ err.code = code;
451
+ return err;
452
+ }
453
+ }
454
+
455
+ /** 进程级单例(RAG 与长期记忆共用同一个子进程,模型只加载一份) */
456
+ let singleton = null;
457
+
458
+ /**
459
+ * 取进程级 embedding 子进程客户端
460
+ * @returns {EmbedWorkerClient}
461
+ */
462
+ export function getEmbedWorker() {
463
+ if (!singleton) singleton = new EmbedWorkerClient();
464
+ return singleton;
465
+ }
466
+
467
+ /**
468
+ * 关闭并丢弃单例(停服路径;下次调用会重新 spawn)
469
+ * @returns {Promise<void>}
470
+ */
471
+ export async function closeEmbedWorker() {
472
+ const current = singleton;
473
+ singleton = null;
474
+ if (!current) return;
475
+ await current.close();
476
+ }