ai-helper-agent 2.4.7 → 2.5.0
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/README.md +33 -1
- package/README.zh-CN.md +33 -1
- package/bin/agent.js +78 -0
- package/dist/assets/{agent-store-Wu4cQfi-.js → agent-store-D0oEv0PW.js} +1 -1
- package/dist/assets/background.js +5 -5
- package/dist/assets/chat-export-MTTSSIwM.js +37 -0
- package/dist/assets/content.js +41 -30
- package/dist/assets/{dist-LQPh1k0y.js → dist-BUuoW_84.js} +1 -1
- package/dist/assets/i18n-Br_sF5pb.js +49 -0
- package/dist/assets/{markdown-render-DsMFYJ7j.js → markdown-render-Dq5F_dqP.js} +2 -2
- package/dist/assets/{model-profiles-DWY7gG5H.js → model-profiles-BdQaV4EZ.js} +1 -1
- package/dist/assets/{options-Dir2xv8X.css → options-JtYgxtsc.css} +1 -1
- package/dist/assets/options.js +297 -238
- package/dist/assets/{page-snapshot-renderer-C0SlAjsY.js → page-snapshot-renderer-Cl0qk7U1.js} +1 -1
- package/dist/assets/{session-store-Dtfmjrt-.js → session-store-KkrAlIc6.js} +3 -3
- package/dist/assets/side_panel.css +1 -1
- package/dist/assets/side_panel.js +400 -400
- package/dist/assets/{utils-S-aJS9gf.js → utils-ZJjxSlg_.js} +1 -1
- package/dist/assets/{version-CcGQQNRR.js → version-C0CY79zF.js} +1 -1
- package/dist/manifest.json +1 -1
- package/dist/offscreen/offscreen.js +9 -9
- package/dist/options.html +38 -4
- package/dist/side_panel.html +25 -7
- package/dist/voice-capture-worklet.js +47 -0
- package/package.json +4 -1
- package/src/asr/config.js +155 -0
- package/src/asr/detect.js +215 -0
- package/src/asr/engine.js +347 -0
- package/src/asr/install.js +439 -0
- package/src/asr/model-catalog.js +207 -0
- package/src/asr/model-download.js +461 -0
- package/src/asr/model-pack.js +398 -0
- package/src/asr/offline-pool.js +283 -0
- package/src/asr/offline-worker.js +97 -0
- package/src/asr/probe-child.mjs +31 -0
- package/src/asr/routes.js +385 -0
- package/src/asr/session.js +435 -0
- package/src/asr/transcribe.js +310 -0
- package/src/directory-picker.js +549 -70
- package/src/locales/cli.json +26 -0
- package/src/locales/en.json +22 -1
- package/src/locales/zh.json +22 -1
- package/src/rag/install.js +60 -2
- package/src/server.js +168 -7
- package/dist/assets/chat-export-DYpi1VYc.js +0 -37
- package/dist/assets/i18n-DkQH7l0R.js +0 -49
package/src/locales/cli.json
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
"cmdConfig": " config 查看当前配置",
|
|
12
12
|
"cmdHelp": " help 显示此帮助信息",
|
|
13
13
|
"cmdRag": " rag 管理 RAG 可选依赖 (status | install)",
|
|
14
|
+
"cmdAsr": " asr 管理语音识别可选依赖 (status | install)",
|
|
14
15
|
"cmdUpdate": " update 检查并更新到最新版本 (--check 仅检查)",
|
|
15
16
|
"cmdUninstall": " uninstall 一键卸载代理端",
|
|
16
17
|
"cmdAutostart": " autostart 开机自启管理 (on | off)",
|
|
@@ -72,6 +73,18 @@
|
|
|
72
73
|
"ragRestartAdvice": "提示:若多次安装失败,可尝试重启代理服务(aha restart)后再重试。",
|
|
73
74
|
"ragUnknownSub": "未知的 rag 子命令: {sub}",
|
|
74
75
|
"ragHelpUsage": "用法: aha rag <status|install>",
|
|
76
|
+
"asrStatusTitle": "======= 语音识别(ASR)能力检测 ========",
|
|
77
|
+
"asrAvailable": "✅ 语音识别依赖已就绪",
|
|
78
|
+
"asrNotAvailable": "❌ 语音识别依赖未安装(可运行 aha asr install 一键安装)",
|
|
79
|
+
"asrProbeError": "探测详情: {reason}",
|
|
80
|
+
"asrInstalling": "正在安装语音识别依赖(sherpa-onnx-node,约 300MB+,可能需要几分钟)...",
|
|
81
|
+
"asrInstallFailed": "语音识别依赖安装失败(退出码 {code})",
|
|
82
|
+
"asrInstallSuccess": "✅ 语音识别依赖安装成功,功能已就绪",
|
|
83
|
+
"asrVerifyFailed": "npm 安装完成,但依赖验证未通过",
|
|
84
|
+
"asrRestartAdvice": "提示:若多次安装失败,可尝试重启代理服务(aha restart)后重试。",
|
|
85
|
+
"asrModelHint": "注意:依赖就绪后还需导入本地模型包(配置页 → 工具箱 → 语音输入 → 选择模型目录)。",
|
|
86
|
+
"asrUnknownSub": "未知的 asr 子命令: {sub}",
|
|
87
|
+
"asrHelpUsage": "用法: aha asr <status|install>",
|
|
75
88
|
"updateLatest": "已是最新版本 v{version}",
|
|
76
89
|
"updateAvailable": "发现新版本: v{current} → v{latest}(运行 aha update 更新)",
|
|
77
90
|
"updateInstalling": "正在更新 v{current} → v{latest}...",
|
|
@@ -103,6 +116,7 @@
|
|
|
103
116
|
"cmdConfig": " config View current configuration",
|
|
104
117
|
"cmdHelp": " help Show this help message",
|
|
105
118
|
"cmdRag": " rag Manage RAG optional dependencies (status | install)",
|
|
119
|
+
"cmdAsr": " asr Manage speech recognition optional dependencies (status | install)",
|
|
106
120
|
"cmdUpdate": " update Check and update to latest (--check for info only)",
|
|
107
121
|
"cmdUninstall": " uninstall One-click uninstall agent",
|
|
108
122
|
"cmdAutostart": " autostart Manage auto-start (on | off)",
|
|
@@ -164,6 +178,18 @@
|
|
|
164
178
|
"ragRestartAdvice": "Tip: if installation keeps failing, try restarting the agent (aha restart) and retry.",
|
|
165
179
|
"ragUnknownSub": "Unknown rag subcommand: {sub}",
|
|
166
180
|
"ragHelpUsage": "Usage: aha rag <status|install>",
|
|
181
|
+
"asrStatusTitle": "======= ASR Capability Check ========",
|
|
182
|
+
"asrAvailable": "✅ Speech recognition dependencies are ready",
|
|
183
|
+
"asrNotAvailable": "❌ Speech recognition dependencies not installed (run 'aha asr install')",
|
|
184
|
+
"asrProbeError": "Probe detail: {reason}",
|
|
185
|
+
"asrInstalling": "Installing speech recognition dependencies (sherpa-onnx-node, 300MB+, may take several minutes)...",
|
|
186
|
+
"asrInstallFailed": "Speech recognition dependency installation failed (exit code {code})",
|
|
187
|
+
"asrInstallSuccess": "✅ Speech recognition dependencies installed successfully",
|
|
188
|
+
"asrVerifyFailed": "npm install completed, but dependency verification failed",
|
|
189
|
+
"asrRestartAdvice": "Tip: if installation keeps failing, restart the agent (aha restart) and retry.",
|
|
190
|
+
"asrModelHint": "Note: local model packs must be imported too (Options -> Toolbox -> Voice Input -> Select model directory).",
|
|
191
|
+
"asrUnknownSub": "Unknown asr subcommand: {sub}",
|
|
192
|
+
"asrHelpUsage": "Usage: aha asr <status|install>",
|
|
167
193
|
"updateLatest": "Already at latest version v{version}",
|
|
168
194
|
"updateAvailable": "New version available: v{current} → v{latest} (run aha update)",
|
|
169
195
|
"updateInstalling": "Updating v{current} → v{latest}...",
|
package/src/locales/en.json
CHANGED
|
@@ -87,7 +87,8 @@
|
|
|
87
87
|
"stderrTruncated": "stderr output exceeded 5MB limit, truncated",
|
|
88
88
|
"ragNotAvailable": "RAG dependencies are not installed or the environment does not meet the requirements. Please install RAG dependencies on the agent side first",
|
|
89
89
|
"ragInstallInProgress": "RAG dependency installation is in progress, please try again later",
|
|
90
|
-
"ragLoadFailed": "Failed to load knowledge base module: {message} (try restarting the agent and retry)"
|
|
90
|
+
"ragLoadFailed": "Failed to load knowledge base module: {message} (try restarting the agent and retry)",
|
|
91
|
+
"asrNotAvailable": "Voice input dependencies are not installed or are being installed. Install them in Options → Toolbox → Voice Input"
|
|
91
92
|
},
|
|
92
93
|
"rag": {
|
|
93
94
|
"nodeVersionLow": "Node.js 22+ is required (current {version}), RAG features are unavailable",
|
|
@@ -307,6 +308,26 @@
|
|
|
307
308
|
"uncaughtException": "Uncaught exception",
|
|
308
309
|
"unhandledRejection": "Unhandled Promise rejection"
|
|
309
310
|
},
|
|
311
|
+
"asr": {
|
|
312
|
+
"depsMissing": "Optional speech recognition dependencies are not installed (Node.js 18+ required). Voice input is unavailable — install them in Options → Toolbox → Voice Input, or run `aha asr install`",
|
|
313
|
+
"depsReady": "Speech recognition dependencies detected",
|
|
314
|
+
"installRunning": "Dependency installation is already running, please retry later",
|
|
315
|
+
"installTimeout": "Dependency installation timed out (10 minutes). Check your network and retry",
|
|
316
|
+
"installAborted": "Dependency installation was aborted (agent stopped or process exited)",
|
|
317
|
+
"installFailed": "Dependency installation failed: {message}",
|
|
318
|
+
"verifyFailed": "npm install finished but dependency verification failed",
|
|
319
|
+
"pickModelDirTitle": "Select a speech model folder (must contain manifest.json)",
|
|
320
|
+
"modelInvalid": "Model pack validation failed: {reason}",
|
|
321
|
+
"invalidModelId": "Invalid model id: {id}",
|
|
322
|
+
"emptyAudio": "Audio payload is empty",
|
|
323
|
+
"invalidAudio": "Failed to decode audio payload",
|
|
324
|
+
"audioTooLarge": "Audio exceeds the size limit (max 5 minutes per recording)",
|
|
325
|
+
"modelMissing": "No usable speech model pack found. Import a finalize model in Options",
|
|
326
|
+
"unsupportedAudio": "Unsupported audio format (PCM WAV only)",
|
|
327
|
+
"transcribeFailed": "Speech recognition failed, please retry",
|
|
328
|
+
"downloadFailed": "Model download failed: {message}",
|
|
329
|
+
"downloadAborted": "Model download aborted (agent stopped or process exited)"
|
|
330
|
+
},
|
|
310
331
|
"memory": {
|
|
311
332
|
"missingAction": "Missing action parameter",
|
|
312
333
|
"missingType": "Missing type parameter",
|
package/src/locales/zh.json
CHANGED
|
@@ -87,7 +87,8 @@
|
|
|
87
87
|
"stderrTruncated": "stderr 输出超过 5MB 上限,已截断",
|
|
88
88
|
"ragNotAvailable": "RAG 功能依赖未安装或运行环境不满足要求,请先在代理端安装 RAG 依赖",
|
|
89
89
|
"ragInstallInProgress": "RAG 依赖安装正在进行中,请稍后再试",
|
|
90
|
-
"ragLoadFailed": "知识库模块加载失败: {message}(可尝试重启代理端后重试)"
|
|
90
|
+
"ragLoadFailed": "知识库模块加载失败: {message}(可尝试重启代理端后重试)",
|
|
91
|
+
"asrNotAvailable": "语音输入组件未安装或正在安装中,请先在配置页「工具箱 → 语音输入」安装组件"
|
|
91
92
|
},
|
|
92
93
|
"rag": {
|
|
93
94
|
"nodeVersionLow": "需要 Node.js 22+(当前 {version}),RAG 功能不可用",
|
|
@@ -307,6 +308,26 @@
|
|
|
307
308
|
"uncaughtException": "未捕获异常",
|
|
308
309
|
"unhandledRejection": "未处理的 Promise 拒绝"
|
|
309
310
|
},
|
|
311
|
+
"asr": {
|
|
312
|
+
"depsMissing": "语音识别可选依赖未安装(需 Node.js 18+),语音输入功能不可用(可在配置页「工具箱 → 语音输入」一键安装,或运行 aha asr install)",
|
|
313
|
+
"depsReady": "语音识别可选依赖检测通过",
|
|
314
|
+
"installRunning": "语音识别组件安装已在进行中,请稍后重试",
|
|
315
|
+
"installTimeout": "语音识别组件安装超时(10 分钟),请检查网络后重试",
|
|
316
|
+
"installAborted": "语音识别组件安装已中止(Agent 关闭或进程退出)",
|
|
317
|
+
"installFailed": "语音识别组件安装失败: {message}",
|
|
318
|
+
"verifyFailed": "npm 安装完成,但依赖验证未通过",
|
|
319
|
+
"pickModelDirTitle": "选择语音模型目录(内含 manifest.json)",
|
|
320
|
+
"modelInvalid": "模型包校验未通过: {reason}",
|
|
321
|
+
"invalidModelId": "非法模型 ID: {id}",
|
|
322
|
+
"emptyAudio": "音频内容为空",
|
|
323
|
+
"invalidAudio": "音频数据解析失败",
|
|
324
|
+
"audioTooLarge": "音频超过大小限制(单次录音上限 5 分钟)",
|
|
325
|
+
"modelMissing": "未找到可用的语音模型包,请在配置页导入定稿模型",
|
|
326
|
+
"unsupportedAudio": "不支持的音频格式(仅支持 PCM WAV)",
|
|
327
|
+
"transcribeFailed": "语音识别失败,请重试",
|
|
328
|
+
"downloadFailed": "模型下载失败: {message}",
|
|
329
|
+
"downloadAborted": "模型下载已中止(Agent 关闭或进程退出)"
|
|
330
|
+
},
|
|
310
331
|
"memory": {
|
|
311
332
|
"missingAction": "缺少 action 参数",
|
|
312
333
|
"missingType": "缺少 type 参数",
|
package/src/rag/install.js
CHANGED
|
@@ -66,6 +66,62 @@ export function getRagInstallSpecs() {
|
|
|
66
66
|
return RAG_DEPENDENCY_ENTRIES.map(([name, spec]) => `${name}@${spec}`);
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
/**
|
|
70
|
+
* 取 spec 的包名(兼容 scoped:@scope/pkg@^1.0.0 → @scope/pkg)
|
|
71
|
+
* @param {string} spec
|
|
72
|
+
* @returns {string}
|
|
73
|
+
*/
|
|
74
|
+
function specName(spec) {
|
|
75
|
+
const idx = spec.lastIndexOf('@');
|
|
76
|
+
return idx > 0 ? spec.slice(0, idx) : spec;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 读取「对侧」可选组件(ASR 语音输入)曾安装成功的依赖 spec,用于合并安装
|
|
81
|
+
*
|
|
82
|
+
* 背景(实测缺陷):ASR 与 RAG 的可选依赖都以 `npm install --no-save` 装在同一个
|
|
83
|
+
* 包目录里。npm 执行带包名的 install 时会按依赖树重算包目录,把不在本次清单内的
|
|
84
|
+
* 顶层包当作 extraneous 移除——只带自己清单安装,就会把 ASR 整组依赖清掉。
|
|
85
|
+
* 判据用对侧状态文件的 everSucceeded(持久化,不随目录被清而丢失):只要对方曾经
|
|
86
|
+
* 装成功过,就把它的清单一起带上,既避免互相清除,也顺带恢复已被清掉的对方。
|
|
87
|
+
* @returns {string[]}
|
|
88
|
+
*/
|
|
89
|
+
function readPeerPreservedSpecs() {
|
|
90
|
+
try {
|
|
91
|
+
const stateFile = join(homedir(), '.ai-helper-agent', 'asr-install-state.json');
|
|
92
|
+
if (!existsSync(stateFile)) return [];
|
|
93
|
+
const state = JSON.parse(readFileSync(stateFile, 'utf-8'));
|
|
94
|
+
if (!state || state.everSucceeded !== true) return [];
|
|
95
|
+
const raw = JSON.parse(readFileSync(join(getAgentRoot(), 'package.json'), 'utf-8'));
|
|
96
|
+
const deps = raw && typeof raw.asrDependencies === 'object' && raw.asrDependencies !== null
|
|
97
|
+
? raw.asrDependencies
|
|
98
|
+
: {};
|
|
99
|
+
return Object.entries(deps)
|
|
100
|
+
.filter(([name, spec]) => name && typeof spec === 'string' && spec.trim())
|
|
101
|
+
.map(([name, spec]) => `${name}@${spec}`);
|
|
102
|
+
} catch {
|
|
103
|
+
return [];
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 合并本组件清单与对侧保全清单(同名包以本组件 spec 为准,本组件顺序在前)
|
|
109
|
+
* @param {string[]} ownSpecs
|
|
110
|
+
* @param {string[]} peerSpecs
|
|
111
|
+
* @returns {string[]}
|
|
112
|
+
*/
|
|
113
|
+
function mergePreservedSpecs(ownSpecs, peerSpecs) {
|
|
114
|
+
const seen = new Set(ownSpecs.map(specName));
|
|
115
|
+
const merged = [...ownSpecs];
|
|
116
|
+
for (const spec of peerSpecs) {
|
|
117
|
+
const name = specName(spec);
|
|
118
|
+
if (!name || seen.has(name)) continue;
|
|
119
|
+
seen.add(name);
|
|
120
|
+
merged.push(spec);
|
|
121
|
+
}
|
|
122
|
+
return merged;
|
|
123
|
+
}
|
|
124
|
+
|
|
69
125
|
/**
|
|
70
126
|
* Windows:定位与 node 同目录分布的 npm-cli.js(官方安装器 / nvm-windows 结构)
|
|
71
127
|
* @param {string} execPath
|
|
@@ -91,11 +147,13 @@ function findWinNpmCli(execPath) {
|
|
|
91
147
|
export function buildRagInstallCommand(opts = {}) {
|
|
92
148
|
const isWin = opts.isWin ?? process.platform === 'win32';
|
|
93
149
|
const execPath = opts.execPath ?? process.execPath;
|
|
94
|
-
const
|
|
95
|
-
if (
|
|
150
|
+
const ownSpecs = opts.specs ?? getRagInstallSpecs();
|
|
151
|
+
if (ownSpecs.length === 0) {
|
|
96
152
|
// 包损坏/被裁剪:拒绝构建(无包名参数的 npm install 会按依赖树重算包目录,不可接受)
|
|
97
153
|
throw new Error('ragDependencies missing in package.json');
|
|
98
154
|
}
|
|
155
|
+
// 显式注入 specs(测试/诊断)视为精确清单,不做对侧保全
|
|
156
|
+
const specs = opts.specs ? ownSpecs : mergePreservedSpecs(ownSpecs, readPeerPreservedSpecs());
|
|
99
157
|
// 如果有探测出的镜像 registry,自动注入(npm -g 用户无 mirrors.json 时此值为 undefined)
|
|
100
158
|
const registryUrl = opts.registry ?? getRegistryUrl();
|
|
101
159
|
const baseArgs = ['install', '--no-save', '--no-audit', '--no-fund'];
|
package/src/server.js
CHANGED
|
@@ -19,6 +19,12 @@ import { setConsoleOutput, setLoggerLocale, logAuth, logFs, logExec, logSecurity
|
|
|
19
19
|
import { initSearchTools, getSearchToolsAvailable, searchFiles, searchContent, setSearchLang } from './search.js';
|
|
20
20
|
import { detectRagAvailable, isRagAvailable, resetRagDetection, setRagLang, getLastRagProbeError } from './rag/detect.js';
|
|
21
21
|
import { startRagInstall, getRagInstallStatus, stopRagInstall, maybeAutoRestoreRagDeps } from './rag/install.js';
|
|
22
|
+
import { detectAsrAvailable, isAsrAvailable, resetAsrDetection, setAsrLang, getLastAsrProbeError } from './asr/detect.js';
|
|
23
|
+
import { startAsrInstall, getAsrInstallStatus, stopAsrInstall } from './asr/install.js';
|
|
24
|
+
import { asrRouter, isDepsIndependentPath as isAsrDepsIndependentPath, resolveAsrModels } from './asr/routes.js';
|
|
25
|
+
import { createAsrSessionManager } from './asr/session.js';
|
|
26
|
+
import { getAsrConfig } from './asr/config.js';
|
|
27
|
+
import { warmupAsrEngines, closeOfflinePool } from './asr/offline-pool.js';
|
|
22
28
|
import { memoryRouter } from './memory/routes.js';
|
|
23
29
|
import { stopProcessTree } from './process-tree.js';
|
|
24
30
|
import {
|
|
@@ -497,7 +503,10 @@ export function startServer() {
|
|
|
497
503
|
arch: PLATFORM_INFO.arch,
|
|
498
504
|
nodeVersion: PLATFORM_INFO.nodeVersion,
|
|
499
505
|
searchTools: getSearchToolsAvailable(),
|
|
500
|
-
ragAvailable: isRagAvailable()
|
|
506
|
+
ragAvailable: isRagAvailable(),
|
|
507
|
+
// 语音输入:只暴露「依赖是否就绪」与「用户是否启用」,模型清单走 /api/asr/status
|
|
508
|
+
asrDepsAvailable: isAsrAvailable(),
|
|
509
|
+
asrEnabled: getAsrConfig().enabled,
|
|
501
510
|
});
|
|
502
511
|
}
|
|
503
512
|
|
|
@@ -746,7 +755,9 @@ export function startServer() {
|
|
|
746
755
|
},
|
|
747
756
|
...PLATFORM_INFO,
|
|
748
757
|
searchTools: getSearchToolsAvailable(),
|
|
749
|
-
ragAvailable: isRagAvailable()
|
|
758
|
+
ragAvailable: isRagAvailable(),
|
|
759
|
+
asrDepsAvailable: isAsrAvailable(),
|
|
760
|
+
asrEnabled: getAsrConfig().enabled,
|
|
750
761
|
});
|
|
751
762
|
}
|
|
752
763
|
|
|
@@ -995,15 +1006,46 @@ export function startServer() {
|
|
|
995
1006
|
logSecurity('pick_directory_remote_blocked', { remote: remoteIp, extId });
|
|
996
1007
|
return jsonResponse(res, 200, { success: false, path: null, available: false, error: 'remote-source' });
|
|
997
1008
|
}
|
|
1009
|
+
// 这是全服务里唯一可能耗时数分钟的端点(等用户选目录):客户端很可能在此期间
|
|
1010
|
+
// 关闭侧边栏/断开。向已销毁的 res 写入会触发流错误,因此统一走安全响应。
|
|
1011
|
+
const respond = (payload) => {
|
|
1012
|
+
if (res.writableEnded || res.destroyed) return;
|
|
1013
|
+
try {
|
|
1014
|
+
jsonResponse(res, 200, payload);
|
|
1015
|
+
} catch (err) {
|
|
1016
|
+
try { logError('config', 'pick_directory_respond_failed', { error: err.message }); } catch { /* 日志失败不影响进程 */ }
|
|
1017
|
+
}
|
|
1018
|
+
};
|
|
998
1019
|
try {
|
|
999
|
-
const
|
|
1020
|
+
const title = typeof body.title === 'string' ? body.title.slice(0, 120) : '';
|
|
1021
|
+
// pickDirectoryNative 内部已做多后端兜底、超时强杀与异常吸收,此处只会拿到结果对象
|
|
1022
|
+
const result = await pickDirectoryNative(title);
|
|
1000
1023
|
if (result.success && result.path) {
|
|
1001
|
-
logSystem('directory_picked', { path: result.path, extId });
|
|
1024
|
+
logSystem('directory_picked', { path: result.path, backend: result.backend || '', extId });
|
|
1025
|
+
} else if (!result.success && result.error !== 'busy') {
|
|
1026
|
+
// busy 是并发保护的正常分支(已有窗口在等),不算失败
|
|
1027
|
+
// 其余记录各后端真实失败原因(无桌面会话 / 被安全策略拦截 / 超时等),
|
|
1028
|
+
// 用户端只看得到摘要,完整 attempts 落到日志里备查
|
|
1029
|
+
// environment 快照记录父进程环境特征(SystemRoot/pathStartsWithPosix/stdoutIsTTY):
|
|
1030
|
+
// 实测同一个 Windows 上 CMD 启动能弹窗、PowerShell/Git Bash 启动弹不出来,
|
|
1031
|
+
// 这三项是区分各终端的直接证据
|
|
1032
|
+
logError('config', 'pick_directory_failed', {
|
|
1033
|
+
error: result.error,
|
|
1034
|
+
backend: result.backend || '',
|
|
1035
|
+
exitCode: result.exitCode,
|
|
1036
|
+
available: result.available,
|
|
1037
|
+
attempts: Array.isArray(result.attempts) ? result.attempts : [],
|
|
1038
|
+
environment: result.environment || null,
|
|
1039
|
+
extId,
|
|
1040
|
+
});
|
|
1002
1041
|
}
|
|
1003
|
-
|
|
1042
|
+
respond(result);
|
|
1043
|
+
return;
|
|
1004
1044
|
} catch (err) {
|
|
1005
|
-
|
|
1006
|
-
|
|
1045
|
+
// 兜底:即便 picker 自身出意外,也只返回结构化错误,不影响 agent 其它接口
|
|
1046
|
+
try { logError('config', 'pick_directory_error', { error: err.message }); } catch { /* 日志失败不影响进程 */ }
|
|
1047
|
+
respond({ success: false, path: null, available: true, error: err.message });
|
|
1048
|
+
return;
|
|
1007
1049
|
}
|
|
1008
1050
|
}
|
|
1009
1051
|
|
|
@@ -2102,6 +2144,43 @@ export function startServer() {
|
|
|
2102
2144
|
return ragRouter(req, res, pathname, url, t, requestBody);
|
|
2103
2145
|
}
|
|
2104
2146
|
|
|
2147
|
+
// ========== 语音输入(本地 STT)接口(可选组件,默认不装不启用) ==========
|
|
2148
|
+
|
|
2149
|
+
if (pathname.startsWith('/api/asr/')) {
|
|
2150
|
+
// 依赖安装/检测:固定白名单 + 强制 Bearer(位于认证区,不走本机来源免认证豁免)
|
|
2151
|
+
if (req.method === 'POST' && pathname === '/api/asr/deps/install') {
|
|
2152
|
+
if (agentOperationInProgress) {
|
|
2153
|
+
return jsonResponse(res, 409, { success: false, error: t('error.operationInProgress') });
|
|
2154
|
+
}
|
|
2155
|
+
const result = startAsrInstall(t);
|
|
2156
|
+
if (result.started) logSystem('asr_install', { reason: 'api_request', extId });
|
|
2157
|
+
// 已在安装中一律回 200 + alreadyRunning:这是幂等重入而非错误,
|
|
2158
|
+
// 前端据此继续轮询进度,避免把「重复点击」误报成「安装失败」
|
|
2159
|
+
return jsonResponse(res, 200, result);
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
if (req.method === 'GET' && pathname === '/api/asr/deps/install/status') {
|
|
2163
|
+
return jsonResponse(res, 200, getAsrInstallStatus());
|
|
2164
|
+
}
|
|
2165
|
+
|
|
2166
|
+
if (req.method === 'POST' && pathname === '/api/asr/deps/detect') {
|
|
2167
|
+
resetAsrDetection();
|
|
2168
|
+
const available = await detectAsrAvailable({ force: true });
|
|
2169
|
+
return jsonResponse(res, 200, {
|
|
2170
|
+
success: true,
|
|
2171
|
+
available,
|
|
2172
|
+
error: available ? null : getLastAsrProbeError(),
|
|
2173
|
+
});
|
|
2174
|
+
}
|
|
2175
|
+
|
|
2176
|
+
// 依赖不可用时的降级:只拦截真正需要引擎的端点;
|
|
2177
|
+
// status / config / models* 必须可用,否则配置页无法告诉用户「缺哪一环」
|
|
2178
|
+
if (!isAsrDepsIndependentPath(pathname) && !isAsrAvailable()) {
|
|
2179
|
+
return jsonResponse(res, 503, { success: false, code: 'deps_missing', error: t('error.asrNotAvailable') });
|
|
2180
|
+
}
|
|
2181
|
+
return asrRouter(req, res, pathname, url, t, requestBody);
|
|
2182
|
+
}
|
|
2183
|
+
|
|
2105
2184
|
// 长期记忆业务端点(逻辑与数据文件同侧;零外部依赖,静态加载)
|
|
2106
2185
|
if (pathname.startsWith('/api/memory/')) {
|
|
2107
2186
|
return memoryRouter(req, res, pathname, url, t, requestBody);
|
|
@@ -2122,6 +2201,17 @@ export function startServer() {
|
|
|
2122
2201
|
// ==================== WebSocket Server ====================
|
|
2123
2202
|
const wss = new WebSocketServer({ noServer: true });
|
|
2124
2203
|
|
|
2204
|
+
// 语音输入流式会话管理器(进程级单例;并发上限见 asr/config.js)
|
|
2205
|
+
const asrSessions = createAsrSessionManager({
|
|
2206
|
+
getModels: () => {
|
|
2207
|
+
const resolved = resolveAsrModels();
|
|
2208
|
+
return { online: resolved.online, offline: resolved.offline, vad: resolved.vad };
|
|
2209
|
+
},
|
|
2210
|
+
getIdleUnloadMs: () => getAsrConfig().idleUnloadMs,
|
|
2211
|
+
onError: (stage, err) => logError('system', 'asr_session_error', { stage, error: err?.message || String(err) }),
|
|
2212
|
+
onLog: (event, payload) => logSystem(event, payload),
|
|
2213
|
+
});
|
|
2214
|
+
|
|
2125
2215
|
server.on('upgrade', (request, socket, head) => {
|
|
2126
2216
|
let url;
|
|
2127
2217
|
try {
|
|
@@ -2183,6 +2273,47 @@ export function startServer() {
|
|
|
2183
2273
|
disconnectWsClient(execId, ws);
|
|
2184
2274
|
});
|
|
2185
2275
|
});
|
|
2276
|
+
} else if (pathParts[1] === 'ws' && pathParts[2] === 'asr') {
|
|
2277
|
+
// 语音输入流式通道:鉴权规则与 /ws/exec 完全一致(Header 优先,回退 ?token=)
|
|
2278
|
+
const asrSessionId = pathParts[3] || randomBytes(8).toString('hex');
|
|
2279
|
+
const wsLang = getRequestI18n(request).lang;
|
|
2280
|
+
setAsrLang(wsLang);
|
|
2281
|
+
|
|
2282
|
+
const authHeader = request.headers.authorization;
|
|
2283
|
+
let asrToken = null;
|
|
2284
|
+
if (authHeader && authHeader.startsWith('Bearer ')) asrToken = authHeader.slice(7);
|
|
2285
|
+
else asrToken = url.searchParams.get('token');
|
|
2286
|
+
if (!verifyToken(asrToken)) {
|
|
2287
|
+
logSecurity('ws_asr_auth_invalid', { sessionId: asrSessionId });
|
|
2288
|
+
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
|
|
2289
|
+
socket.destroy();
|
|
2290
|
+
return;
|
|
2291
|
+
}
|
|
2292
|
+
|
|
2293
|
+
// 依赖不可用时直接拒连(客户端按 deps_missing 引导用户去安装)
|
|
2294
|
+
if (!isAsrAvailable()) {
|
|
2295
|
+
socket.write('HTTP/1.1 503 Service Unavailable\r\n\r\n');
|
|
2296
|
+
socket.destroy();
|
|
2297
|
+
return;
|
|
2298
|
+
}
|
|
2299
|
+
|
|
2300
|
+
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
2301
|
+
// 控制面心跳:与 /ws/exec 同节奏,检测半开连接
|
|
2302
|
+
ws.isAlive = true;
|
|
2303
|
+
ws.on('pong', () => { ws.isAlive = true; });
|
|
2304
|
+
const heartbeat = setInterval(() => {
|
|
2305
|
+
if (ws.readyState !== 1) { clearInterval(heartbeat); return; }
|
|
2306
|
+
if (!ws.isAlive) { try { ws.terminate(); } catch {} clearInterval(heartbeat); return; }
|
|
2307
|
+
ws.isAlive = false;
|
|
2308
|
+
ws.ping();
|
|
2309
|
+
}, 30000);
|
|
2310
|
+
heartbeat.unref();
|
|
2311
|
+
ws.on('close', () => clearInterval(heartbeat));
|
|
2312
|
+
|
|
2313
|
+
asrSessions.attach(ws, asrSessionId, {
|
|
2314
|
+
language: url.searchParams.get('language') || getAsrConfig().language,
|
|
2315
|
+
});
|
|
2316
|
+
});
|
|
2186
2317
|
} else {
|
|
2187
2318
|
socket.destroy();
|
|
2188
2319
|
}
|
|
@@ -2211,6 +2342,7 @@ export function startServer() {
|
|
|
2211
2342
|
setSecurityLang(serverLang);
|
|
2212
2343
|
setSearchLang(serverLang);
|
|
2213
2344
|
setRagLang(serverLang);
|
|
2345
|
+
setAsrLang(serverLang);
|
|
2214
2346
|
setSkillLoaderLang(serverLang);
|
|
2215
2347
|
setSkillRegistryLang(serverLang);
|
|
2216
2348
|
setSkillExecutorLang(serverLang);
|
|
@@ -2238,6 +2370,29 @@ export function startServer() {
|
|
|
2238
2370
|
console.error(`[Agent] ${ln('skillInitFailed')}:`, err.message);
|
|
2239
2371
|
}
|
|
2240
2372
|
})();
|
|
2373
|
+
|
|
2374
|
+
// 语音输入:零成本磁盘判定 → 必要时子进程探测 → 预热(全异步,不阻塞启动)
|
|
2375
|
+
// 未装依赖的用户不会付出任何探测/加载开销(见 asr/detect.js 文件头)。
|
|
2376
|
+
(async () => {
|
|
2377
|
+
try {
|
|
2378
|
+
const available = await detectAsrAvailable();
|
|
2379
|
+
if (!available) return;
|
|
2380
|
+
const config = getAsrConfig();
|
|
2381
|
+
if (!config.enabled) return;
|
|
2382
|
+
const resolved = resolveAsrModels();
|
|
2383
|
+
if (!resolved.online && !resolved.offline) return;
|
|
2384
|
+
// 流式引擎在主线程预热,offline 引擎在 worker 线程预热(不阻塞启动,也不重复驻留模型)
|
|
2385
|
+
const result = await warmupAsrEngines(resolved, { idleUnloadMs: config.idleUnloadMs });
|
|
2386
|
+
if (result.failed.length > 0) {
|
|
2387
|
+
logError('system', 'asr_warmup_failed', { failed: result.failed });
|
|
2388
|
+
}
|
|
2389
|
+
if (result.warmed.length > 0) {
|
|
2390
|
+
logSystem('asr_warmup', { warmed: result.warmed, trigger: 'startup' });
|
|
2391
|
+
}
|
|
2392
|
+
} catch (err) {
|
|
2393
|
+
console.error(`[Agent] ASR warmup failed:`, err.message);
|
|
2394
|
+
}
|
|
2395
|
+
})();
|
|
2241
2396
|
});
|
|
2242
2397
|
|
|
2243
2398
|
/**
|
|
@@ -2291,6 +2446,12 @@ export function startServer() {
|
|
|
2291
2446
|
// 中止 RAG 依赖安装并回收 npm 进程树(R1/R3):不留孤儿 npm 继续写 node_modules
|
|
2292
2447
|
try { await stopRagInstall(); } catch {}
|
|
2293
2448
|
|
|
2449
|
+
// 中止 ASR 依赖安装 + 释放全部流式会话(不留孤儿 npm / 原生引擎句柄)
|
|
2450
|
+
try { await stopAsrInstall(); } catch {}
|
|
2451
|
+
try { asrSessions.closeAll(); } catch {}
|
|
2452
|
+
// offline 定稿线程也要收掉:native 会话持有几百 MB,进程退出前让它先 free
|
|
2453
|
+
try { await closeOfflinePool(); } catch {}
|
|
2454
|
+
|
|
2294
2455
|
// 终止所有运行中的进程
|
|
2295
2456
|
for (const entry of getRunningProcesses()) {
|
|
2296
2457
|
killProcess(entry.execId);
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import{a as e,c as t,l as n}from"./i18n-DkQH7l0R.js";import{C as r}from"./utils-S-aJS9gf.js";import{f as i,h as a,m as o,s}from"./markdown-render-DsMFYJ7j.js";import{BorderStyle as c,Document as l,ExternalHyperlink as u,HeadingLevel as d,ImageRun as f,Packer as p,Paragraph as m,Table as h,TableCell as g,TableRow as _,TextRun as v,WidthType as y,convertInchesToTwip as b}from"./dist-LQPh1k0y.js";e(`zh`,{chatExport:{exportFailed:`导出失败:{message}`,pdfLibNotLoaded:`PDF 库未加载,无法导出`,noContent:`没有可导出的内容`,imageLibNotLoaded:`图片库未加载,无法导出为图片`,imagePlaceholder:`[图片: {name}]`,canvasFailed:`Canvas 转 DataURL 失败:{message}`,svgLoadFailed:`SVG 图片加载失败`}}),e(`en`,{chatExport:{exportFailed:`Export failed: {message}`,pdfLibNotLoaded:`PDF library not loaded, cannot export`,noContent:`No content to export`,imageLibNotLoaded:`Image library not loaded, cannot export as image`,imagePlaceholder:`[Image: {name}]`,canvasFailed:`Canvas to DataURL failed: {message}`,svgLoadFailed:`SVG image loading failed`}});var x=new Map,S=/Mac|iPhone|iPad|iPod/i.test(typeof navigator<`u`?navigator.userAgent:``)?`Apple Color Emoji`:`Segoe UI Emoji`,C=RegExp(`(?:\\p{Emoji_Presentation}|\\p{Extended_Pictographic}\\uFE0F)(?:[\\u{1F3FB}-\\u{1F3FF}]|\\u200D(?:\\p{Emoji_Presentation}|\\p{Extended_Pictographic}\\uFE0F))*`,`gu`);function w(e,t={}){if(!e)return[];let n=[],r=0;for(let i of e.matchAll(C))i.index>r&&n.push(new v({...t,text:e.slice(r,i.index)})),n.push(new v({...t,text:i[0],font:{name:S}})),r=i.index+i[0].length;return r<e.length&&n.push(new v({...t,text:e.slice(r)})),n}function T(e){if(!e)return[];let r=/(\*\*(.+?)\*\*|(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)|__(.+?)__|(?<!_)_(?!_)(.+?)(?<!_)_(?!_)|`([^`]+)`|\[([^\]]+)\]\(([^)]+)\)|!\[([^\]]*)\]\(([^)]+)\))/,i=[],a=e;for(;a.length>0;){let e=a.match(r);if(!e){i.push(...w(a));break}let o=e.index;o>0&&i.push(...w(a.slice(0,o)));let s=e[1];if(e[2]!==void 0)i.push(...w(e[2],{bold:!0}));else if(e[3]!==void 0)i.push(...w(e[3],{italics:!0}));else if(e[4]!==void 0)i.push(...w(e[4],{bold:!0}));else if(e[5]!==void 0)i.push(...w(e[5],{italics:!0}));else if(e[6]!==void 0)i.push(new v({text:e[6],font:`Consolas`,size:20}));else if(e[7]!==void 0)i.push(new u({children:[new v({text:e[7],style:`Hyperlink`})],link:e[8]}));else if(e[9]!==void 0){let r=e[10];if(r.startsWith(`data:`))try{let[e,t]=r.split(`,`),n=e.match(/data:(image\/(\w+))/);if(n&&t){let e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);let a=n[2],o=E(r,a),s=o.width,c=o.height;if(s>567){let e=567/s;s=Math.round(s*e),c=Math.round(c*e)}i.push(new f({data:r,transformation:{width:s,height:c},type:a}))}}catch(r){n.warn(`[ChatExport] ImageRun create failed:`,r.message),i.push(new v({text:t(`chatExport.imagePlaceholder`,{name:e[9]||`image`}),italics:!0,color:`999999`}))}else i.push(new v({text:t(`chatExport.imagePlaceholder`,{name:e[9]||r}),italics:!0,color:`999999`}))}a=a.slice(o+s.length)}return i}function E(e,t){if(t===`png`&&e.length>24){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{width:t.getUint32(16),height:t.getUint32(20)}}if((t===`jpeg`||t===`jpg`)&&e.length>100){let t=2;for(;t<e.length-9;)if(e[t]===255){let n=e[t+1];if(n>=192&&n<=195){let n=new DataView(e.buffer,e.byteOffset,e.byteLength);return{height:n.getUint16(t+5),width:n.getUint16(t+7)}}t+=2+(e[t+2]<<8|e[t+3])}else t++}return{width:600,height:400}}async function D(e){if(!e||!e.trim())return[new m({children:[new v({text:``})]})];let t=[],n=e,r=[];n=n.replace(/```(\w*)\n([\s\S]*?)```/g,(e,t,n)=>{let i=r.length;return r.push({lang:t||``,code:n.trimEnd()}),`\n\n%%CODEBLOCK_${i}%%\n\n`});let i=[];n=n.replace(/<table[\s\S]*?<\/table>/gi,e=>{let t=i.length;return i.push(e),`\n\n%%HTMLTABLE_${t}%%\n\n`});let a=[];n=n.replace(/(?:^\|.+\|\s*$\n)+^\|[\s\-:|]+\|\s*$\n(?:^\|.+\|\s*$\n?)+/gm,e=>{let t=a.length;return a.push(e),`\n\n%%MDTABLE_${t}%%\n\n`});let o=n.split(/\n{2,}/).filter(e=>e.trim());for(let e of o){let n=e.trim(),o=n.match(/^%%CODEBLOCK_(\d+)%%$/);if(o){let{lang:e,code:n}=r[parseInt(o[1])],i=e?`${e} code`:`code`;t.push(new m({children:[new v({text:i,bold:!0,font:`Consolas`,size:18})]}));let a=n.split(`
|
|
2
|
-
`);for(let e of a)t.push(new m({children:[new v({text:e||` `,font:`Consolas`,size:18})],spacing:{before:0,after:0,line:240},shading:{fill:`F5F5F5`}}));t.push(new m({children:[new v({text:``})]}));continue}let s=n.match(/^%%HTMLTABLE_(\d+)%%$/);if(s){let e=i[parseInt(s[1])],n=O(e);n.length>0&&(t.push(A(n)),t.push(new m({children:[new v({text:``})]})));continue}let l=n.match(/^%%MDTABLE_(\d+)%%$/);if(l){let e=a[parseInt(l[1])],n=k(e);t.push(A(n)),t.push(new m({children:[new v({text:``})]}));continue}let u=n.match(/^(#{1,6})\s+(.+)/);if(u){let e=u[1].length,r=u[2],i={1:d.HEADING_1,2:d.HEADING_2,3:d.HEADING_3,4:d.HEADING_4,5:d.HEADING_5,6:d.HEADING_6};t.push(new m({children:T(r),heading:i[e]||d.HEADING_1,border:{bottom:{style:c.SINGLE,size:6,color:`EAECEF`}}}));let a=n.slice(u[0].length).replace(/^\n+/,``).trim();a&&t.push(new m({children:T(a),spacing:{before:60,after:60}}));continue}if(/^(---|\*\*\*|___)\s*$/.test(n)){t.push(new m({children:[],border:{bottom:{style:c.SINGLE,size:6,color:`CCCCCC`}},spacing:{before:200,after:200}}));continue}if(/^[\-\*\+]\s+/.test(n)){let n=e.split(/\n(?=[\-\*\+]\s+)/);for(let e of n){let n=e.replace(/^[\-\*\+]\s+/,``);t.push(new m({children:T(n),bullet:{level:0},spacing:{before:40,after:40}}))}continue}if(/^\d+\.\s+/.test(n)){let n=e.split(/\n(?=\d+\.\s+)/);for(let e of n){let n=e.replace(/^\d+\.\s+/,``);t.push(new m({children:T(n),numbering:{reference:`default`,level:0},spacing:{before:40,after:40}}))}continue}if(n.startsWith(`>`)){let n=e.split(`
|
|
3
|
-
`).map(e=>e.replace(/^>\s?/,``)).join(`
|
|
4
|
-
`);t.push(new m({children:T(n),indent:{left:b(.5)},border:{left:{style:c.SINGLE,size:12,color:`CCCCCC`}},spacing:{before:60,after:60}}));continue}let f=T(n);t.push(new m({children:f.length>0?f:w(n),spacing:{before:60,after:60}}))}return t}function O(e){let t=new DOMParser().parseFromString(e,`text/html`),n=[];return t.querySelectorAll(`tr`).forEach(e=>{let t=[];e.querySelectorAll(`th, td`).forEach(e=>{t.push(e.textContent.trim())}),t.length>0&&n.push(t)}),n}function k(e){let t=e.trim().split(`
|
|
5
|
-
`),n=[];for(let e of t){if(/^[\s\|:\-]+$/.test(e.replace(/\|/g,``)))continue;let t=i(e).slice(1,-1).map(e=>e.trim());t.length>0&&n.push(t)}return n}function A(e){if(e.length===0)return new m({children:[]});let t=Math.max(...e.map(e=>e.length));return new h({rows:e.map((e,n)=>{let r=[];for(let i=0;i<t;i++){let a=e[i]||``;r.push(new g({children:[new m({children:T(a),spacing:{before:40,after:40}})],shading:n===0?{fill:`F2F2F2`}:void 0,width:{size:100/t,type:y.PERCENTAGE}}))}return new _({children:r})}),width:{size:100,type:y.PERCENTAGE},borders:{top:{style:c.SINGLE,size:1,color:`DDDDDD`},bottom:{style:c.SINGLE,size:1,color:`DDDDDD`},left:{style:c.SINGLE,size:1,color:`DDDDDD`},right:{style:c.SINGLE,size:1,color:`DDDDDD`},insideHorizontal:{style:c.SINGLE,size:1,color:`DDDDDD`},insideVertical:{style:c.SINGLE,size:1,color:`DDDDDD`}}})}function j(e){try{let t=e.toDataURL(`image/jpeg`,.85);if(t&&t.length>100)return{dataUrl:t,format:`JPEG`}}catch(e){n.debug(`[ChatExport] JPEG toDataURL failed, downgrade to PNG:`,e.message)}try{return{dataUrl:e.toDataURL(`image/png`),format:`PNG`}}catch{try{return{dataUrl:e.toDataURL(`image/jpeg`,.5),format:`JPEG`}}catch(e){throw Error(t(`chatExport.canvasFailed`,{message:e.message}))}}}async function M(e){if(typeof mermaid>`u`)return;let t=e.querySelectorAll(`.mermaid`);if(t.length!==0){for(let e of t)if(!e.querySelector(`svg`))try{await mermaid.run({nodes:[e]})}catch(e){n.warn(`[SidePanel] exporthour mermaid render failed:`,e)}}}function N(e){let t=e.closest(`.mermaid`);if(!t)return!1;let n=t.getAttribute(`data-raw-code`);if(!n)return!1;try{let e=decodeURIComponent(n);return/^\s*classDiagram/im.test(e)}catch{return!1}}function P(e){e.querySelectorAll(`foreignObject`).forEach(e=>{let t=e.querySelector(`div`);if(!t){e.remove();return}let n=t.querySelector(`span`),r=(n||t).textContent.trim();if(!r){e.remove();return}let i=parseFloat(e.getAttribute(`width`))||100,a=parseFloat(e.getAttribute(`height`))||30,o=e.getAttribute(`transform`),s=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);s.setAttribute(`x`,String(i/2)),s.setAttribute(`y`,String(a/2)),s.setAttribute(`text-anchor`,`middle`),s.setAttribute(`dominant-baseline`,`central`),o&&s.setAttribute(`transform`,o);let c=n?n.getAttribute(`class`):``;c&&s.setAttribute(`class`,c),s.textContent=r,e.parentNode.replaceChild(s,e)})}async function F(e){let r=e.querySelectorAll(`svg`);if(r.length!==0)for(let e of r)try{let n=e.cloneNode(!0);N(e)?P(n):n.querySelectorAll(`foreignObject`).forEach(e=>{let t=e.querySelector(`div`);if(!t)return;let n=document.createElementNS(`http://www.w3.org/2000/svg`,`text`),r=parseFloat(e.getAttribute(`x`))||0,i=parseFloat(e.getAttribute(`y`))||0,a=parseFloat(e.getAttribute(`width`))||100,o=parseFloat(e.getAttribute(`height`))||30;window.getComputedStyle(t);let s=t.querySelector(`span`)||t,c=window.getComputedStyle(s);n.textContent=s.textContent.trim(),n.setAttribute(`x`,String(r+a/2)),n.setAttribute(`y`,String(i+o/2)),n.setAttribute(`text-anchor`,`middle`),n.setAttribute(`dominant-baseline`,`central`),n.setAttribute(`fill`,c.color||`#333`),n.setAttribute(`font-family`,c.fontFamily||`sans-serif`),n.setAttribute(`font-size`,c.fontSize||`14px`),(c.fontWeight===`bold`||parseInt(c.fontWeight)>=600)&&n.setAttribute(`font-weight`,`bold`),e.parentNode.replaceChild(n,e)});let r=e.getAttribute(`viewBox`),i,a;if(r){let e=r.split(/\s+/);i=Math.ceil(parseFloat(e[2])),a=Math.ceil(parseFloat(e[3]))}else{let t=e.getBoundingClientRect();i=Math.ceil(t.width||e.getAttribute(`width`)||300),a=Math.ceil(t.height||e.getAttribute(`height`)||200)}let o=new XMLSerializer().serializeToString(n),s=new Blob([o],{type:`image/svg+xml;charset=utf-8`}),c=URL.createObjectURL(s),l=await new Promise((e,n)=>{let r=new Image;r.onload=()=>e(r),r.onerror=()=>n(Error(t(`chatExport.svgLoadFailed`))),r.src=c}),u=document.createElement(`canvas`);u.width=i*2,u.height=a*2;let d=u.getContext(`2d`,{willReadFrequently:!0});d.scale(2,2),d.fillStyle=`#ffffff`,d.fillRect(0,0,u.width,u.height),d.drawImage(l,0,0,i,a);let{dataUrl:f,format:p}=j(u);URL.revokeObjectURL(c);let m=document.createElement(`img`);m.src=f,m.style.cssText=`max-width:100%;width:${i}px;height:auto;`,e.parentNode.replaceChild(m,e)}catch(e){n.warn(`[SidePanel] SVG rotationimage failed:`,e.name,e.message)}}function I(e,t,n){if(!e)return;let r=e.dataset.exportBtnKey||Date.now().toString();e.dataset.exportBtnKey=r;let i=e.querySelector(`svg`),a=i?i.outerHTML:``;x.set(r,{originalSvgHTML:a,timer:null,dropdown:n||null}),i&&(i.outerHTML=`
|
|
6
|
-
<svg viewBox="0 0 24 24" fill="none" style="animation: spin 0.8s linear infinite; width: 18px; height: 18px; flex-shrink: 0;">
|
|
7
|
-
<circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10" opacity="0.25"/>
|
|
8
|
-
<circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10"/>
|
|
9
|
-
</svg>
|
|
10
|
-
`),e.disabled=!0,e.style.opacity=`0.6`,e.style.transition=`all 0.3s ease`}function L(e,t){if(!e)return;let n=e.dataset.exportBtnKey,r=n?x.get(n):null,i=r&&r.dropdown;i&&i.classList.remove(`show`),r&&r.timer&&clearTimeout(r.timer);let a=e.querySelector(`svg`);a&&r&&r.originalSvgHTML&&(a.outerHTML=r.originalSvgHTML),e.disabled=!1,e.style.opacity=`1`,e.style.transition=`all 0.3s ease`,n&&x.delete(n)}function R(e){if(!e)return;let t=e.dataset.exportBtnKey,n=t?x.get(t):null,r=n&&n.dropdown;r&&r.classList.remove(`show`),n&&n.timer&&clearTimeout(n.timer);let i=e.querySelector(`svg`);i&&n&&n.originalSvgHTML&&(i.outerHTML=n.originalSvgHTML),e.disabled=!1,e.style.opacity=`1`,e.style.transition=`all 0.3s ease`,t&&x.delete(t)}async function z(e){if(typeof mermaid>`u`||!/```mermaid/i.test(e))return e;try{let t=s(e),n=document.createElement(`div`);n.style.cssText=`position:fixed;left:-9999px;top:-9999px;`,n.innerHTML=t,document.body.appendChild(n),await M(n),await F(n);let r=n.querySelectorAll(`.mermaid`),i=[];for(let e of r){let t=e.querySelector(`img`);t&&t.src&&t.src.startsWith(`data:`)?i.push(t.src):i.push(null)}if(document.body.removeChild(n),i.length===0)return e;let a=0;return e.replace(/```\s*mermaid\s*[\r\n]+([\s\S]*?)```/gi,e=>{let t=i[a];return a++,t?``:e})}catch(t){return n.warn(`[ChatExport] Mermaid pre-render failed,will keep ascodeblock:`,t.message),e}}async function B(e,i,a){let o=i.dataset.exportBtnKey;o&&x.has(o)||(I(i,`docx`,a),requestAnimationFrame(()=>{requestAnimationFrame(async()=>{try{let t=e.dataset.rawMarkdown||e.dataset.rawContent||``;if(!t){let n=e.querySelector(`.markdown-body`);t=n?n.innerText:e.innerText}t=await z(t);let r=await D(t),a=new l({styles:{default:{document:{run:{font:`Calibri`,size:22}},heading1:{run:{size:40,bold:!0,color:`333333`},paragraph:{spacing:{before:320,after:160}}},heading2:{run:{size:30,bold:!0,color:`333333`},paragraph:{spacing:{before:280,after:120}}},heading3:{run:{size:26,bold:!0,color:`333333`},paragraph:{spacing:{before:240,after:100}}}}},sections:[{properties:{page:{margin:{top:b(1),right:b(1),bottom:b(1),left:b(1)}}},children:r}]}),o=await p.toBlob(a),s=URL.createObjectURL(o),c=document.createElement(`a`);c.href=s,c.download=`word-${new Date().getTime()}.docx`,document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(s),L(i,`docx`),n.debug(`[SidePanel] Word (docx) document export successful`)}catch(e){n.error(`[SidePanel] export Word failed:`,e),r(t(`chatExport.exportFailed`,{message:e.message}),`error`),R(i)}})}))}function V(e,i,o){let c=i.dataset.exportBtnKey;c&&x.has(c)||(I(i,`pdf`,o),requestAnimationFrame(()=>{requestAnimationFrame(async()=>{try{let{jsPDF:o,html2canvas:c}=await a();if(!o||!c){r(t(`chatExport.pdfLibNotLoaded`),`error`),R(i);return}let l=e.dataset.rawMarkdown||e.dataset.rawContent||``;if(!l){let t=e.querySelector(`.markdown-body`);l=t?t.innerText:e.innerText}let u=`pdf-${new Date().getTime()}.pdf`,d=document.createElement(`div`);d.style.cssText=`
|
|
11
|
-
position: fixed;
|
|
12
|
-
left: -9999px;
|
|
13
|
-
top: -9999px;
|
|
14
|
-
width: 515px;
|
|
15
|
-
padding: 40px;
|
|
16
|
-
background: white;
|
|
17
|
-
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
|
|
18
|
-
font-size: 12px;
|
|
19
|
-
line-height: 1.6;
|
|
20
|
-
color: #333;
|
|
21
|
-
box-sizing: border-box;
|
|
22
|
-
`;let f=document.createElement(`div`);f.className=`markdown-body`,f.innerHTML=s(l),d.appendChild(f),document.body.appendChild(d),await M(d),await F(d);let p=d.scrollHeight,m=Math.ceil(p/762);c(d,{scale:2,useCORS:!0,logging:!1,backgroundColor:`#ffffff`,willReadFrequently:!0}).then(e=>{let t=new o({orientation:`portrait`,unit:`px`,format:[595,842],compress:!0}),r=e.width,a=e.height,s=a/p,c=762*s;for(let n=0;n<m;n++){n>0&&t.addPage();let i=n*c,o=Math.min(i+c,a)-i,l=document.createElement(`canvas`);l.width=r,l.height=o;let u=l.getContext(`2d`,{willReadFrequently:!0});u.fillStyle=`#ffffff`,u.fillRect(0,0,l.width,l.height),u.drawImage(e,0,i,r,o,0,0,r,o);let{dataUrl:d,format:f}=j(l),p=o/s;t.addImage(d,f,0,0,595,p,void 0,`FAST`)}t.save(u),L(i,`pdf`),document.body.removeChild(d),n.debug(`[SidePanel] PDF export successful:`,u)}).catch(e=>{n.error(`[SidePanel] PDF export failed:`,e),r(t(`chatExport.exportFailed`,{message:e.message}),`error`),document.body.removeChild(d),R(i)})}catch(e){n.error(`[SidePanel] export PDF failed:`,e),r(t(`chatExport.exportFailed`,{message:e.message}),`error`),R(i)}})}))}function H(e,i,a){let o=i.dataset.exportBtnKey;o&&x.has(o)||(I(i,`md`,a),requestAnimationFrame(()=>{requestAnimationFrame(()=>{try{let a=e.dataset.rawMarkdown||e.dataset.rawContent||``;if(!a){let t=e.querySelector(`.assistant-message-content, .message-content`);t&&(a=t.innerText||t.textContent||``)}if(!a.trim()){r(t(`chatExport.noContent`),`error`),R(i);return}a=a.replace(/\r\n/g,`
|
|
23
|
-
`).replace(/\n{3,}/g,`
|
|
24
|
-
|
|
25
|
-
`);let o=`md-${new Date().getTime()}.md`,s=new Blob([a],{type:`text/markdown;charset=utf-8`}),c=URL.createObjectURL(s),l=document.createElement(`a`);l.href=c,l.download=o,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(c),L(i,`md`),n.debug(`[SidePanel] Markdown export successful:`,o)}catch(e){n.error(`[SidePanel] export Markdown failed:`,e),r(t(`chatExport.exportFailed`,{message:e.message}),`error`),R(i)}})}))}function U(e,i,a){let c=i.dataset.exportBtnKey;c&&x.has(c)||(I(i,`image`,a),requestAnimationFrame(()=>{requestAnimationFrame(async()=>{let a=null;try{let c=await o();if(!c){r(t(`chatExport.imageLibNotLoaded`),`error`),R(i);return}let l=e.dataset.rawMarkdown||e.dataset.rawContent||``;if(!l){let t=e.querySelector(`.markdown-body`);l=t?t.innerText:e.innerText}let u=`image-${new Date().getTime()}.jpg`,d=Math.ceil(e.getBoundingClientRect().width),f=Math.max(595,d);a=document.createElement(`div`),a.style.cssText=`
|
|
26
|
-
position: fixed;
|
|
27
|
-
left: -9999px;
|
|
28
|
-
top: -9999px;
|
|
29
|
-
width: ${f}px;
|
|
30
|
-
padding: 40px;
|
|
31
|
-
background: white;
|
|
32
|
-
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
|
|
33
|
-
font-size: 14px;
|
|
34
|
-
line-height: 1.6;
|
|
35
|
-
color: #333;
|
|
36
|
-
box-sizing: border-box;
|
|
37
|
-
`;let p=document.createElement(`div`);p.className=`markdown-body`,p.innerHTML=s(l),a.appendChild(p),document.body.appendChild(a),await M(a),await F(a),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(e)));let m=(await c(a,{scale:2,useCORS:!0,logging:!1,backgroundColor:`#ffffff`,willReadFrequently:!0})).toDataURL(`image/jpeg`,.92),h=document.createElement(`a`);h.href=m,h.download=u,document.body.appendChild(h),h.click(),document.body.removeChild(h),L(i,`image`),document.body.removeChild(a),a=null,n.debug(`[SidePanel] image export successful:`,u)}catch(e){n.error(`[SidePanel] export image failed:`,e),r(t(`chatExport.exportFailed`,{message:e.message}),`error`),a&&a.parentNode&&document.body.removeChild(a),R(i)}})}))}export{F as convertSvgsToImages,w as createTextRuns,B as exportAssistantMessageToDocx,U as exportAssistantMessageToImage,H as exportAssistantMessageToMarkdown,V as exportAssistantMessageToPdf,T as parseInlineMarkdown,D as parseMarkdownToDocxChildren,M as renderMermaidInContainer,R as resetExportButton,I as setExportButtonLoading,L as setExportButtonSuccess};
|