zcode-pro 1.10.0 → 1.12.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.
@@ -0,0 +1,781 @@
1
+ // 划词翻译的后端库:zcode-translate.json 配置读写、LLM 通道调用(anthropic/openai
2
+ // 双格式,支持思考档位与流式)、单词词典卡片的提示词与解析、机翻通道适配。
3
+ // LLM 请求体构造与 helper.mjs 的智能起名、zcode-plugins 的 vision-lib.mjs 各有
4
+ // 一份复刻(仓库惯例:发布产物不跨仓库 import),改请求体结构时三处同改。
5
+
6
+ import { readFileSync, renameSync, writeFileSync } from 'node:fs';
7
+ import { createHash, createHmac } from 'node:crypto';
8
+ import { homedir } from 'node:os';
9
+ import { dirname, join } from 'node:path';
10
+
11
+ // 划词翻译的配置文件(与设置页“翻译”标签、翻译面板共用)
12
+ export function defaultTranslateFile() {
13
+ return join(homedir(), '.zcode', 'zcode-translate.json');
14
+ }
15
+
16
+ function historyFileOf(translateFile) {
17
+ return join(dirname(translateFile), 'zcode-translate-history.json');
18
+ }
19
+
20
+ function readJsonFile(p) {
21
+ try {
22
+ // Windows 记事本/PowerShell 保存的 JSON 带 UTF-8 BOM,JSON.parse 不认:先剥掉
23
+ const text = readFileSync(p, 'utf-8');
24
+ return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
25
+ } catch { return null; }
26
+ }
27
+
28
+ // ———— 配置:默认值、读取归一、校验、合并写 ————
29
+
30
+ // 思考档位:各模型支持的档位不同(GLM 是 low/high/max,MiMo 只有 off/enabled,
31
+ // Meta 有 6 档)。这里只做通用校验,具体可选值来自供应商表里每个模型的
32
+ // modelReasoning.variants;'off' 统一表示关闭
33
+ export const THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'enabled'];
34
+ export const isValidThinking = (v) => typeof v === 'string' && /^[a-z]{2,10}$/.test(v);
35
+ export const TRIGGER_MODES = ['ctrl-drag', 'ctrl-tap', 'alt-drag'];
36
+ export const PANEL_THEMES = ['follow', 'light', 'dark'];
37
+
38
+ // 机翻通道注册表:新增一家只需在 MT_ADAPTERS(见下)加适配函数并在此登记凭据字段
39
+ export const MT_SERVICES = [
40
+ { id: 'youdao', creds: ['appKey', 'key'] },
41
+ { id: 'baidu', creds: ['appId', 'secret'] },
42
+ { id: 'caiyun', creds: ['token'] },
43
+ { id: 'deepl', creds: ['authKey'] },
44
+ { id: 'deeplx', creds: ['apiUrl'] },
45
+ { id: 'niu', creds: ['apiKey'] },
46
+ { id: 'tencent', creds: ['secretId', 'secretKey'] },
47
+ { id: 'aliyun', creds: ['accessKeyId', 'accessKeySecret'] },
48
+ { id: 'volc', creds: ['accessKeyId', 'secretAccessKey'] },
49
+ ];
50
+
51
+ export const DEFAULT_TRANSLATE_PROMPTS = [
52
+ { id: 'quick', name: '快译', prompt: '你是翻译引擎。把用户消息翻译成{target},只输出译文:不解释、不加注、保留原文的换行与段落结构。' },
53
+ { id: 'refined', name: '精翻', prompt: '你是资深译者。把用户消息翻译成{target}:先吃透原意,再用符合{target}表达习惯的文字重写,做到信达雅,正确使用{target}标点,保留原文的语气与正式程度;只输出最终译文。' },
54
+ { id: 'tech', name: '技术文档', prompt: '你是技术文档译者。把用户消息翻译成{target}:代码、命令、路径、API 名、产品名保留原文不译;专有名词首次出现时在译文后括注原文;同一术语全文统一;只输出译文。' },
55
+ ];
56
+
57
+ export const TARGET_LANG_NAMES = {
58
+ zh: '简体中文', en: 'English', ja: '日本語', ko: '한국어',
59
+ fr: 'Français', de: 'Deutsch', ru: 'Русский', es: 'Español', pt: 'Português',
60
+ };
61
+
62
+ function defaultTranslateConfig() {
63
+ return {
64
+ enabled: true,
65
+ trigger: { mode: 'ctrl-drag' },
66
+ channel: { type: 'llm', provider: 'session', model: '', thinking: 'off', service: 'deepl' },
67
+ promptId: 'quick',
68
+ prompts: DEFAULT_TRANSLATE_PROMPTS.map((p) => ({ ...p })),
69
+ targetLang: 'zh',
70
+ // height: 用户拖拽设置的像素高度,0 表示未设置(按 maxHeightPct 自适应内容)
71
+ panel: { width: 450, maxHeightPct: 80, height: 0, theme: 'follow' },
72
+ history: { enabled: true, limit: 100 },
73
+ mt: { services: {} },
74
+ };
75
+ }
76
+
77
+ function clampInt(v, fallback, min, max) {
78
+ const n = Math.floor(Number(v));
79
+ if (!Number.isFinite(n)) return fallback;
80
+ return Math.min(max, Math.max(min, n));
81
+ }
82
+
83
+ // 读取并按默认归一:磁盘上缺的键补默认值,非法值回退,多出的未知键原样保留
84
+ export function readTranslateConfig(file) {
85
+ const cur = readJsonFile(file);
86
+ const def = defaultTranslateConfig();
87
+ const doc = cur && typeof cur === 'object' && !Array.isArray(cur) ? cur : {};
88
+ const out = { ...def, ...doc };
89
+ out.enabled = doc.enabled !== false;
90
+ out.trigger = { ...def.trigger, ...(doc.trigger && typeof doc.trigger === 'object' ? doc.trigger : {}) };
91
+ if (!TRIGGER_MODES.includes(out.trigger.mode)) out.trigger.mode = 'ctrl-drag';
92
+ out.channel = { ...def.channel, ...(doc.channel && typeof doc.channel === 'object' ? doc.channel : {}) };
93
+ if (out.channel.type !== 'mt') out.channel.type = 'llm';
94
+ if (!isValidThinking(out.channel.thinking)) out.channel.thinking = 'off';
95
+ if (typeof out.promptId !== 'string' || !out.promptId) out.promptId = 'quick';
96
+ if (!Array.isArray(out.prompts) || !out.prompts.length) out.prompts = def.prompts;
97
+ out.prompts = out.prompts
98
+ .filter((p) => p && typeof p === 'object' && typeof p.id === 'string' && typeof p.prompt === 'string')
99
+ .slice(0, 20)
100
+ .map((p) => ({ id: p.id.slice(0, 40), name: String(p.name || p.id).slice(0, 30), prompt: p.prompt.slice(0, 4000) }));
101
+ if (!out.prompts.length) out.prompts = def.prompts;
102
+ if (typeof out.targetLang !== 'string' || !/^[a-z]{2,8}$/.test(out.targetLang)) out.targetLang = 'zh';
103
+ out.panel = { ...def.panel, ...(doc.panel && typeof doc.panel === 'object' ? doc.panel : {}) };
104
+ out.panel.width = clampInt(out.panel.width, 450, 240, 1200);
105
+ out.panel.maxHeightPct = clampInt(out.panel.maxHeightPct, 80, 40, 95);
106
+ out.panel.height = clampInt(out.panel.height, 0, 0, 2000);
107
+ if (!PANEL_THEMES.includes(out.panel.theme)) out.panel.theme = 'follow';
108
+ out.history = { ...def.history, ...(doc.history && typeof doc.history === 'object' ? doc.history : {}) };
109
+ out.history.enabled = out.history.enabled !== false;
110
+ out.history.limit = clampInt(out.history.limit, 100, 10, 1000);
111
+ const mt = doc.mt && typeof doc.mt === 'object' && doc.mt.services && typeof doc.mt.services === 'object' ? doc.mt.services : {};
112
+ const services = {};
113
+ for (const s of MT_SERVICES) {
114
+ const src = mt[s.id] && typeof mt[s.id] === 'object' ? mt[s.id] : {};
115
+ const dst = {};
116
+ for (const k of s.creds) if (typeof src[k] === 'string') dst[k] = src[k].slice(0, 300);
117
+ if (s.id === 'deeplx' && typeof src.token === 'string') dst.token = src.token.slice(0, 300); // DeepLX 的 token 可选(Bearer 或 {{apiKey}} 占位)
118
+ services[s.id] = dst;
119
+ }
120
+ out.mt = { services };
121
+ return out;
122
+ }
123
+
124
+ // 校验前端提交的配置(返回 [cfg, err],cfg 只含认识且合法的键)
125
+ export function validateTranslateConfig(raw) {
126
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [null, 'config 需为对象'];
127
+ const def = defaultTranslateConfig();
128
+ const out = {};
129
+ if (raw.enabled !== undefined) {
130
+ if (typeof raw.enabled !== 'boolean') return [null, 'enabled 需为布尔值'];
131
+ out.enabled = raw.enabled;
132
+ }
133
+ if (raw.trigger && typeof raw.trigger === 'object') {
134
+ if (raw.trigger.mode !== undefined) {
135
+ if (!TRIGGER_MODES.includes(raw.trigger.mode)) return [null, 'trigger.mode 取值不合法'];
136
+ out.trigger = { mode: raw.trigger.mode };
137
+ }
138
+ }
139
+ if (raw.channel && typeof raw.channel === 'object') {
140
+ const c = raw.channel;
141
+ const dst = {};
142
+ if (c.type !== undefined) {
143
+ if (c.type !== 'llm' && c.type !== 'mt') return [null, 'channel.type 只能是 llm 或 mt'];
144
+ dst.type = c.type;
145
+ }
146
+ for (const k of ['provider', 'model', 'service']) {
147
+ if (typeof c[k] === 'string') dst[k] = c[k].slice(0, 200);
148
+ }
149
+ if (c.thinking !== undefined) {
150
+ if (!isValidThinking(c.thinking)) return [null, 'channel.thinking 取值不合法'];
151
+ dst.thinking = c.thinking;
152
+ }
153
+ if (Object.keys(dst).length) out.channel = dst;
154
+ }
155
+ if (typeof raw.promptId === 'string' && raw.promptId) out.promptId = raw.promptId.slice(0, 40);
156
+ if (raw.prompts !== undefined) {
157
+ if (!Array.isArray(raw.prompts)) return [null, 'prompts 需为数组'];
158
+ const list = [];
159
+ for (const p of raw.prompts.slice(0, 20)) {
160
+ if (!p || typeof p !== 'object' || typeof p.id !== 'string' || !p.id || typeof p.prompt !== 'string') {
161
+ return [null, 'prompts 条目需含 id 与 prompt 字符串'];
162
+ }
163
+ list.push({ id: p.id.slice(0, 40), name: String(p.name || p.id).slice(0, 30), prompt: p.prompt.slice(0, 4000) });
164
+ }
165
+ if (!list.length) return [null, 'prompts 不能为空'];
166
+ out.prompts = list;
167
+ }
168
+ if (raw.targetLang !== undefined) {
169
+ if (typeof raw.targetLang !== 'string' || !/^[a-z]{2,8}$/.test(raw.targetLang)) return [null, 'targetLang 取值不合法'];
170
+ out.targetLang = raw.targetLang;
171
+ }
172
+ if (raw.panel && typeof raw.panel === 'object') {
173
+ const dst = {};
174
+ if (raw.panel.width !== undefined) dst.width = clampInt(raw.panel.width, 450, 240, 1200);
175
+ if (raw.panel.maxHeightPct !== undefined) dst.maxHeightPct = clampInt(raw.panel.maxHeightPct, 80, 40, 95);
176
+ if (raw.panel.height !== undefined) dst.height = clampInt(raw.panel.height, 0, 0, 2000);
177
+ if (raw.panel.theme !== undefined) {
178
+ if (!PANEL_THEMES.includes(raw.panel.theme)) return [null, 'panel.theme 取值不合法'];
179
+ dst.theme = raw.panel.theme;
180
+ }
181
+ if (Object.keys(dst).length) out.panel = dst;
182
+ }
183
+ if (raw.history && typeof raw.history === 'object') {
184
+ const dst = {};
185
+ if (raw.history.enabled !== undefined) {
186
+ if (typeof raw.history.enabled !== 'boolean') return [null, 'history.enabled 需为布尔值'];
187
+ dst.enabled = raw.history.enabled;
188
+ }
189
+ if (raw.history.limit !== undefined) dst.limit = clampInt(raw.history.limit, 100, 10, 1000);
190
+ if (Object.keys(dst).length) out.history = dst;
191
+ }
192
+ if (raw.mt && typeof raw.mt === 'object' && raw.mt.services && typeof raw.mt.services === 'object') {
193
+ const known = new Set(MT_SERVICES.map((s) => s.id));
194
+ const dst = {};
195
+ for (const [id, val] of Object.entries(raw.mt.services)) {
196
+ if (!known.has(id)) return [null, `未知机翻服务 ${id}`];
197
+ if (!val || typeof val !== 'object') return [null, `mt.services.${id} 需为对象`];
198
+ const fields = MT_SERVICES.find((s) => s.id === id).creds;
199
+ const sv = {};
200
+ for (const k of fields) if (typeof val[k] === 'string') sv[k] = val[k].slice(0, 300);
201
+ if (id === 'deeplx' && typeof val.token === 'string') sv.token = val.token.slice(0, 300); // DeepLX 的 token 可选
202
+ dst[id] = sv;
203
+ }
204
+ out.mt = { services: dst };
205
+ }
206
+ return [out, ''];
207
+ }
208
+
209
+ // 合并写:只覆盖提交的键,磁盘上其余键保留;临时文件 + rename 防多写者撕裂,
210
+ // mode 0600(文件里有机翻密钥)。与 /vision、headroom 的写法同款。
211
+ export function writeTranslateConfig(file, cfg) {
212
+ const cur = readJsonFile(file);
213
+ const base = cur && typeof cur === 'object' && !Array.isArray(cur) ? cur : {};
214
+ const merged = { ...base, ...cfg };
215
+ const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
216
+ writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
217
+ renameSync(tmp, file);
218
+ }
219
+
220
+ // 机翻通道的下拉状态:各家是否已配置凭据(不回密钥本身)
221
+ export function translateServicesStatus(file) {
222
+ const cfg = readTranslateConfig(file);
223
+ return MT_SERVICES.map((s) => ({
224
+ id: s.id,
225
+ configured: s.creds.every((k) => String(cfg.mt.services[s.id]?.[k] || '').trim() !== ''),
226
+ }));
227
+ }
228
+
229
+ // ———— 文本判定与提示词 ————
230
+
231
+ export const TRANSLATE_MAX_TEXT = 8000; // 送入通道的文本长度上限(按字符计)
232
+
233
+ // 单词判定:纯英文字母(允许连字符/撇号),无空白 —— 只有这种才出词典卡片
234
+ export function isWordText(text) {
235
+ return /^[A-Za-z][A-Za-z'-]{0,39}$/.test(text);
236
+ }
237
+
238
+ // 中文为主的文本在目标为中文时把目标转成英文(翻译才有意义)
239
+ export function targetLangFor(text, targetLang) {
240
+ const cjk = (text.match(/[\u4e00-\u9fff\u3400-\u4dbf]/g) || []).length;
241
+ const letters = (text.match(/[A-Za-z]/g) || []).length;
242
+ if (targetLang === 'zh' && cjk > letters) return 'en';
243
+ return targetLang;
244
+ }
245
+
246
+ export function targetLangName(lang) {
247
+ return TARGET_LANG_NAMES[lang] || lang;
248
+ }
249
+
250
+ // 从字符集猜源语言:LLM 通道的译文区用(机翻优先用接口返回的检测语言,
251
+ // 没有时也退回这里)。只认字符集能区分的常见语种,猜不出返回空串不硬凑
252
+ export function guessSourceLang(text) {
253
+ const s = String(text || '');
254
+ const cjk = (s.match(/[\u4e00-\u9fff\u3400-\u4dbf]/g) || []).length;
255
+ const kana = (s.match(/[\u3040-\u30ff]/g) || []).length;
256
+ const hangul = (s.match(/[\uac00-\ud7af]/g) || []).length;
257
+ const cyr = (s.match(/[\u0400-\u04ff]/g) || []).length;
258
+ const latin = (s.match(/[A-Za-z]/g) || []).length;
259
+ const total = cjk + kana + hangul + cyr + latin;
260
+ if (!total) return '';
261
+ if (kana > 0 && kana >= cjk * 0.2) return 'ja'; // 假名是日文的强信号
262
+ if (hangul > total * 0.3) return 'ko';
263
+ if (cjk > total * 0.5) return 'zh';
264
+ if (cyr > total * 0.5) return 'ru';
265
+ if (latin > total * 0.5) return 'en';
266
+ return '';
267
+ }
268
+
269
+ // 渲染提示词里的 {target} 占位
270
+ export function renderTranslatePrompt(prompt, targetLang) {
271
+ return String(prompt || '').replaceAll('{target}', targetLangName(targetLang));
272
+ }
273
+
274
+ const WORD_CARD_PROMPT = '你是词典引擎。把用户消息里的英文单词整理成词典卡片,只输出一个 JSON 对象(不要 markdown 围栏、不要任何解释),结构:{"phonetic":{"uk":"","us":""},"senses":[{"pos":"词性","defs":["中文释义"]}],"examples":[{"src":"英文例句","dst":"例句的中文翻译"}],"forms":["词形变化"]}\n规则:释义与例句翻译用简体中文;例句最多 2 条;没有的信息用空串或空数组;除 JSON 外不输出任何内容。';
275
+
276
+ // 解析模型的词典卡片输出:剥思考块与代码围栏后取首个 { 到末个 } 的 JSON,字段宽松归一
277
+ export function parseWordCard(text, word) {
278
+ let t = String(text || '').replace(/<think>[\s\S]*?<\/think>/gi, '').trim();
279
+ t = t.replace(/^```[a-zA-Z]*\s*\n?/, '').replace(/\n?```\s*$/, '').trim();
280
+ const start = t.indexOf('{');
281
+ const end = t.lastIndexOf('}');
282
+ let doc = null;
283
+ if (start >= 0 && end > start) {
284
+ try { doc = JSON.parse(t.slice(start, end + 1)); } catch { doc = null; }
285
+ }
286
+ const str = (v) => (typeof v === 'string' ? v.trim() : '');
287
+ const card = {
288
+ word: word || '',
289
+ phonetic: { uk: str(doc?.phonetic?.uk), us: str(doc?.phonetic?.us) },
290
+ senses: [],
291
+ examples: [],
292
+ forms: [],
293
+ tts: '',
294
+ };
295
+ if (Array.isArray(doc?.senses)) {
296
+ for (const s of doc.senses.slice(0, 8)) {
297
+ const defs = Array.isArray(s?.defs) ? s.defs.filter((d) => typeof d === 'string' && d.trim()).slice(0, 8) : [];
298
+ if (defs.length) card.senses.push({ pos: str(s?.pos), defs });
299
+ }
300
+ }
301
+ if (Array.isArray(doc?.examples)) {
302
+ for (const e of doc.examples.slice(0, 3)) {
303
+ if (e && typeof e === 'object' && str(e.src)) card.examples.push({ src: str(e.src), dst: str(e.dst) });
304
+ }
305
+ }
306
+ if (Array.isArray(doc?.forms)) card.forms = doc.forms.filter((f) => typeof f === 'string' && f.trim()).slice(0, 8);
307
+ if (card.word) card.tts = `https://dict.youdao.com/dictvoice?audio=${encodeURIComponent(card.word)}&type=2`;
308
+ return card;
309
+ }
310
+
311
+ // ———— LLM 通道调用(anthropic / openai 双格式) ————
312
+ // 与 helper.mjs 的 callAnthropicText/callOpenAiText、vision-lib.mjs 的 callProxy
313
+ // 各有一份复刻;这里多了 system 消息、思考档位与流式。
314
+
315
+ const TRANSLATE_TIMEOUT_MS = 60000;
316
+
317
+ function anthropicUrl(baseUrl) { return baseUrl.replace(/\/+$/, '') + '/v1/messages'; }
318
+ function openaiUrl(baseUrl) {
319
+ const base = baseUrl.replace(/\/+$/, '');
320
+ return /\/v\d+$/.test(base) ? base + '/chat/completions' : base + '/v1/chat/completions';
321
+ }
322
+
323
+ // 思考档位写进请求体。档位值由调用方按所选模型的实际档位给出(模型不支持
324
+ // 思考时不会走到这里)。映射:
325
+ // - anthropic 协议:换算成思考预算(max_tokens 必须大于预算)
326
+ // - 智谱 openai 兼容端点:只认思考开/关,任何非 off 档位都发 enabled
327
+ // - 其他 openai 兼容端点:原样发 reasoning_effort(low/high/max 等由厂商定义)
328
+ export function applyThinking(body, format, baseUrl, level) {
329
+ const isBigmodel = /bigmodel\.cn/.test(baseUrl);
330
+ const off = !level || level === 'off';
331
+ if (off) {
332
+ // 智谱 GLM-4.5+ 默认开思考,显式关闭时必须发 disabled
333
+ if (format === 'openai' && isBigmodel) body.thinking = { type: 'disabled' };
334
+ if (format === 'anthropic' && isBigmodel) body.thinking = { type: 'disabled' };
335
+ return;
336
+ }
337
+ if (format === 'anthropic') {
338
+ const budget = THINKING_BUDGET[level] || 8192;
339
+ body.thinking = { type: 'enabled', budget_tokens: budget };
340
+ body.max_tokens = Math.max(body.max_tokens || 0, budget + 8192);
341
+ } else if (isBigmodel) {
342
+ body.thinking = { type: 'enabled' };
343
+ } else {
344
+ body.reasoning_effort = level;
345
+ }
346
+ }
347
+
348
+ // 档位名 → anthropic 思考预算(未列出的档位给中等值)
349
+ const THINKING_BUDGET = { minimal: 1024, low: 2048, medium: 6144, high: 12288, xhigh: 16384, max: 24576, enabled: 8192 };
350
+
351
+ function stripThinking(body) {
352
+ delete body.thinking;
353
+ delete body.reasoning_effort;
354
+ }
355
+
356
+ function hadThinking(body) {
357
+ return body.thinking !== undefined || body.reasoning_effort !== undefined;
358
+ }
359
+
360
+ // messages 为 [{role:'system'|'user', content}];anthropic 的 system 走顶层参数。
361
+ // 返回模型输出的文本(思考块/思考字段已过滤);onDelta 存在时走流式并逐段回调。
362
+ async function callTranslateLlm(conn, messages, { maxTokens = 4096, thinking = 'off', onDelta = null, signal = null } = {}) {
363
+ const anthropic = (conn.format || 'openai') === 'anthropic';
364
+ const system = messages.filter((m) => m.role === 'system').map((m) => m.content).join('\n\n');
365
+ const chat = messages.filter((m) => m.role !== 'system');
366
+ const buildBody = () => {
367
+ const body = anthropic
368
+ ? { model: conn.model, max_tokens: maxTokens, messages: chat.map((m) => ({ role: m.role, content: m.content })) }
369
+ : { model: conn.model, max_tokens: maxTokens, messages: system ? [{ role: 'system', content: system }, ...chat] : chat };
370
+ if (anthropic && system) body.system = system;
371
+ applyThinking(body, conn.format, conn.baseUrl, thinking);
372
+ return body;
373
+ };
374
+ const url = anthropic ? anthropicUrl(conn.baseUrl) : openaiUrl(conn.baseUrl);
375
+ const headers = anthropic
376
+ ? { 'content-type': 'application/json', 'x-api-key': conn.apiKey, 'anthropic-version': '2023-06-01' }
377
+ : { 'content-type': 'application/json', authorization: `Bearer ${conn.apiKey}` };
378
+ if (onDelta) {
379
+ headers.accept = 'text/event-stream';
380
+ }
381
+
382
+ const ctrl = new AbortController();
383
+ const timer = setTimeout(() => ctrl.abort(), TRANSLATE_TIMEOUT_MS);
384
+ if (signal) signal.addEventListener('abort', () => ctrl.abort(), { once: true });
385
+ const doFetch = async (body) => {
386
+ let payload = { ...body };
387
+ if (onDelta) payload.stream = true;
388
+ return fetch(url, { method: 'POST', signal: ctrl.signal, headers, body: JSON.stringify(payload) });
389
+ };
390
+ try {
391
+ let body = buildBody();
392
+ let resp = await doFetch(body);
393
+ // 老端点不认思考参数会回 400:去掉思考键重试一次
394
+ if (resp.status === 400 && hadThinking(body)) {
395
+ body = { ...body };
396
+ stripThinking(body);
397
+ resp = await doFetch(body);
398
+ }
399
+ if (!resp.ok) {
400
+ const errText = (await resp.text()).slice(0, 300);
401
+ throw new Error(`HTTP ${resp.status} [model=${conn.model}]: ${errText}`);
402
+ }
403
+ if (!onDelta) {
404
+ const doc = JSON.parse(await resp.text());
405
+ const text = anthropic
406
+ ? (Array.isArray(doc.content) ? doc.content.filter((b) => b && b.type === 'text').map((b) => b.text || '').join('') : '')
407
+ : (doc.choices?.[0]?.message?.content || '');
408
+ if (!text) {
409
+ const e = new Error(anthropic && doc?.stop_reason === 'max_tokens'
410
+ ? '模型的思考用完了输出上限,仍未给出文本:请调低思考档位或换模型' : '响应中没有文本内容');
411
+ e.code = 'translate-empty';
412
+ throw e;
413
+ }
414
+ return text;
415
+ }
416
+ // 流式:逐行解析上游 SSE,把文本增量回调给调用方
417
+ const reader = resp.body.getReader();
418
+ const decoder = new TextDecoder();
419
+ let buf = '';
420
+ let full = '';
421
+ for (;;) {
422
+ const { done, value } = await reader.read();
423
+ if (done) break;
424
+ buf += decoder.decode(value, { stream: true });
425
+ let idx;
426
+ while ((idx = buf.indexOf('\n')) >= 0) {
427
+ const line = buf.slice(0, idx).replace(/\r$/, '');
428
+ buf = buf.slice(idx + 1);
429
+ if (!line.startsWith('data:')) continue;
430
+ const data = line.slice(5).trim();
431
+ if (!data || data === '[DONE]') continue;
432
+ let evt;
433
+ try { evt = JSON.parse(data); } catch { continue; }
434
+ let delta = '';
435
+ if (anthropic) {
436
+ if (evt.type === 'content_block_delta' && evt.delta?.type === 'text_delta') delta = evt.delta.text || '';
437
+ } else {
438
+ delta = evt.choices?.[0]?.delta?.content || '';
439
+ }
440
+ if (delta) { full += delta; onDelta(delta); }
441
+ }
442
+ }
443
+ if (!full.trim()) {
444
+ const e = new Error('流式响应中没有文本内容');
445
+ e.code = 'translate-empty';
446
+ throw e;
447
+ }
448
+ return full;
449
+ } catch (err) {
450
+ if (err && err.name === 'AbortError') {
451
+ const e = new Error(signal && signal.aborted ? '请求已取消' : `请求超时(${Math.round(TRANSLATE_TIMEOUT_MS / 1000)} 秒)`);
452
+ e.code = signal && signal.aborted ? 'translate-cancelled' : 'translate-timeout';
453
+ throw e;
454
+ }
455
+ throw err;
456
+ } finally { clearTimeout(timer); }
457
+ }
458
+
459
+ // 非流式翻译:单词出词典卡片,句子/段落出整段译文
460
+ export async function translateJson(conn, opts) {
461
+ if (opts.isWord) {
462
+ const raw = await callTranslateLlm(conn, [
463
+ { role: 'system', content: WORD_CARD_PROMPT },
464
+ { role: 'user', content: opts.text },
465
+ ], { maxTokens: 2000 });
466
+ return { kind: 'dict', dict: parseWordCard(raw, opts.text) };
467
+ }
468
+ const text = await callTranslateLlm(conn, [
469
+ { role: 'system', content: opts.prompt },
470
+ { role: 'user', content: opts.text },
471
+ ], { maxTokens: 8192, thinking: opts.thinking });
472
+ return { kind: 'trans', trans: { text, sourceLang: guessSourceLang(opts.text) } };
473
+ }
474
+
475
+ // 流式翻译(仅句子/段落):先发 meta,再逐段 delta,结束由调用方发 done
476
+ export async function streamTranslateText(conn, opts, send, signal) {
477
+ const sourceLang = guessSourceLang(opts.text);
478
+ send({ type: 'meta', kind: 'trans', sourceLang });
479
+ const text = await callTranslateLlm(conn, [
480
+ { role: 'system', content: opts.prompt },
481
+ { role: 'user', content: opts.text },
482
+ ], { maxTokens: 8192, thinking: opts.thinking, onDelta: (d) => send({ type: 'delta', text: d }), signal });
483
+ send({ type: 'done', text, sourceLang });
484
+ }
485
+
486
+ // ———— 机翻通道(适配器逐家实现,凭据来自 zcode-translate.json) ————
487
+
488
+ // ———— 机翻通道适配器 ————
489
+ // 请求与签名算法参考沙拉查词(crimx/ext-saladist,MIT 许可)的 @opentranslate
490
+ // 包与手写适配。适配器统一返回 { paragraphs: [译文段], detectedLang: '', tts: '', dict: null }。
491
+ // 语言内部码为 ISO(zh/en/ja/...),from 一律 auto(面板不做源语言选择)。
492
+
493
+ async function fetchJson(url, options = {}, timeoutMs = 30000) {
494
+ const ctrl = new AbortController();
495
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
496
+ try {
497
+ const resp = await fetch(url, { ...options, signal: ctrl.signal });
498
+ const body = await resp.text();
499
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${body.slice(0, 200)}`);
500
+ try { return JSON.parse(body); } catch { throw new Error('响应不是合法 JSON: ' + body.slice(0, 200)); }
501
+ } finally { clearTimeout(timer); }
502
+ }
503
+
504
+ function splitParagraphs(s) { return String(s).split(/\n+/).map((x) => x.trim()).filter(Boolean); }
505
+
506
+ function decodeEntities(s) {
507
+ return String(s)
508
+ .replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
509
+ .replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)))
510
+ .replace(/&quot;/g, '"').replace(/&amp;/g, '&').replace(/&lt;/g, '<')
511
+ .replace(/&gt;/g, '>').replace(/&#39;/g, "'").replace(/&nbsp;/g, ' ');
512
+ }
513
+
514
+ const YOUDAO_LANG = { zh: 'zh-CHS', en: 'en', ja: 'ja', ko: 'ko', fr: 'fr', ru: 'ru', pt: 'pt', es: 'es', it: 'it' };
515
+ const BAIDU_LANG = { zh: 'zh', en: 'en', ja: 'jp', ko: 'kor', fr: 'fra', es: 'spa', ru: 'ru', de: 'de', it: 'it', pt: 'pt', vi: 'vie', th: 'th', ar: 'ara' };
516
+ const TENCENT_LANG = { zh: 'zh', en: 'en', ja: 'jp', ko: 'kr', de: 'de', es: 'es', fr: 'fr', ru: 'ru', it: 'it', pt: 'pt', vi: 'vn', th: 'th', ms: 'ms', id: 'id' };
517
+ const NIU_LANG = { zh: 'zh', en: 'en', ja: 'ja', ko: 'ko', fr: 'fr', ru: 'ru', es: 'es', pt: 'pt', de: 'de', it: 'it' };
518
+
519
+ // 有道 signType=v3 签名:sha256(appKey + truncate(q) + salt + curtime + key)。导出以便测试
520
+ export function youdaoSign(appKey, key, text, salt, curtime) {
521
+ const input = text.length <= 20 ? text : text.slice(0, 10) + text.length + text.slice(-10);
522
+ return createHash('sha256').update(appKey + input + salt + curtime + key).digest('hex');
523
+ }
524
+
525
+ // 把有道 basic 词条数据(官方文档口径,字段做防御式兼容)整理成轻量词条卡
526
+ function youdaoBasicToDict(b, word) {
527
+ if (!b || typeof b !== 'object') return null;
528
+ const str = (v) => (typeof v === 'string' ? v.trim() : '');
529
+ const senseMap = new Map();
530
+ for (const line of (Array.isArray(b.explains) ? b.explains : [])) {
531
+ const s = String(line).trim();
532
+ if (!s) continue;
533
+ const m = /^([A-Za-z][A-Za-z.]*|\d+[.])\s+(.+)$/.exec(s);
534
+ const pos = m ? m[1] : '';
535
+ const def = m ? m[2] : s;
536
+ if (!senseMap.has(pos)) senseMap.set(pos, []);
537
+ senseMap.get(pos).push(def);
538
+ }
539
+ const forms = (Array.isArray(b.wfs) ? b.wfs : [])
540
+ .map((w) => w && w.wf ? `${String(w.wf.name || '').trim()} ${String(w.wf.value || '').trim()}`.trim() : '')
541
+ .filter(Boolean);
542
+ if (!senseMap.size && !str(b.uk_phonetic) && !str(b.us_phonetic) && !forms.length) return null;
543
+ return {
544
+ word,
545
+ phonetic: { uk: str(b.uk_phonetic), us: str(b.us_phonetic) },
546
+ senses: [...senseMap].map(([pos, defs]) => ({ pos, defs })),
547
+ examples: [],
548
+ forms,
549
+ tts: `https://dict.youdao.com/dictvoice?audio=${encodeURIComponent(word)}&type=2`,
550
+ };
551
+ }
552
+
553
+ async function mtYoudao(creds, { text, to }) {
554
+ const salt = String(Date.now());
555
+ const curtime = String(Math.round(Date.now() / 1000));
556
+ const doc = await fetchJson('https://openapi.youdao.com/api', {
557
+ method: 'POST',
558
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
559
+ body: new URLSearchParams({
560
+ q: text, appKey: creds.appKey, salt, from: 'auto', to: YOUDAO_LANG[to] || 'zh-CHS',
561
+ sign: youdaoSign(creds.appKey, creds.key, text, salt, curtime), signType: 'v3', curtime,
562
+ }).toString(),
563
+ });
564
+ if (doc.errorCode && doc.errorCode !== '0') throw new Error(`有道接口错误码 ${doc.errorCode}`);
565
+ const paragraphs = Array.isArray(doc.translation) ? doc.translation.filter(Boolean) : [];
566
+ if (!paragraphs.length) throw new Error('有道未返回译文');
567
+ return { paragraphs, detectedLang: '', tts: '', dict: youdaoBasicToDict(doc.basic, text) };
568
+ }
569
+
570
+ // 百度签名:md5(appId + 完整原文 + salt + secret)。导出以便测试
571
+ export function baiduSign(appId, secret, text, salt) {
572
+ return createHash('md5').update(appId + text + salt + secret).digest('hex');
573
+ }
574
+
575
+ async function mtBaidu(creds, { text, to }) {
576
+ const salt = String(Date.now());
577
+ const qs = new URLSearchParams({
578
+ q: text, from: 'auto', to: BAIDU_LANG[to] || 'zh',
579
+ appid: creds.appId, salt, sign: baiduSign(creds.appId, creds.secret, text, salt),
580
+ });
581
+ const doc = await fetchJson('https://api.fanyi.baidu.com/api/trans/vip/translate?' + qs.toString());
582
+ if (doc.error_code) throw new Error(`百度接口错误 ${doc.error_code}: ${doc.error_msg || ''}`);
583
+ const list = Array.isArray(doc.trans_result) ? doc.trans_result : [];
584
+ if (!list.length) throw new Error('百度未返回译文');
585
+ return { paragraphs: list.map((r) => String(r.dst || '')), detectedLang: doc.from && doc.from !== 'auto' ? doc.from : '', tts: '', dict: null };
586
+ }
587
+
588
+ async function mtCaiyun(creds, { text, to }) {
589
+ const tgt = { zh: 'zh', en: 'en', ja: 'ja' }[to];
590
+ if (!tgt) throw new Error('彩云小译只支持中文/英文/日文目标');
591
+ const doc = await fetchJson('https://api.interpreter.caiyunai.com/v1/translator', {
592
+ method: 'POST',
593
+ headers: { 'content-type': 'application/json', 'x-authorization': 'token ' + String(creds.token).trim() },
594
+ body: JSON.stringify({ source: text.split(/\n+/), trans_type: `auto2${tgt}`, detect: true }),
595
+ });
596
+ const paragraphs = Array.isArray(doc.target) ? doc.target.filter(Boolean) : [];
597
+ if (!paragraphs.length) throw new Error('彩云未返回译文');
598
+ return { paragraphs, detectedLang: '', tts: '', dict: null };
599
+ }
600
+
601
+ // 腾讯云 TC3-HMAC-SHA256 签名头(tmt 服务)。导出以便测试
602
+ export function tencentHeaders({ secretId, secretKey, timestamp, body }) {
603
+ const host = 'tmt.tencentcloudapi.com';
604
+ const hashedPayload = createHash('sha256').update(body).digest('hex');
605
+ const canonical = ['POST', '/', '', 'content-type:application/json; charset=utf-8',
606
+ `host:${host}`, '', 'content-type;host', hashedPayload].join('\n');
607
+ const datestamp = new Date(timestamp * 1000).toISOString().slice(0, 10);
608
+ const stringToSign = ['TC3-HMAC-SHA256', String(timestamp),
609
+ `${datestamp}/tmt/tc3_request`, createHash('sha256').update(canonical).digest('hex')].join('\n');
610
+ const hmac = (key, msg) => createHmac('sha256', key).update(msg).digest();
611
+ const kDate = hmac(Buffer.from('TC3' + secretKey, 'utf8'), datestamp);
612
+ const kService = hmac(kDate, 'tmt');
613
+ const kSigning = hmac(kService, 'tc3_request');
614
+ const signature = createHmac('sha256', kSigning).update(stringToSign).digest('hex');
615
+ return {
616
+ 'content-type': 'application/json; charset=utf-8', Host: host,
617
+ 'X-TC-Action': 'TextTranslate', 'X-TC-Timestamp': String(timestamp),
618
+ 'X-TC-Region': 'ap-beijing', 'X-TC-Version': '2018-03-21',
619
+ Authorization: `TC3-HMAC-SHA256 Credential=${secretId}/${datestamp}/tmt/tc3_request, SignedHeaders=content-type;host, Signature=${signature}`,
620
+ };
621
+ }
622
+
623
+ async function mtTencent(creds, { text, to }) {
624
+ const body = JSON.stringify({ ProjectId: 0, Source: 'auto', SourceText: text, Target: TENCENT_LANG[to] || 'en' });
625
+ const doc = await fetchJson('https://tmt.tencentcloudapi.com', {
626
+ method: 'POST', headers: tencentHeaders({ ...creds, timestamp: Math.floor(Date.now() / 1000), body }), body,
627
+ });
628
+ const r = doc.Response || {};
629
+ if (r.Error) throw new Error(`腾讯接口错误 ${r.Error.Code}: ${r.Error.Message}`);
630
+ if (!r.TargetText) throw new Error('腾讯未返回译文');
631
+ return { paragraphs: splitParagraphs(decodeEntities(r.TargetText)), detectedLang: r.Source || '', tts: '', dict: null };
632
+ }
633
+
634
+ async function mtDeepl(creds, { text, to }) {
635
+ const target = to === 'zh' ? 'ZH-HANS' : to.toUpperCase();
636
+ const base = /:fx$/.test(creds.authKey) ? 'https://api-free.deepl.com' : 'https://api.deepl.com';
637
+ const doc = await fetchJson(base + '/v2/translate', {
638
+ method: 'POST',
639
+ headers: { 'content-type': 'application/json', authorization: 'DeepL-Auth-Key ' + String(creds.authKey).trim() },
640
+ body: JSON.stringify({ text: [text], target_lang: target }),
641
+ });
642
+ const t = doc.translations && doc.translations[0];
643
+ if (!t || !t.text) throw new Error('DeepL 未返回译文');
644
+ return { paragraphs: splitParagraphs(t.text), detectedLang: t.detected_source_language || '', tts: '', dict: null };
645
+ }
646
+
647
+ async function mtDeeplx(creds, { text, to }) {
648
+ const target = to === 'zh' ? 'ZH-HANS' : to.toUpperCase();
649
+ let url = String(creds.apiUrl || '').trim();
650
+ if (creds.token) url = url.replaceAll('{{apiKey}}', encodeURIComponent(String(creds.token).trim()));
651
+ if (!/\/translate\/?$/.test(url)) url = url.replace(/\/+$/, '') + '/translate';
652
+ const useBearer = creds.token && !String(creds.apiUrl).includes('{{apiKey}}');
653
+ const doc = await fetchJson(url, {
654
+ method: 'POST',
655
+ headers: { 'content-type': 'application/json', ...(useBearer ? { authorization: 'Bearer ' + String(creds.token).trim() } : {}) },
656
+ body: JSON.stringify({ text, source_lang: 'auto', target_lang: target }),
657
+ });
658
+ const out = (typeof doc.data === 'string' ? doc.data : '')
659
+ || doc.translation || doc.translated || doc.translatedText
660
+ || (doc.translations && doc.translations[0] && doc.translations[0].text) || '';
661
+ if (!out) throw new Error('DeepLX 未返回译文');
662
+ const src = doc.source_lang || doc.sourceLanguage || doc.detected_source_language
663
+ || (doc.translations && doc.translations[0] && doc.translations[0].detected_source_language) || '';
664
+ return { paragraphs: splitParagraphs(out), detectedLang: src, tts: '', dict: null };
665
+ }
666
+
667
+ // 阿里云 RPC 签名:HMAC-SHA1(secret + "&", "GET&%2F&" + percent(canonicalQuery)) 的 base64。导出以便测试
668
+ export function aliyunSignature(params, accessKeySecret) {
669
+ const pe = (s) => encodeURIComponent(String(s)).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
670
+ const canonical = Object.keys(params).sort().map((k) => pe(k) + '=' + pe(params[k])).join('&');
671
+ const stringToSign = 'GET&%2F&' + pe(canonical);
672
+ return { canonical, signature: createHmac('sha1', accessKeySecret + '&').update(stringToSign).digest('base64'), pe };
673
+ }
674
+
675
+ async function mtAliyun(creds, { text, to }) {
676
+ const params = {
677
+ AccessKeyId: creds.accessKeyId, Action: 'TranslateGeneral', Format: 'JSON', FormatType: 'text',
678
+ Scene: 'general', SignatureMethod: 'HMAC-SHA1', SignatureNonce: Math.random().toString(36).slice(2),
679
+ SignatureVersion: '1.0', SourceLanguage: 'auto', SourceText: text,
680
+ TargetLanguage: to === 'zh' ? 'zh' : to,
681
+ Timestamp: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'), Version: '2018-10-12',
682
+ };
683
+ const { canonical, signature, pe } = aliyunSignature(params, creds.accessKeySecret);
684
+ const doc = await fetchJson('https://mt.aliyuncs.com/?' + canonical + '&Signature=' + pe(signature));
685
+ let data = doc.Data;
686
+ if (typeof data === 'string') { try { data = JSON.parse(data); } catch { data = null; } }
687
+ const out = (data && (data.Translated || data.translated || data.TranslatedText)) || '';
688
+ if (!out) throw new Error(doc.Message ? `阿里接口错误 ${doc.Code || ''}: ${doc.Message}` : '阿里未返回译文');
689
+ return { paragraphs: splitParagraphs(out), detectedLang: (data && data.DetectedLanguage) || '', tts: '', dict: null };
690
+ }
691
+
692
+ async function mtNiu(creds, { text, to }) {
693
+ const doc = await fetchJson('https://api.niutrans.com/NiuTransServer/translation', {
694
+ method: 'POST',
695
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
696
+ body: new URLSearchParams({ from: 'auto', to: NIU_LANG[to] || 'zh', apikey: creds.apiKey, src_text: text }).toString(),
697
+ });
698
+ if (doc.error_code) throw new Error(`小牛接口错误 ${doc.error_code}: ${doc.error_msg || ''}`);
699
+ const out = doc.tgt_text || doc.tgtText || doc.translation || doc.translated || '';
700
+ if (!out) throw new Error('小牛未返回译文');
701
+ return { paragraphs: splitParagraphs(out), detectedLang: doc.from || '', tts: '', dict: null };
702
+ }
703
+
704
+ // 火山引擎 V4 签名头(translate 服务,region cn-north-1)。导出以便测试
705
+ export function volcHeaders({ accessKeyId, secretAccessKey, xDate, body }) {
706
+ const host = 'translate.volcengineapi.com';
707
+ const payloadHash = createHash('sha256').update(body).digest('hex');
708
+ const canonicalHeaders = `content-type:application/json\nhost:${host}\nx-content-sha256:${payloadHash}\nx-date:${xDate}`;
709
+ const signedHeaders = 'content-type;host;x-content-sha256;x-date';
710
+ const canonicalRequest = ['POST', '/', 'Action=TranslateText&Version=2020-06-01',
711
+ canonicalHeaders + '\n', signedHeaders, payloadHash].join('\n');
712
+ const dateStamp = xDate.slice(0, 8);
713
+ const scope = `${dateStamp}/cn-north-1/translate/request`;
714
+ const stringToSign = ['HMAC-SHA256', xDate, scope, createHash('sha256').update(canonicalRequest).digest('hex')].join('\n');
715
+ const hmac = (key, msg) => createHmac('sha256', key).update(msg).digest();
716
+ let k = hmac(Buffer.from(secretAccessKey, 'utf8'), dateStamp);
717
+ k = hmac(k, 'cn-north-1'); k = hmac(k, 'translate'); k = hmac(k, 'request');
718
+ const signature = createHmac('sha256', k).update(stringToSign).digest('hex');
719
+ return {
720
+ 'content-type': 'application/json', 'X-Content-Sha256': payloadHash, 'X-Date': xDate,
721
+ Authorization: `HMAC-SHA256 Credential=${accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
722
+ };
723
+ }
724
+
725
+ async function mtVolc(creds, { text, to }) {
726
+ const body = JSON.stringify({ TargetLanguage: to === 'zh' ? 'zh' : to, TextList: [text] });
727
+ const xDate = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z');
728
+ const doc = await fetchJson('https://translate.volcengineapi.com/?Action=TranslateText&Version=2020-06-01', {
729
+ method: 'POST', headers: volcHeaders({ ...creds, xDate, body }), body,
730
+ });
731
+ const list = doc.TranslationList || doc.translationList || (doc.Result && doc.Result.TranslationList) || [];
732
+ const out = list.map((x) => x && x.Translation).filter(Boolean).join('\n');
733
+ if (!out) {
734
+ const err = doc.ResponseMetadata && doc.ResponseMetadata.Error;
735
+ throw new Error(err ? `火山接口错误 ${err.Code || ''}: ${err.Message || ''}` : '火山未返回译文');
736
+ }
737
+ const first = list[0] || {};
738
+ return { paragraphs: splitParagraphs(out), detectedLang: first.DetectedSourceLanguage || first.SourceLanguage || '', tts: '', dict: null };
739
+ }
740
+
741
+ const MT_ADAPTERS = {
742
+ youdao: mtYoudao, baidu: mtBaidu, caiyun: mtCaiyun, deepl: mtDeepl, deeplx: mtDeeplx,
743
+ niu: mtNiu, tencent: mtTencent, aliyun: mtAliyun, volc: mtVolc,
744
+ };
745
+
746
+ export async function translateMt(file, service, { text, targetLang }) {
747
+ const cfg = readTranslateConfig(file);
748
+ const meta = MT_SERVICES.find((s) => s.id === service);
749
+ const adapter = MT_ADAPTERS[service];
750
+ if (!meta || !adapter) throw new Error(`未知机翻服务 ${service}`);
751
+ const creds = cfg.mt.services[service] || {};
752
+ const missing = meta.creds.filter((k) => !String(creds[k] || '').trim());
753
+ if (missing.length) throw new Error(`${service} 未配置(缺 ${missing.join('/')}),请在设置页“翻译”标签填写`);
754
+ const r = await adapter(creds, { text, from: 'auto', to: targetLangFor(text, targetLang) });
755
+ // 检测语言优先用接口返回值,接口不给时按字符集猜
756
+ return { ...r, detectedLang: r.detectedLang || guessSourceLang(text) };
757
+ }
758
+
759
+ // ———— 历史记录(独立文件,避免配置文件被频繁重写) ————
760
+
761
+ export function readTranslateHistory(file) {
762
+ const doc = readJsonFile(historyFileOf(file));
763
+ return Array.isArray(doc) ? doc : [];
764
+ }
765
+
766
+ export function appendTranslateHistory(file, item, limit) {
767
+ const cur = readTranslateHistory(file);
768
+ const entry = {
769
+ t: Date.now(),
770
+ text: String(item?.text || '').slice(0, 300),
771
+ kind: item?.kind === 'dict' ? 'dict' : 'trans',
772
+ label: String(item?.label || '').slice(0, 80),
773
+ };
774
+ const next = [entry, ...cur.filter((h) => h && typeof h === 'object')].slice(0, Math.max(1, limit || 100));
775
+ const out = historyFileOf(file);
776
+ const tmp = `${out}.${process.pid}.${Date.now().toString(36)}.tmp`;
777
+ writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
778
+ renameSync(tmp, out);
779
+ }
780
+
781
+ export function translateHistoryFile(file) { return historyFileOf(file); }