dsh-bilingual-reader 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.en.md +146 -0
- package/README.md +145 -2
- package/client/client.js +88 -0
- package/cordis.patch.yml +7 -0
- package/docs/architecture.md +66 -0
- package/docs/demo.jpg +0 -0
- package/docs/release-v0.1.0.md +47 -0
- package/docs/release-v0.1.1.md +31 -0
- package/index.js +82 -0
- package/package.json +76 -4
- package/src/cache.js +76 -0
- package/src/client.js +59 -0
- package/src/config.js +74 -0
- package/src/extract.js +259 -0
- package/src/fetch.js +183 -0
- package/src/glossary.js +74 -0
- package/src/prompt.js +125 -0
- package/src/protect.js +71 -0
- package/src/routes.js +317 -0
- package/src/security.js +169 -0
- package/src/segment.js +116 -0
- package/src/store.js +325 -0
- package/src/tools.js +220 -0
- package/src/translator.js +357 -0
- package/src/util.js +62 -0
- package/web/app.js +477 -0
- package/web/favicon.svg +5 -0
- package/web/index.html +99 -0
- package/web/style.css +488 -0
package/src/store.js
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import fs from 'node:fs/promises'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { TranslationCache } from './cache.js'
|
|
4
|
+
import { normalizeTargetLang, targetLanguageName } from './config.js'
|
|
5
|
+
import { parseArticle } from './extract.js'
|
|
6
|
+
import { fetchHtml } from './fetch.js'
|
|
7
|
+
import { Glossary } from './glossary.js'
|
|
8
|
+
import { bilingualMarkdown, segmentMarkdown } from './segment.js'
|
|
9
|
+
import { Translator } from './translator.js'
|
|
10
|
+
import { nowIso, readJson, sha256, writeJsonAtomic, writeTextAtomic } from './util.js'
|
|
11
|
+
|
|
12
|
+
const TERMINAL = new Set(['done', 'partial', 'failed', 'interrupted'])
|
|
13
|
+
const ID_PATTERN = /^[a-z0-9-]+$/i
|
|
14
|
+
|
|
15
|
+
function sleep(ms) {
|
|
16
|
+
return new Promise(resolve => setTimeout(resolve, ms))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class BilingualStore {
|
|
20
|
+
constructor(config, { complete = null } = {}) {
|
|
21
|
+
this.config = config
|
|
22
|
+
this.dir = config.dir
|
|
23
|
+
this.docsDir = join(config.dir, 'docs')
|
|
24
|
+
this.cache = new TranslationCache({ file: join(config.dir, 'cache.json'), limit: config.cacheLimit })
|
|
25
|
+
this.glossary = new Glossary({ file: join(config.dir, 'glossary.json'), limit: config.glossaryLimit })
|
|
26
|
+
this.translator = new Translator({
|
|
27
|
+
config,
|
|
28
|
+
cache: this.cache,
|
|
29
|
+
glossary: this.glossary,
|
|
30
|
+
complete,
|
|
31
|
+
})
|
|
32
|
+
this.jobs = new Map()
|
|
33
|
+
this.saveQueue = Promise.resolve()
|
|
34
|
+
this.loaded = false
|
|
35
|
+
this.readyPromise = null
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
get aiEnabled() {
|
|
39
|
+
return this.translator.enabled
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
docDir(id) {
|
|
43
|
+
if (!ID_PATTERN.test(String(id ?? ''))) throw new Error('无效的文档 id')
|
|
44
|
+
return join(this.docsDir, String(id))
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
docFile(id) {
|
|
48
|
+
return join(this.docDir(id), 'doc.json')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async ready() {
|
|
52
|
+
if (this.loaded) return
|
|
53
|
+
if (this.readyPromise !== null) return this.readyPromise
|
|
54
|
+
this.readyPromise = (async () => {
|
|
55
|
+
await fs.mkdir(this.docsDir, { recursive: true })
|
|
56
|
+
await this.cache.ready()
|
|
57
|
+
await this.glossary.ready()
|
|
58
|
+
await this.recover()
|
|
59
|
+
this.loaded = true
|
|
60
|
+
})().catch(error => {
|
|
61
|
+
this.readyPromise = null
|
|
62
|
+
throw error
|
|
63
|
+
})
|
|
64
|
+
return this.readyPromise
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async recover() {
|
|
68
|
+
let entries = []
|
|
69
|
+
try {
|
|
70
|
+
entries = await fs.readdir(this.docsDir, { withFileTypes: true })
|
|
71
|
+
} catch {
|
|
72
|
+
return
|
|
73
|
+
}
|
|
74
|
+
for (const entry of entries) {
|
|
75
|
+
if (!entry.isDirectory()) continue
|
|
76
|
+
const doc = await this.getDoc(entry.name)
|
|
77
|
+
if (doc !== null && doc.status === 'running') {
|
|
78
|
+
doc.status = 'interrupted'
|
|
79
|
+
doc.error = '进程重启,翻译已中断;可以在界面里重试'
|
|
80
|
+
await this.saveDoc(doc)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async createDocFromUrl(url, options = {}) {
|
|
86
|
+
await this.ready()
|
|
87
|
+
const targetLang = normalizeTargetLang(options.targetLang, this.config.targetLang)
|
|
88
|
+
const fetched = await fetchHtml(url, this.config, { signal: options.signal })
|
|
89
|
+
const article = parseArticle(fetched.html, {
|
|
90
|
+
url: fetched.finalUrl,
|
|
91
|
+
maxMarkdownChars: this.config.maxMarkdownChars,
|
|
92
|
+
})
|
|
93
|
+
if (article.ok !== true) throw new Error(article.reason)
|
|
94
|
+
return this.createDoc({
|
|
95
|
+
markdown: article.markdown,
|
|
96
|
+
title: article.title,
|
|
97
|
+
url: fetched.finalUrl,
|
|
98
|
+
meta: {
|
|
99
|
+
siteName: article.siteName,
|
|
100
|
+
byline: article.byline,
|
|
101
|
+
published: article.published,
|
|
102
|
+
lang: article.lang,
|
|
103
|
+
excerpt: article.excerpt,
|
|
104
|
+
wordCount: article.wordCount,
|
|
105
|
+
charCount: article.charCount,
|
|
106
|
+
canonicalUrl: article.canonicalUrl,
|
|
107
|
+
requestedUrl: url,
|
|
108
|
+
fetchedAt: nowIso(),
|
|
109
|
+
httpStatus: fetched.status,
|
|
110
|
+
charset: fetched.charset,
|
|
111
|
+
bytes: fetched.bytes,
|
|
112
|
+
contentType: fetched.contentType,
|
|
113
|
+
},
|
|
114
|
+
}, { targetLang })
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async createDoc({ markdown, title, url = '', meta = {} }, options = {}) {
|
|
118
|
+
await this.ready()
|
|
119
|
+
const targetLang = normalizeTargetLang(options.targetLang, this.config.targetLang)
|
|
120
|
+
const { blocks, truncated } = segmentMarkdown(markdown, { maxBlocks: this.config.maxBlocks })
|
|
121
|
+
if (blocks.length === 0) throw new Error('正文为空,无法创建双语文档')
|
|
122
|
+
const id = sha256(`${url}\u0000${title}\u0000${Date.now()}\u0000${Math.random()}`).slice(0, 12)
|
|
123
|
+
const translatable = blocks.filter(block => block.translatable).length
|
|
124
|
+
const doc = {
|
|
125
|
+
schemaVersion: 1,
|
|
126
|
+
id,
|
|
127
|
+
title: title || '未命名文章',
|
|
128
|
+
url,
|
|
129
|
+
targetLang,
|
|
130
|
+
createdAt: nowIso(),
|
|
131
|
+
updatedAt: nowIso(),
|
|
132
|
+
status: 'pending',
|
|
133
|
+
error: '',
|
|
134
|
+
progress: 0,
|
|
135
|
+
truncated: Boolean(truncated || meta.truncated),
|
|
136
|
+
meta: { ...meta },
|
|
137
|
+
stats: {
|
|
138
|
+
requests: 0,
|
|
139
|
+
cacheHits: 0,
|
|
140
|
+
blocks: blocks.length,
|
|
141
|
+
translatable,
|
|
142
|
+
done: 0,
|
|
143
|
+
cached: 0,
|
|
144
|
+
failed: 0,
|
|
145
|
+
pending: translatable,
|
|
146
|
+
chars: markdown.length,
|
|
147
|
+
translatedChars: 0,
|
|
148
|
+
},
|
|
149
|
+
blocks: blocks.map((block, index) => ({
|
|
150
|
+
id: index,
|
|
151
|
+
type: block.type,
|
|
152
|
+
original: block.original,
|
|
153
|
+
translatable: block.translatable,
|
|
154
|
+
translation: '',
|
|
155
|
+
status: block.translatable ? 'pending' : 'skipped',
|
|
156
|
+
warning: '',
|
|
157
|
+
error: '',
|
|
158
|
+
})),
|
|
159
|
+
}
|
|
160
|
+
await writeTextAtomic(join(this.docDir(id), 'article.md'), markdown)
|
|
161
|
+
await this.saveDoc(doc)
|
|
162
|
+
return doc
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Serialize writes for the same store. Parallel translation batches finish at
|
|
167
|
+
* different times; without a queue an older snapshot could rename over a
|
|
168
|
+
* newer one and briefly hide finished blocks from the UI.
|
|
169
|
+
*/
|
|
170
|
+
saveDoc(doc) {
|
|
171
|
+
doc.updatedAt = nowIso()
|
|
172
|
+
const file = this.docFile(doc.id)
|
|
173
|
+
const write = this.saveQueue.then(() => writeJsonAtomic(file, doc))
|
|
174
|
+
this.saveQueue = write.catch(() => {})
|
|
175
|
+
return write
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async getDoc(id) {
|
|
179
|
+
try {
|
|
180
|
+
const doc = await readJson(this.docFile(id), null)
|
|
181
|
+
if (doc === null || typeof doc !== 'object' || !Array.isArray(doc.blocks)) return null
|
|
182
|
+
return doc
|
|
183
|
+
} catch {
|
|
184
|
+
return null
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async listDocs(options = {}) {
|
|
189
|
+
await this.ready()
|
|
190
|
+
const limit = options.limit ?? 30
|
|
191
|
+
let entries = []
|
|
192
|
+
try {
|
|
193
|
+
entries = await fs.readdir(this.docsDir, { withFileTypes: true })
|
|
194
|
+
} catch {
|
|
195
|
+
return []
|
|
196
|
+
}
|
|
197
|
+
const docs = []
|
|
198
|
+
for (const entry of entries) {
|
|
199
|
+
if (!entry.isDirectory()) continue
|
|
200
|
+
const doc = await this.getDoc(entry.name)
|
|
201
|
+
if (doc === null) continue
|
|
202
|
+
docs.push({
|
|
203
|
+
id: doc.id,
|
|
204
|
+
title: doc.title,
|
|
205
|
+
url: doc.url,
|
|
206
|
+
siteName: doc.meta?.siteName ?? '',
|
|
207
|
+
targetLang: doc.targetLang,
|
|
208
|
+
status: doc.status,
|
|
209
|
+
progress: doc.progress ?? 0,
|
|
210
|
+
createdAt: doc.createdAt,
|
|
211
|
+
updatedAt: doc.updatedAt,
|
|
212
|
+
stats: doc.stats,
|
|
213
|
+
})
|
|
214
|
+
}
|
|
215
|
+
docs.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
216
|
+
return docs.slice(0, limit)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async deleteDoc(id) {
|
|
220
|
+
await fs.rm(this.docDir(id), { recursive: true, force: true })
|
|
221
|
+
this.jobs.delete(id)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Start a translation in the background. Returns the doc immediately; callers
|
|
226
|
+
* can poll with waitForJob or re-read getDoc. The job is kept in memory only;
|
|
227
|
+
* a restart marks the doc interrupted during recover().
|
|
228
|
+
*/
|
|
229
|
+
async startJob(idOrDoc) {
|
|
230
|
+
const doc = typeof idOrDoc === 'string' ? await this.getDoc(idOrDoc) : idOrDoc
|
|
231
|
+
if (doc === null || doc === undefined) throw new Error('找不到文档')
|
|
232
|
+
if (doc.status === 'done') return doc
|
|
233
|
+
if (this.jobs.has(doc.id)) return doc
|
|
234
|
+
|
|
235
|
+
const job = { startedAt: nowIso(), promise: null }
|
|
236
|
+
job.promise = (async () => {
|
|
237
|
+
try {
|
|
238
|
+
await this.translator.translateDoc(doc, {
|
|
239
|
+
onProgress: async current => {
|
|
240
|
+
await this.saveDoc(current)
|
|
241
|
+
},
|
|
242
|
+
})
|
|
243
|
+
} catch (error) {
|
|
244
|
+
doc.status = 'failed'
|
|
245
|
+
doc.error = error instanceof Error ? error.message : String(error)
|
|
246
|
+
}
|
|
247
|
+
this.translator.refreshStats(doc)
|
|
248
|
+
await this.saveDoc(doc)
|
|
249
|
+
this.jobs.delete(doc.id)
|
|
250
|
+
})().catch(() => {})
|
|
251
|
+
this.jobs.set(doc.id, job)
|
|
252
|
+
return doc
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async waitForJob(id, options = {}) {
|
|
256
|
+
const timeoutMs = options.timeoutMs ?? 120_000
|
|
257
|
+
const intervalMs = options.intervalMs ?? 300
|
|
258
|
+
const deadline = Date.now() + timeoutMs
|
|
259
|
+
let doc = await this.getDoc(id)
|
|
260
|
+
if (doc === null) throw new Error('找不到文档')
|
|
261
|
+
while (!TERMINAL.has(doc.status) && Date.now() < deadline) {
|
|
262
|
+
await sleep(intervalMs)
|
|
263
|
+
doc = await this.getDoc(id)
|
|
264
|
+
if (doc === null) throw new Error('文档已被删除')
|
|
265
|
+
}
|
|
266
|
+
return doc
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async retryDoc(id) {
|
|
270
|
+
const doc = await this.getDoc(id)
|
|
271
|
+
if (doc === null) throw new Error('找不到文档')
|
|
272
|
+
for (const block of doc.blocks) {
|
|
273
|
+
if (block.translatable && block.status !== 'done' && block.status !== 'cached') {
|
|
274
|
+
block.status = 'pending'
|
|
275
|
+
block.error = ''
|
|
276
|
+
block.warning = ''
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
doc.status = 'pending'
|
|
280
|
+
doc.error = ''
|
|
281
|
+
this.translator.refreshStats(doc)
|
|
282
|
+
await this.saveDoc(doc)
|
|
283
|
+
await this.startJob(doc)
|
|
284
|
+
return doc
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async exportMarkdown(id) {
|
|
288
|
+
const doc = await this.getDoc(id)
|
|
289
|
+
if (doc === null) throw new Error('找不到文档')
|
|
290
|
+
const lines = [
|
|
291
|
+
`# ${doc.title}`,
|
|
292
|
+
'',
|
|
293
|
+
`> 原文:${doc.url || '(本地文本)'}`,
|
|
294
|
+
`> 目标语言:${targetLanguageName(doc.targetLang)}`,
|
|
295
|
+
`> 生成时间:${nowIso()}`,
|
|
296
|
+
'',
|
|
297
|
+
'---',
|
|
298
|
+
'',
|
|
299
|
+
bilingualMarkdown(doc.blocks),
|
|
300
|
+
'',
|
|
301
|
+
]
|
|
302
|
+
return lines.join('\n')
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
async translateText(text, options = {}) {
|
|
306
|
+
await this.ready()
|
|
307
|
+
const value = String(text ?? '')
|
|
308
|
+
if (value.length > this.config.maxTranslateChars) {
|
|
309
|
+
throw new Error(`文本超过 ${this.config.maxTranslateChars} 字符上限`)
|
|
310
|
+
}
|
|
311
|
+
return this.translator.translateText(value, {
|
|
312
|
+
targetLang: normalizeTargetLang(options.targetLang, this.config.targetLang),
|
|
313
|
+
title: options.title,
|
|
314
|
+
signal: options.signal,
|
|
315
|
+
})
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
stats() {
|
|
319
|
+
return {
|
|
320
|
+
jobs: this.jobs.size,
|
|
321
|
+
cache: this.cache.stats(),
|
|
322
|
+
glossary: this.glossary.list().length,
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
package/src/tools.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { TARGET_LANGUAGES, targetLanguageName } from './config.js'
|
|
2
|
+
import { bilingualMarkdown, translationMarkdown } from './segment.js'
|
|
3
|
+
|
|
4
|
+
const LANG_ENUM = TARGET_LANGUAGES.map(item => item.code)
|
|
5
|
+
|
|
6
|
+
const OUTPUT = {
|
|
7
|
+
schema: {
|
|
8
|
+
type: 'object',
|
|
9
|
+
additionalProperties: true,
|
|
10
|
+
properties: { text: { type: 'string' } },
|
|
11
|
+
required: ['text'],
|
|
12
|
+
},
|
|
13
|
+
render: (_args, value) => [{ type: 'text', text: String(value?.text ?? '') }],
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function statusLabel(status) {
|
|
17
|
+
return {
|
|
18
|
+
pending: '待翻译',
|
|
19
|
+
running: '翻译中',
|
|
20
|
+
done: '已完成',
|
|
21
|
+
partial: '部分完成',
|
|
22
|
+
failed: '失败',
|
|
23
|
+
interrupted: '已中断',
|
|
24
|
+
}[status] ?? status
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function docSummary(doc) {
|
|
28
|
+
const stats = doc.stats ?? {}
|
|
29
|
+
const lines = [
|
|
30
|
+
`《${doc.title}》`,
|
|
31
|
+
`id: ${doc.id}`,
|
|
32
|
+
doc.url ? `url: ${doc.url}` : '来源:本地文本',
|
|
33
|
+
`目标语言:${targetLanguageName(doc.targetLang)}`,
|
|
34
|
+
`状态:${statusLabel(doc.status)}(${Math.round((doc.progress ?? 0) * 100)}%)`,
|
|
35
|
+
`段落:${stats.done ?? 0}/${stats.translatable ?? 0},缓存命中 ${stats.cached ?? 0},失败 ${stats.failed ?? 0},请求 ${stats.requests ?? 0}`,
|
|
36
|
+
]
|
|
37
|
+
if (doc.error) lines.push(`错误:${doc.error}`)
|
|
38
|
+
if (doc.status === 'running') lines.push('翻译仍在后台进行,可稍后用 bilingual_status 查看。')
|
|
39
|
+
return lines.join('\n')
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function previewBlocks(doc, limit = 6) {
|
|
43
|
+
const blocks = doc.blocks
|
|
44
|
+
.filter(block => block.translatable && block.translation)
|
|
45
|
+
.slice(0, limit)
|
|
46
|
+
if (blocks.length === 0) return ''
|
|
47
|
+
return blocks
|
|
48
|
+
.map(block => `原文:${block.original}\n译文:${block.translation}`)
|
|
49
|
+
.join('\n\n')
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function registerTools(ctx, { store }) {
|
|
53
|
+
ctx.tools.register({
|
|
54
|
+
name: 'bilingual_read_url',
|
|
55
|
+
description:
|
|
56
|
+
'抓取一个公开网页,提取正文,按段落翻译成目标语言,并保存为双语阅读文档。' +
|
|
57
|
+
'当用户要求“翻译这篇文章 / 双语阅读这个链接 / 读懂这个页面”时使用。' +
|
|
58
|
+
'默认等待翻译完成(最多约 2 分钟);长文章可传 wait=false,再用 bilingual_status 查询。' +
|
|
59
|
+
'只能访问 http/https 公开页面,内网和本机地址会被拒绝。',
|
|
60
|
+
parameters: {
|
|
61
|
+
type: 'object',
|
|
62
|
+
additionalProperties: false,
|
|
63
|
+
properties: {
|
|
64
|
+
url: { type: 'string', description: '要阅读和翻译的 http/https URL。' },
|
|
65
|
+
targetLang: {
|
|
66
|
+
type: 'string',
|
|
67
|
+
enum: LANG_ENUM,
|
|
68
|
+
description: '目标语言,默认使用插件配置(通常是 zh-CN)。',
|
|
69
|
+
},
|
|
70
|
+
wait: {
|
|
71
|
+
type: 'boolean',
|
|
72
|
+
description: '是否等待翻译完成;默认 true。长文章可以设 false 后轮询。',
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
required: ['url'],
|
|
76
|
+
},
|
|
77
|
+
output: OUTPUT,
|
|
78
|
+
timeoutMs: 150_000,
|
|
79
|
+
isConcurrencySafe: () => false,
|
|
80
|
+
async execute(args, exec) {
|
|
81
|
+
if (args === null || typeof args !== 'object' || typeof args.url !== 'string' || args.url.trim() === '') {
|
|
82
|
+
throw new Error('bilingual_read_url 需要非空的 url')
|
|
83
|
+
}
|
|
84
|
+
const doc = await store.createDocFromUrl(args.url.trim(), {
|
|
85
|
+
targetLang: args.targetLang,
|
|
86
|
+
signal: exec.signal,
|
|
87
|
+
})
|
|
88
|
+
await store.startJob(doc)
|
|
89
|
+
const current = args.wait === false
|
|
90
|
+
? doc
|
|
91
|
+
: await store.waitForJob(doc.id, { timeoutMs: 115_000 })
|
|
92
|
+
const lines = [docSummary(current)]
|
|
93
|
+
const preview = previewBlocks(current)
|
|
94
|
+
if (preview !== '') lines.push('', preview)
|
|
95
|
+
if (current.status === 'done' || current.status === 'partial') {
|
|
96
|
+
lines.push('', `可在侧栏“双语阅读”里打开对照视图,或导出双语 Markdown。`)
|
|
97
|
+
}
|
|
98
|
+
return { text: lines.join('\n') }
|
|
99
|
+
},
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
ctx.tools.register({
|
|
103
|
+
name: 'bilingual_translate',
|
|
104
|
+
description:
|
|
105
|
+
'把一段 Markdown 或纯文本翻译成目标语言,保留代码、链接、公式、表格和标题结构。' +
|
|
106
|
+
'适合用户粘贴一段文字要求翻译;不需要保存为文档。结果会被缓存,重复内容不会再次调用模型。',
|
|
107
|
+
parameters: {
|
|
108
|
+
type: 'object',
|
|
109
|
+
additionalProperties: false,
|
|
110
|
+
properties: {
|
|
111
|
+
text: { type: 'string', description: '要翻译的文本,支持 Markdown。' },
|
|
112
|
+
targetLang: {
|
|
113
|
+
type: 'string',
|
|
114
|
+
enum: LANG_ENUM,
|
|
115
|
+
description: '目标语言,默认使用插件配置。',
|
|
116
|
+
},
|
|
117
|
+
bilingual: {
|
|
118
|
+
type: 'boolean',
|
|
119
|
+
description: '为 true 时返回原文 + 译文对照,否则只返回译文。',
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
required: ['text'],
|
|
123
|
+
},
|
|
124
|
+
output: OUTPUT,
|
|
125
|
+
timeoutMs: 120_000,
|
|
126
|
+
isConcurrencySafe: () => false,
|
|
127
|
+
async execute(args, exec) {
|
|
128
|
+
if (args === null || typeof args !== 'object' || typeof args.text !== 'string' || args.text.trim() === '') {
|
|
129
|
+
throw new Error('bilingual_translate 需要非空的 text')
|
|
130
|
+
}
|
|
131
|
+
const doc = await store.translateText(args.text, {
|
|
132
|
+
targetLang: args.targetLang,
|
|
133
|
+
signal: exec.signal,
|
|
134
|
+
})
|
|
135
|
+
const body = args.bilingual === true
|
|
136
|
+
? bilingualMarkdown(doc.blocks)
|
|
137
|
+
: translationMarkdown(doc.blocks)
|
|
138
|
+
return {
|
|
139
|
+
text: [
|
|
140
|
+
`目标语言:${targetLanguageName(doc.targetLang)}`,
|
|
141
|
+
`段落:${doc.stats?.done ?? 0}/${doc.stats?.translatable ?? 0},缓存命中 ${doc.stats?.cached ?? 0},失败 ${doc.stats?.failed ?? 0}`,
|
|
142
|
+
'',
|
|
143
|
+
body,
|
|
144
|
+
].join('\n'),
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
ctx.tools.register({
|
|
150
|
+
name: 'bilingual_status',
|
|
151
|
+
description:
|
|
152
|
+
'查看一个双语阅读文档的翻译进度、失败段落和部分译文。' +
|
|
153
|
+
'当 bilingual_read_url 返回“翻译仍在后台进行”或用户问“翻译好了吗”时使用。',
|
|
154
|
+
parameters: {
|
|
155
|
+
type: 'object',
|
|
156
|
+
additionalProperties: false,
|
|
157
|
+
properties: {
|
|
158
|
+
id: { type: 'string', description: 'bilingual_read_url 返回的文档 id。' },
|
|
159
|
+
includeTranslations: {
|
|
160
|
+
type: 'boolean',
|
|
161
|
+
description: '为 true 时附带前 20 个已完成段落的原文和译文。',
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
required: ['id'],
|
|
165
|
+
},
|
|
166
|
+
output: OUTPUT,
|
|
167
|
+
timeoutMs: 30_000,
|
|
168
|
+
isConcurrencySafe: () => true,
|
|
169
|
+
async execute(args) {
|
|
170
|
+
await store.ready()
|
|
171
|
+
const doc = await store.getDoc(args?.id)
|
|
172
|
+
if (doc === null) throw new Error(`找不到文档:${args?.id}`)
|
|
173
|
+
const lines = [docSummary(doc)]
|
|
174
|
+
if (args.includeTranslations === true) {
|
|
175
|
+
const preview = previewBlocks(doc, 20)
|
|
176
|
+
if (preview !== '') lines.push('', preview)
|
|
177
|
+
}
|
|
178
|
+
return { text: lines.join('\n') }
|
|
179
|
+
},
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
ctx.tools.register({
|
|
183
|
+
name: 'bilingual_glossary',
|
|
184
|
+
description:
|
|
185
|
+
'管理双语阅读的术语表。翻译时会强制使用术语表里的译法。' +
|
|
186
|
+
'action=list 查看;action=add 添加或更新(需要 source 和 target);action=remove 删除(需要 source)。',
|
|
187
|
+
parameters: {
|
|
188
|
+
type: 'object',
|
|
189
|
+
additionalProperties: false,
|
|
190
|
+
properties: {
|
|
191
|
+
action: { type: 'string', enum: ['list', 'add', 'remove'] },
|
|
192
|
+
source: { type: 'string', description: '原文术语,例如 token。' },
|
|
193
|
+
target: { type: 'string', description: '目标语言术语,例如 令牌。' },
|
|
194
|
+
note: { type: 'string', description: '可选备注。' },
|
|
195
|
+
},
|
|
196
|
+
required: ['action'],
|
|
197
|
+
},
|
|
198
|
+
output: OUTPUT,
|
|
199
|
+
timeoutMs: 30_000,
|
|
200
|
+
isConcurrencySafe: () => false,
|
|
201
|
+
async execute(args) {
|
|
202
|
+
await store.ready()
|
|
203
|
+
const action = args?.action
|
|
204
|
+
if (action === 'add') {
|
|
205
|
+
store.glossary.add(args.source, args.target, args.note)
|
|
206
|
+
await store.glossary.flush()
|
|
207
|
+
} else if (action === 'remove') {
|
|
208
|
+
store.glossary.remove(args.source)
|
|
209
|
+
await store.glossary.flush()
|
|
210
|
+
} else if (action !== 'list') {
|
|
211
|
+
throw new Error('action 只支持 list / add / remove')
|
|
212
|
+
}
|
|
213
|
+
const terms = store.glossary.list()
|
|
214
|
+
const lines = terms.length === 0
|
|
215
|
+
? ['术语表为空。']
|
|
216
|
+
: terms.map(term => `${term.source} => ${term.target}${term.note ? `(${term.note})` : ''}`)
|
|
217
|
+
return { text: lines.join('\n') }
|
|
218
|
+
},
|
|
219
|
+
})
|
|
220
|
+
}
|