dsh-chatbot-tools 0.0.0-stage → 0.2.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/CHANGELOG.md +62 -0
- package/LICENSE +21 -0
- package/README-en.md +199 -0
- package/README.md +199 -2
- package/client.js +83 -0
- package/cordis.patch.yml +20 -0
- package/docs/feedback-safety-check-exclusivity.md +82 -0
- package/docs/feedback-tts-code-switch.md +108 -0
- package/docs/incident-2026-11-17-safety-check-defer-loading.md +220 -0
- package/docs/incident-2026-11-17-tool-result-image.md +63 -0
- package/docs/verification-2026-11-17.md +471 -0
- package/lib/index.js +788 -0
- package/lib/safety.js +106 -0
- package/lib/speakable.js +162 -0
- package/lib/speech.js +94 -0
- package/package.json +71 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-chatbot-tools — 补齐 DeepSeek Chatbot 有、DSH 缺的能力:
|
|
3
|
+
* 1. 模型内容安全(safety_check,官方请求顶层字段,经 deepseekLlmApiExtensions 注入)
|
|
4
|
+
* 2. 图片搜索(Search API 不支持,只能走服务端工具 deepseek_web_search,需消息内带图)
|
|
5
|
+
* 3. 结构化引用来源(Search API 的 site_name/site_icon/date/authority)
|
|
6
|
+
* 4. 文档识别 OCR / 语音识别 ASR / 语音合成 TTS(官方工具 API)
|
|
7
|
+
*
|
|
8
|
+
* 设计约束(源码证据见 docs/incident-*.md):
|
|
9
|
+
* - 主对话不能声明服务端联网工具:dsh-llm-deepseek 的 translate.startBlock 对未知块抛
|
|
10
|
+
* UNSUPPORTED_CONTENT(src/translate.ts:60),且 extension 合并拒绝覆盖 base 的 tools 字段。
|
|
11
|
+
* 因此图片搜索走"辅助 Messages 调用",与会话主链路解耦。
|
|
12
|
+
* - safety_check 有三条服务端硬约束:与 defer_loading 互斥、非思考模式与 client tools 互斥、
|
|
13
|
+
* 内部 title 请求不需要。守卫见 lib/safety.js。
|
|
14
|
+
* - 拒答(stop_reason: refusal)会让适配器抛 unsupported stop reason,用 llm/stream 兜底。
|
|
15
|
+
* - 凭证优先复用 DeepSeek 账号登录(x-dsh-auth-token),回退 DEEPSEEK_API_KEY 或字面 apiKey。
|
|
16
|
+
*
|
|
17
|
+
* 设置页:Config 每个字段都标 .volatile(),宿主据此生成表单;被标记的字段以 live reference
|
|
18
|
+
* 形式传入,因此请求期一律走 live() 读取,改设置不需要重载插件。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { appendFileSync, mkdirSync } from 'node:fs'
|
|
22
|
+
import { readFile, writeFile } from 'node:fs/promises'
|
|
23
|
+
import os from 'node:os'
|
|
24
|
+
import path, { extname } from 'node:path'
|
|
25
|
+
import z from '@deepseek-ai/schemastery'
|
|
26
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
27
|
+
import { deferredToolNames, isRefusalError, safetyDecision } from './safety.js'
|
|
28
|
+
import { createDeepSeekSpeechProvider } from './speech.js'
|
|
29
|
+
import { applyTerms, parseTermMap, toSpeakable } from './speakable.js'
|
|
30
|
+
|
|
31
|
+
export const name = 'dsh-chatbot-tools'
|
|
32
|
+
export const inject = ['tools']
|
|
33
|
+
|
|
34
|
+
/** 构建标记:每次改动递增,用来在日志里确认 hotreload 真的换上了新代码。 */
|
|
35
|
+
const BUILD_TAG = 'r20-image-guard'
|
|
36
|
+
|
|
37
|
+
/** cosmokit 给 volatile 配置引用打的标记;值在运行时会被包成 { get() } 的活引用。 */
|
|
38
|
+
const VOLATILE_WRITE = Symbol.for('cosmokit.volatile.write')
|
|
39
|
+
|
|
40
|
+
/** 默认配置;设置页写入的覆盖会合到它上面。 */
|
|
41
|
+
const DEFAULTS = {
|
|
42
|
+
// 平台 API Key。Search / OCR 接受账号登录,但 TTS / ASR 只认 API Key(实测 401),
|
|
43
|
+
// 所以需要语音能力时必须提供它(设置页填写或 DEEPSEEK_API_KEY 环境变量)。
|
|
44
|
+
apiKey: '',
|
|
45
|
+
/** 宿主凭据服务里的 key 名;默认与 DSH 的 DeepSeek 适配器一致。 */
|
|
46
|
+
apiKeyRef: 'DEEPSEEK_API_KEY',
|
|
47
|
+
apiBaseURL: 'https://api.deepseek.com',
|
|
48
|
+
messagesBaseURL: 'https://api.deepseek.com/anthropic/v1',
|
|
49
|
+
apiVersion: '2023-06-01',
|
|
50
|
+
model: 'deepseek-flash',
|
|
51
|
+
maxTokens: 1024,
|
|
52
|
+
maxUses: 1,
|
|
53
|
+
serverTool: 'deepseek_web_search',
|
|
54
|
+
searchCount: 8,
|
|
55
|
+
maxImageBytes: 4 * 1024 * 1024,
|
|
56
|
+
// 2026-11-17 事故:safety_check 与 defer_loading / 非思考模式互斥,三态 + 守卫。
|
|
57
|
+
// 复现见 docs/incident-2026-11-17-safety-check-defer-loading.md。
|
|
58
|
+
safetyMode: 'enforce',
|
|
59
|
+
safetyLevel: 'high',
|
|
60
|
+
safetyGuardDeferLoading: true,
|
|
61
|
+
safetyLog: true,
|
|
62
|
+
safetySkipPurposes: ['title', 'session-title'],
|
|
63
|
+
ocrPurpose: 'text_recognition',
|
|
64
|
+
ocrMaxChars: 8000,
|
|
65
|
+
ttsVoice: 'stella',
|
|
66
|
+
ttsFormat: 'wav',
|
|
67
|
+
ttsOutDir: '',
|
|
68
|
+
ttsMaxChars: 10000,
|
|
69
|
+
ttsFilterMarkdown: false,
|
|
70
|
+
// skip 删除代码块 / placeholder 念一句占位 / read 保留代码内容
|
|
71
|
+
ttsCodeMode: 'skip',
|
|
72
|
+
// 术语替换表:官方 TTS 无语种/prompt 参数,英文词易被误判,这里做朗读前替换
|
|
73
|
+
ttsTermMap: '',
|
|
74
|
+
// Files API 默认解析方式(见 guides/document_parsing)
|
|
75
|
+
documentPurpose: 'text_recognition',
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 设置页 schema。每个字段都标 `.volatile()` —— 设置服务只用 volatile 节点建表单,
|
|
80
|
+
* 一个标记都没有的 schema 会**静默地不生成任何表单**。volatile 同时意味着宿主把改动
|
|
81
|
+
* 直接写进运行中的引用(不重载插件),所以请求期必须用 live() 现读。
|
|
82
|
+
*/
|
|
83
|
+
export const Config = z.object({
|
|
84
|
+
apiKey: z.string().default('').volatile()
|
|
85
|
+
.description('平台 API Key(TTS/ASR 必需;Search/OCR 可用账号登录)。明文存 profile patch,建议改用 DEEPSEEK_API_KEY'),
|
|
86
|
+
apiKeyRef: z.string().default('DEEPSEEK_API_KEY').volatile()
|
|
87
|
+
.description('宿主凭据服务里的 key 名(默认与 DSH 的 DeepSeek 适配器一致)'),
|
|
88
|
+
safetyMode: z.union([z.const('off'), z.const('observe'), z.const('enforce')]).default('enforce').volatile()
|
|
89
|
+
.description('内容安全:off 关闭 / observe 只记录 / enforce 注入 safety_check'),
|
|
90
|
+
safetyLevel: z.union([z.const('high'), z.const('low')]).default('high').volatile()
|
|
91
|
+
.description('内容安全级别:high 基础风控 / low 等同不传'),
|
|
92
|
+
safetyGuardDeferLoading: z.boolean().default(true).volatile()
|
|
93
|
+
.description('请求带 defer_loading 时跳过注入(事故守卫,务必保持开启)'),
|
|
94
|
+
safetyLog: z.boolean().default(true).volatile()
|
|
95
|
+
.description('把每次请求的工具形态记到 ~/.dsh/logs/chatbot-tools-safety.ndjson'),
|
|
96
|
+
safetySkipPurposes: z.array(z.string()).default(['title', 'session-title']).volatile()
|
|
97
|
+
.description('这些内部请求不注入 safety_check,省费用'),
|
|
98
|
+
model: z.string().default('deepseek-flash').volatile()
|
|
99
|
+
.description('辅助调用(图片搜索 / 结构化搜索 / OCR 之外的模型调用)使用的模型'),
|
|
100
|
+
serverTool: z.string().default('deepseek_web_search').volatile()
|
|
101
|
+
.description('图片搜索使用的服务端工具名'),
|
|
102
|
+
maxUses: z.number().step(1).min(1).default(1).volatile()
|
|
103
|
+
.description('单次图片搜索的服务端工具调用上限'),
|
|
104
|
+
maxTokens: z.number().step(1).min(16).default(1024).volatile()
|
|
105
|
+
.description('辅助调用的输出上限'),
|
|
106
|
+
maxImageBytes: z.number().step(1).min(1024).default(4194304).volatile()
|
|
107
|
+
.description('图片搜索的图片大小上限(字节)'),
|
|
108
|
+
apiBaseURL: z.string().default('https://api.deepseek.com').volatile()
|
|
109
|
+
.description('工具 API 基址(/v1/tools/*)'),
|
|
110
|
+
messagesBaseURL: z.string().default('https://api.deepseek.com/anthropic/v1').volatile()
|
|
111
|
+
.description('Anthropic 兼容 Messages 基址(图片搜索用)'),
|
|
112
|
+
searchCount: z.number().step(1).min(1).max(50).default(8).volatile()
|
|
113
|
+
.description('chatbot_search 默认返回条数'),
|
|
114
|
+
ocrPurpose: z.union([z.const('text_recognition'), z.const('rich_layout_recognition')]).default('text_recognition').volatile()
|
|
115
|
+
.description('OCR 模式:纯文本提取 / 逐页版面识别'),
|
|
116
|
+
ocrMaxChars: z.number().step(1).min(200).default(8000).volatile()
|
|
117
|
+
.description('OCR 结果返回给模型的字符上限'),
|
|
118
|
+
documentPurpose: z.union([z.const('text_recognition'), z.const('rich_layout_recognition'), z.const('user_data')])
|
|
119
|
+
.default('text_recognition').volatile()
|
|
120
|
+
.description('chatbot_upload_document 默认的解析方式。text_recognition 只要文字(按页计费)/ '
|
|
121
|
+
+ 'rich_layout_recognition 文字+文中图表(按页计费)/ user_data 不解析不计费(纯文本、表格、电子书)'),
|
|
122
|
+
ttsVoice: z.union([z.const('stella'), z.const('tide')]).default('stella').volatile()
|
|
123
|
+
.description('朗读音色:stella 海星(女声)/ tide 暗潮(男声)'),
|
|
124
|
+
ttsFormat: z.union([z.const('wav'), z.const('pcm')]).default('wav').volatile()
|
|
125
|
+
.description('朗读输出格式'),
|
|
126
|
+
ttsOutDir: z.string().default('').volatile()
|
|
127
|
+
.description('朗读文件输出目录,留空用 ~/.dsh/chatbot-tools/out'),
|
|
128
|
+
ttsMaxChars: z.number().step(1).min(1).max(10000).default(10000).volatile()
|
|
129
|
+
.description('单次朗读的字符上限(服务端上限 10000)'),
|
|
130
|
+
ttsFilterMarkdown: z.boolean().default(false).volatile()
|
|
131
|
+
.description('朗读前由服务端去掉 Markdown。默认 false:插件已自己把 Markdown 转成可朗读文本'
|
|
132
|
+
+ '(行内代码保留,避免像 ttsFilterMarkdown 这样的词被吞掉)'),
|
|
133
|
+
ttsCodeMode: z.union([z.const('skip'), z.const('placeholder'), z.const('read')]).default('skip').volatile()
|
|
134
|
+
.description('代码块怎么处理:skip 删除 / placeholder 念一句「这里有一段代码」/ read 保留内容'),
|
|
135
|
+
ttsTermMap: z.string().default('').volatile()
|
|
136
|
+
.description('朗读前的术语替换表。JSON 或 key=value 形式,例如 {"Markdown":"马克当","API":"接口"}。'
|
|
137
|
+
+ '官方 TTS 无语种/prompt 参数,英文词在中文里可能被读错,用这里换成读音稳定的说法'),
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
const MEDIA = {
|
|
141
|
+
'.png': 'image/png',
|
|
142
|
+
'.jpg': 'image/jpeg',
|
|
143
|
+
'.jpeg': 'image/jpeg',
|
|
144
|
+
'.webp': 'image/webp',
|
|
145
|
+
'.gif': 'image/gif',
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** 拆开 volatile 引用,拿到真实值。 */
|
|
149
|
+
function plainValue(value) {
|
|
150
|
+
if (value !== null && typeof value === 'object' && VOLATILE_WRITE in value && typeof value.get === 'function') {
|
|
151
|
+
return plainValue(value.get())
|
|
152
|
+
}
|
|
153
|
+
return value
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** 把整个 config 物化成普通对象(一层)。 */
|
|
157
|
+
function plainConfig(config) {
|
|
158
|
+
if (config === null || typeof config !== 'object') return {}
|
|
159
|
+
const out = {}
|
|
160
|
+
for (const [key, value] of Object.entries(config)) out[key] = plainValue(value)
|
|
161
|
+
return out
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 现读配置:设置页改完立刻生效,不需要重载。 */
|
|
165
|
+
function settings(config) {
|
|
166
|
+
return { ...DEFAULTS, ...plainConfig(config) }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 解析一次请求的鉴权头:显式设置 > 环境变量 > 宿主凭据服务 > DeepSeek 账号登录。 */
|
|
170
|
+
async function authHeaders(ctx, cfg, endpoint) {
|
|
171
|
+
const explicit = typeof cfg.apiKey === 'string' ? cfg.apiKey.trim() : ''
|
|
172
|
+
const env = (process.env.DEEPSEEK_API_KEY ?? '').trim()
|
|
173
|
+
let key = explicit.length > 0 ? explicit : env
|
|
174
|
+
let source = explicit.length > 0 ? 'settings' : env.length > 0 ? 'env' : ''
|
|
175
|
+
if (key.length === 0) {
|
|
176
|
+
// 宿主凭据服务是权威来源(DSH 设置里填过的 API Key 就存这里),
|
|
177
|
+
// 走与官方适配器同一条路径:ctx.get('credentials').resolve(ref)。
|
|
178
|
+
const credentials = ctx.get('credentials')
|
|
179
|
+
if (credentials && typeof credentials.resolve === 'function') {
|
|
180
|
+
const ref = typeof cfg.apiKeyRef === 'string' && cfg.apiKeyRef.trim().length > 0 ? cfg.apiKeyRef.trim() : 'DEEPSEEK_API_KEY'
|
|
181
|
+
try {
|
|
182
|
+
const hit = await credentials.resolve(ref)
|
|
183
|
+
if (hit && typeof hit.value === 'string' && hit.value.length > 0) {
|
|
184
|
+
key = hit.value
|
|
185
|
+
source = `credentials:${ref}`
|
|
186
|
+
}
|
|
187
|
+
} catch {
|
|
188
|
+
/* 凭据服务不可用则继续走账号通道 */
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (key.length > 0) {
|
|
193
|
+
return { kind: 'api-key', source, headers: { 'x-api-key': key, authorization: `Bearer ${key}` } }
|
|
194
|
+
}
|
|
195
|
+
const account = ctx.get('deepseekAccount')
|
|
196
|
+
if (account && typeof account.resolveToken === 'function') {
|
|
197
|
+
let token
|
|
198
|
+
try {
|
|
199
|
+
token = await account.resolveToken(endpoint)
|
|
200
|
+
} catch {
|
|
201
|
+
token = undefined
|
|
202
|
+
}
|
|
203
|
+
if (typeof token === 'string' && token.length > 0) {
|
|
204
|
+
// 同一账号 token 双发:Search/OCR 认 x-dsh-auth-token;TTS/ASR 实测仍 401(只认平台 Key)。
|
|
205
|
+
return { kind: 'account', headers: { 'x-dsh-auth-token': token, authorization: `Bearer ${token}` } }
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
throw new Error(
|
|
209
|
+
'没有可用的 DeepSeek 凭证:TTS/ASR 需要平台 API Key —— 在 DSH 设置里配置 API Key、在插件设置里填 apiKey,'
|
|
210
|
+
+ '或设置 DEEPSEEK_API_KEY 环境变量;Search/OCR 可直接用应用内 DeepSeek 账号登录。',
|
|
211
|
+
)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** 401 时给出可行动的说明(账号 token 在部分工具 API 上不被接受)。 */
|
|
215
|
+
function authHint(result, auth) {
|
|
216
|
+
if (result.status === 401 && auth.kind === 'account') {
|
|
217
|
+
return '(账号登录在 TTS/ASR 上不被接受:请在插件设置里填 apiKey,或设置 DEEPSEEK_API_KEY)'
|
|
218
|
+
}
|
|
219
|
+
return ''
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** 发送一次 JSON POST,返回 { status, ok, body, raw }。 */
|
|
223
|
+
async function postJSON(url, headers, body, timeoutMs = 60000) {
|
|
224
|
+
return send(url, {
|
|
225
|
+
method: 'POST',
|
|
226
|
+
headers: { 'content-type': 'application/json', ...headers },
|
|
227
|
+
body: JSON.stringify(body),
|
|
228
|
+
}, timeoutMs)
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** 发送一次 multipart POST(FormData 自带 boundary,不要手写 content-type)。 */
|
|
232
|
+
async function postForm(url, headers, form, timeoutMs = 180000) {
|
|
233
|
+
return send(url, { method: 'POST', headers, body: form }, timeoutMs)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** 统一 fetch:超时、错误说明、JSON 解析。 */
|
|
237
|
+
async function send(url, init, timeoutMs) {
|
|
238
|
+
const controller = new AbortController()
|
|
239
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
240
|
+
let response
|
|
241
|
+
try {
|
|
242
|
+
response = await fetch(url, { redirect: 'error', ...init, signal: controller.signal })
|
|
243
|
+
} catch (error) {
|
|
244
|
+
throw new Error(`请求 ${url} 失败:${String(error)}`)
|
|
245
|
+
} finally {
|
|
246
|
+
clearTimeout(timer)
|
|
247
|
+
}
|
|
248
|
+
const buffer = Buffer.from(await response.arrayBuffer())
|
|
249
|
+
let body
|
|
250
|
+
try {
|
|
251
|
+
body = buffer.length > 0 ? JSON.parse(buffer.toString('utf8')) : undefined
|
|
252
|
+
} catch {
|
|
253
|
+
body = undefined
|
|
254
|
+
}
|
|
255
|
+
return { status: response.status, ok: response.ok, body, buffer, contentType: response.headers.get('content-type') ?? '' }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Files API 的失败码说明(guides/document_parsing「Limits and Errors」)。 */
|
|
259
|
+
function uploadHint(status) {
|
|
260
|
+
const hints = {
|
|
261
|
+
400: '(文件无法解析/格式不支持/加密,或 purpose 被排在 file 之后)',
|
|
262
|
+
408: '(上传太慢,需在 120 秒内传完)',
|
|
263
|
+
413: '(文件超过 100 MiB)',
|
|
264
|
+
429: '(账号并发上传过多,上限 15,等一会儿再试)',
|
|
265
|
+
500: '(解析结果不完整)',
|
|
266
|
+
503: '(服务繁忙,稍后重试)',
|
|
267
|
+
504: '(解析超过 120 秒)',
|
|
268
|
+
}
|
|
269
|
+
return hints[status] ?? ''
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** 从 Anthropic / OpenAI 兼容错误体里取一句可读信息。 */
|
|
273
|
+
function apiDetail(result) {
|
|
274
|
+
const body = result.body
|
|
275
|
+
if (body && typeof body === 'object') {
|
|
276
|
+
const error = body.error
|
|
277
|
+
if (typeof error === 'string' && error.length > 0) return error
|
|
278
|
+
if (error && typeof error.message === 'string') return error.message
|
|
279
|
+
if (typeof body.message === 'string') return body.message
|
|
280
|
+
}
|
|
281
|
+
const text = result.buffer.toString('utf8').slice(0, 300)
|
|
282
|
+
return text.length > 0 ? text : `HTTP ${result.status}`
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** 追加一行结构化事件到观测日志(失败不影响插件)。 */
|
|
286
|
+
function logEvent(event) {
|
|
287
|
+
try {
|
|
288
|
+
const dir = path.join(os.homedir(), '.dsh', 'logs')
|
|
289
|
+
mkdirSync(dir, { recursive: true })
|
|
290
|
+
appendFileSync(
|
|
291
|
+
path.join(dir, 'chatbot-tools-safety.ndjson'),
|
|
292
|
+
JSON.stringify({ ts: new Date().toISOString(), event }) + '\n',
|
|
293
|
+
)
|
|
294
|
+
} catch {
|
|
295
|
+
/* 观测失败不影响插件 */
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** 观测模式:只记工具形态,不记录消息内容。 */
|
|
300
|
+
function logSafetyObservation(request, decision) {
|
|
301
|
+
try {
|
|
302
|
+
const deferred = deferredToolNames(request)
|
|
303
|
+
const tools = Array.isArray(request.body?.tools) ? request.body.tools : []
|
|
304
|
+
// 四个互斥顶层字段谁在场:用来区分「是 DSH 自己注入的」还是「本插件注入的」。
|
|
305
|
+
// safety_check 在这一行里出现,说明进入 prepare 前 body 里已经有了(本插件是在之后才加的)。
|
|
306
|
+
const serverFields = ['deepseek_web_search', 'deepseek_read_url', 'safety_check', 'title']
|
|
307
|
+
.filter(name => request.body != null && Object.prototype.hasOwnProperty.call(request.body, name))
|
|
308
|
+
const line = JSON.stringify({
|
|
309
|
+
ts: new Date().toISOString(),
|
|
310
|
+
purpose: request.purpose ?? null,
|
|
311
|
+
thinking: request.body?.thinking?.type ?? null,
|
|
312
|
+
toolCount: tools.length,
|
|
313
|
+
deferredCount: deferred.length,
|
|
314
|
+
deferredNames: deferred,
|
|
315
|
+
serverFields,
|
|
316
|
+
nonTextResults: decision.nonTextResults ?? 0,
|
|
317
|
+
decision: decision.reason,
|
|
318
|
+
})
|
|
319
|
+
const dir = path.join(os.homedir(), '.dsh', 'logs')
|
|
320
|
+
mkdirSync(dir, { recursive: true })
|
|
321
|
+
appendFileSync(path.join(dir, 'chatbot-tools-safety.ndjson'), line + '\n')
|
|
322
|
+
} catch {
|
|
323
|
+
/* 观测失败不影响请求 */
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** 把 image_search 结果块转成 markdown 列表。 */
|
|
328
|
+
function renderImageResults(blocks) {
|
|
329
|
+
const lines = []
|
|
330
|
+
const searches = blocks.filter(block => block && block.type === 'server_tool_use' && block.kind === 'image_search')
|
|
331
|
+
for (const block of blocks) {
|
|
332
|
+
if (!block || block.type !== 'web_search_tool_result') continue
|
|
333
|
+
for (const item of block.content ?? []) {
|
|
334
|
+
if (!item || typeof item.url !== 'string') continue
|
|
335
|
+
const title = typeof item.title === 'string' && item.title.length > 0 ? item.title : '(无标题)'
|
|
336
|
+
const image = typeof item.image_url === 'string' && item.image_url.length > 0 ? item.image_url : undefined
|
|
337
|
+
lines.push(image ? `-  — 来源页:${item.url}` : `- ${title} — ${item.url}`)
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
const header = `图片搜索完成(服务端调用 ${searches.length} 次)`
|
|
341
|
+
return lines.length > 0
|
|
342
|
+
? `${header},结果 ${lines.length} 条:\n${lines.join('\n')}`
|
|
343
|
+
: `${header},但没有取到图片结果。可换一张更清晰的图或补一句 query 重试。`
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** 把 Search API 结果转成结构化 markdown(带站点/时间/权威度)。 */
|
|
347
|
+
function renderSources(results) {
|
|
348
|
+
return results.map((item, index) => {
|
|
349
|
+
const meta = [item.site_name, item.date, typeof item.authority === 'number' ? `权威度 ${item.authority}` : undefined]
|
|
350
|
+
.filter(part => typeof part === 'string' && part.length > 0)
|
|
351
|
+
.join(' · ')
|
|
352
|
+
const summary = typeof item.summary === 'string' && item.summary.length > 0 ? item.summary : item.snippet
|
|
353
|
+
return `${index + 1}. [${item.title || item.url}](${item.url})${meta ? ` — ${meta}` : ''}\n ${summary ?? ''}`
|
|
354
|
+
}).join('\n')
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
/** 从会话日志里取出某条 assistant 消息的正文(供 TTS 路由使用)。 */
|
|
359
|
+
function messageText(ctx, sessionId, messageId) {
|
|
360
|
+
if (!sessionId || !messageId) return ''
|
|
361
|
+
const session = ctx.get('agents')?.get(sessionId)?.session
|
|
362
|
+
if (!session) return ''
|
|
363
|
+
let events = []
|
|
364
|
+
try {
|
|
365
|
+
events = session.snapshotEvents()
|
|
366
|
+
} catch {
|
|
367
|
+
return ''
|
|
368
|
+
}
|
|
369
|
+
for (const event of events) {
|
|
370
|
+
if (!event || event.type !== 'assistant/message') continue
|
|
371
|
+
const message = event.data?.message
|
|
372
|
+
if (!message || String(message.id) !== String(messageId)) continue
|
|
373
|
+
return (message.content ?? [])
|
|
374
|
+
.filter(block => block && block.type === 'text' && typeof block.text === 'string')
|
|
375
|
+
.map(block => block.text)
|
|
376
|
+
.join('\n\n')
|
|
377
|
+
}
|
|
378
|
+
return ''
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export function apply(ctx, config) {
|
|
382
|
+
// 请求期一律现读:设置页的 volatile 改动直接写进运行中的引用。
|
|
383
|
+
const live = () => settings(config)
|
|
384
|
+
logEvent(`applied:${BUILD_TAG}:safety=${live().safetyMode}`)
|
|
385
|
+
|
|
386
|
+
// ── 1. 内容安全:给官方 DeepSeek 请求加顶层 safety_check ─────────────────────
|
|
387
|
+
// 注册常驻,开关交给 prepare 现读 safetyMode,改设置无需重载。
|
|
388
|
+
ctx.inject(['deepseekLlmApiExtensions'], child => {
|
|
389
|
+
child.effect(() => child.deepseekLlmApiExtensions.register('safety_check', {
|
|
390
|
+
prepare(request) {
|
|
391
|
+
const cfg = live()
|
|
392
|
+
const decision = safetyDecision(request, cfg)
|
|
393
|
+
if (cfg.safetyLog) logSafetyObservation(request, decision)
|
|
394
|
+
if (!decision.inject) return undefined
|
|
395
|
+
return { value: { level: cfg.safetyLevel } }
|
|
396
|
+
},
|
|
397
|
+
}), 'dsh-chatbot-tools: safety_check')
|
|
398
|
+
})
|
|
399
|
+
|
|
400
|
+
// ── 1.5 语音输入:把 DeepSeek ASR 注册为官方 speechToText provider ───────────
|
|
401
|
+
// 官方客户端 UI(dsh-experimental-client-ui-voice-input)会列出它并在录音后调用它。
|
|
402
|
+
ctx.inject(['speechToText'], child => {
|
|
403
|
+
child.effect(() => child.speechToText.register(createDeepSeekSpeechProvider({
|
|
404
|
+
config: live,
|
|
405
|
+
auth: endpoint => authHeaders(ctx, live(), endpoint),
|
|
406
|
+
postForm,
|
|
407
|
+
detail: apiDetail,
|
|
408
|
+
})), 'dsh-chatbot-tools: deepseek-asr provider')
|
|
409
|
+
})
|
|
410
|
+
|
|
411
|
+
// ── 2. 拒答兜底:把适配器对 refusal 的抛错转成可读提示 ─────────────────────
|
|
412
|
+
ctx.on('llm/stream', async function* refusalGuard(_options, next) {
|
|
413
|
+
try {
|
|
414
|
+
for await (const chunk of await next()) yield chunk
|
|
415
|
+
} catch (error) {
|
|
416
|
+
if (!isRefusalError(error)) throw error
|
|
417
|
+
const text = '⚠️ 该回答已被 DeepSeek 内容安全策略拦截(refusal)。请换一种问法,或把内容安全设为 off 后重试。'
|
|
418
|
+
yield { type: 'block-start', index: 0, blockType: 'text' }
|
|
419
|
+
yield { type: 'text-delta', index: 0, text }
|
|
420
|
+
yield { type: 'block-end', index: 0, block: { type: 'text', text } }
|
|
421
|
+
yield { type: 'finish', reason: { kind: 'stop' } }
|
|
422
|
+
}
|
|
423
|
+
})
|
|
424
|
+
|
|
425
|
+
// ── 3. 图片搜索工具 ────────────────────────────────────────────────────────
|
|
426
|
+
ctx.effect(() => ctx.tools.register(defineTool({
|
|
427
|
+
name: 'chatbot_image_search',
|
|
428
|
+
description: '按图片搜索相似图片与出处(DeepSeek 服务端图片搜索)。',
|
|
429
|
+
parameters: {
|
|
430
|
+
path: { type: 'string', required: true, description: '本地图片的绝对路径(png/jpg/webp/gif)' },
|
|
431
|
+
query: { type: 'string', description: '可选:补充搜索意图,越具体越好' },
|
|
432
|
+
},
|
|
433
|
+
output: {
|
|
434
|
+
schema: { type: 'string' },
|
|
435
|
+
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
|
436
|
+
},
|
|
437
|
+
async execute(args) {
|
|
438
|
+
const cfg = live()
|
|
439
|
+
const ext = extname(String(args.path)).toLowerCase()
|
|
440
|
+
const mediaType = MEDIA[ext]
|
|
441
|
+
if (!mediaType) throw new Error(`不支持的图片格式:${ext || '(无扩展名)'};支持 png/jpg/jpeg/webp/gif`)
|
|
442
|
+
const bytes = await readFile(args.path)
|
|
443
|
+
if (bytes.length > cfg.maxImageBytes) {
|
|
444
|
+
throw new Error(`图片过大:${bytes.length} 字节,上限 ${cfg.maxImageBytes};请先压缩。`)
|
|
445
|
+
}
|
|
446
|
+
const endpoint = `${cfg.messagesBaseURL}/messages`
|
|
447
|
+
const auth = await authHeaders(ctx, cfg, endpoint)
|
|
448
|
+
const hint = typeof args.query === 'string' && args.query.length > 0
|
|
449
|
+
? `用这张图片做图片搜索。补充意图:${args.query}`
|
|
450
|
+
: '用这张图片做图片搜索,找出相似图片与原始出处。'
|
|
451
|
+
const body = {
|
|
452
|
+
model: cfg.model,
|
|
453
|
+
max_tokens: cfg.maxTokens,
|
|
454
|
+
thinking: { type: 'disabled' },
|
|
455
|
+
tools: [{ type: cfg.serverTool, name: cfg.serverTool, max_uses: cfg.maxUses }],
|
|
456
|
+
messages: [{
|
|
457
|
+
role: 'user',
|
|
458
|
+
content: [
|
|
459
|
+
{ type: 'image', source: { type: 'base64', media_type: mediaType, data: bytes.toString('base64') } },
|
|
460
|
+
{ type: 'text', text: hint },
|
|
461
|
+
],
|
|
462
|
+
}],
|
|
463
|
+
}
|
|
464
|
+
const result = await postJSON(endpoint, { ...auth.headers, 'anthropic-version': cfg.apiVersion }, body)
|
|
465
|
+
if (!result.ok) throw new Error(`图片搜索失败(HTTP ${result.status},凭证 ${auth.kind}):${apiDetail(result)}`)
|
|
466
|
+
const blocks = result.body && Array.isArray(result.body.content) ? result.body.content : []
|
|
467
|
+
return renderImageResults(blocks)
|
|
468
|
+
},
|
|
469
|
+
})), 'dsh-chatbot-tools: chatbot_image_search')
|
|
470
|
+
|
|
471
|
+
// ── 4. 结构化搜索(Search API)────────────────────────────────────────────
|
|
472
|
+
ctx.effect(() => ctx.tools.register(defineTool({
|
|
473
|
+
name: 'chatbot_search',
|
|
474
|
+
description: '联网搜索并返回带站点、发布时间、权威度的结构化来源,便于正文引用。',
|
|
475
|
+
parameters: {
|
|
476
|
+
query: { type: 'string', required: true, description: '搜索词,支持 site:/after:/lang: 等语法' },
|
|
477
|
+
count: { type: 'number', description: '返回条数 1-50,默认取设置里的 searchCount' },
|
|
478
|
+
},
|
|
479
|
+
output: {
|
|
480
|
+
schema: { type: 'string' },
|
|
481
|
+
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
|
482
|
+
},
|
|
483
|
+
async execute(args) {
|
|
484
|
+
const cfg = live()
|
|
485
|
+
const endpoint = `${cfg.apiBaseURL}/v1/tools/search`
|
|
486
|
+
const auth = await authHeaders(ctx, cfg, endpoint)
|
|
487
|
+
const count = Number.isFinite(args.count) ? Math.min(50, Math.max(1, Math.trunc(args.count))) : cfg.searchCount
|
|
488
|
+
const result = await postJSON(endpoint, auth.headers, { query: String(args.query), count, need_content: false })
|
|
489
|
+
if (!result.ok) throw new Error(`搜索失败(HTTP ${result.status},凭证 ${auth.kind}):${apiDetail(result)}`)
|
|
490
|
+
const results = result.body && Array.isArray(result.body.results) ? result.body.results : []
|
|
491
|
+
if (results.length === 0) return '没有搜到结果。换关键词,或用 site:/after: 语法收窄范围后重试。'
|
|
492
|
+
return `共 ${results.length} 条来源(引用时请保留完整 URL):\n${renderSources(results)}`
|
|
493
|
+
},
|
|
494
|
+
})), 'dsh-chatbot-tools: chatbot_search')
|
|
495
|
+
|
|
496
|
+
// ── 5. OCR:文档/图片文字识别 ───────────────────────────────────────────────
|
|
497
|
+
ctx.effect(() => ctx.tools.register(defineTool({
|
|
498
|
+
name: 'chatbot_ocr',
|
|
499
|
+
description: '识别 PDF/Word/PPT/图片中的文字,按页返回(DeepSeek OCR 工具 API)。',
|
|
500
|
+
parameters: {
|
|
501
|
+
path: { type: 'string', required: true, description: '本地文件绝对路径(pdf/docx/pptx/png/jpg 等)' },
|
|
502
|
+
purpose: {
|
|
503
|
+
type: 'string',
|
|
504
|
+
description: 'text_recognition(默认,纯文本优先)或 rich_layout_recognition(逐页版面)',
|
|
505
|
+
},
|
|
506
|
+
},
|
|
507
|
+
output: {
|
|
508
|
+
schema: { type: 'string' },
|
|
509
|
+
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
|
510
|
+
},
|
|
511
|
+
async execute(args) {
|
|
512
|
+
const cfg = live()
|
|
513
|
+
const endpoint = `${cfg.apiBaseURL}/v1/tools/ocr`
|
|
514
|
+
const auth = await authHeaders(ctx, cfg, endpoint)
|
|
515
|
+
const bytes = await readFile(args.path)
|
|
516
|
+
const form = new FormData()
|
|
517
|
+
form.append('file', new Blob([bytes]), path.basename(String(args.path)))
|
|
518
|
+
form.append('purpose', typeof args.purpose === 'string' && args.purpose.length > 0 ? args.purpose : cfg.ocrPurpose)
|
|
519
|
+
const result = await postForm(endpoint, auth.headers, form)
|
|
520
|
+
if (!result.ok) throw new Error(`OCR 失败(HTTP ${result.status},凭证 ${auth.kind}):${apiDetail(result)}`)
|
|
521
|
+
const body = result.body ?? {}
|
|
522
|
+
if (body.error) throw new Error(`OCR 失败:${body.error.message ?? JSON.stringify(body.error)}`)
|
|
523
|
+
const pages = Array.isArray(body.pages) ? body.pages : []
|
|
524
|
+
if (pages.length === 0) return 'OCR 没有返回任何页。'
|
|
525
|
+
const chunks = []
|
|
526
|
+
let total = 0
|
|
527
|
+
for (const page of pages) {
|
|
528
|
+
const text = typeof page.text === 'string' ? page.text.trim() : ''
|
|
529
|
+
if (text.length === 0) continue
|
|
530
|
+
const piece = `--- 第 ${Number(page.index) + 1} 页${page.finish_reason === 'length' ? '(已截断)' : ''} ---\n${text}`
|
|
531
|
+
if (total + piece.length > cfg.ocrMaxChars) {
|
|
532
|
+
chunks.push(piece.slice(0, Math.max(0, cfg.ocrMaxChars - total)))
|
|
533
|
+
chunks.push(`(已到返回上限 ${cfg.ocrMaxChars} 字符,其余 ${pages.length} 页未展开)`)
|
|
534
|
+
break
|
|
535
|
+
}
|
|
536
|
+
chunks.push(piece)
|
|
537
|
+
total += piece.length
|
|
538
|
+
}
|
|
539
|
+
return `OCR 完成:${body.page_count ?? pages.length} 页,用途 ${body.purpose ?? cfg.ocrPurpose}。\n${chunks.join('\n\n')}`
|
|
540
|
+
},
|
|
541
|
+
})), 'dsh-chatbot-tools: chatbot_ocr')
|
|
542
|
+
|
|
543
|
+
// ── 5.5 文件上传:Files API 换取 file_id(对应 Chatbot 的「文件输入」)──────────
|
|
544
|
+
// 与 OCR 的区别:OCR 把文字**取回来**进本地上下文;这里是把文件**交给服务端**解析,
|
|
545
|
+
// 之后由模型按 file_id 直接读(聊天请求里带
|
|
546
|
+
// {"type":"document","source":{"type":"file","file_id":"file-api-..."}})。
|
|
547
|
+
// 官方文档:guides/document_parsing。契约要点:
|
|
548
|
+
// - POST {base}/files,multipart;**purpose 字段必须排在 file 之前**,否则 400
|
|
549
|
+
// - text_recognition / rich_layout_recognition 会解析并**按页计费**(图表另有差别)
|
|
550
|
+
// - user_data 不解析、不计费(纯文本/表格/电子书,原件 ≤32 MiB)
|
|
551
|
+
// - 解析类的上限:单文件 100 MiB / 1000 页 / 上传 120s / 解析 120s / 并发 15
|
|
552
|
+
// - 返回的是 id(形如 file-api-xxxx),原始文件与解析结果都不可下载
|
|
553
|
+
ctx.effect(() => ctx.tools.register(defineTool({
|
|
554
|
+
name: 'chatbot_upload_document',
|
|
555
|
+
description: '把本地文档/图片上传到 DeepSeek Files API,返回可被对话引用的 file_id(可选解析方式)。',
|
|
556
|
+
parameters: {
|
|
557
|
+
path: { type: 'string', required: true, description: '本地文件绝对路径(pdf/docx/pptx/xlsx/txt/md/图片等)' },
|
|
558
|
+
purpose: {
|
|
559
|
+
type: 'string',
|
|
560
|
+
description: 'text_recognition(默认,只要文字)/ rich_layout_recognition(文字+文中图表)/ user_data(不解析、不计费,纯文本表格电子书)',
|
|
561
|
+
},
|
|
562
|
+
},
|
|
563
|
+
output: {
|
|
564
|
+
schema: { type: 'string' },
|
|
565
|
+
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
|
566
|
+
},
|
|
567
|
+
async execute(args) {
|
|
568
|
+
const cfg = live()
|
|
569
|
+
const endpoint = `${cfg.apiBaseURL}/files`
|
|
570
|
+
const auth = await authHeaders(ctx, cfg, endpoint)
|
|
571
|
+
const purpose = typeof args.purpose === 'string' && args.purpose.length > 0 ? args.purpose : cfg.documentPurpose
|
|
572
|
+
const allowed = ['text_recognition', 'rich_layout_recognition', 'user_data']
|
|
573
|
+
if (!allowed.includes(purpose)) {
|
|
574
|
+
throw new Error(`不支持的 purpose:${purpose};只能是 ${allowed.join(' / ')}`)
|
|
575
|
+
}
|
|
576
|
+
const bytes = await readFile(args.path)
|
|
577
|
+
// user_data 的 32 MiB 是「原始文件」限制;解析类按 100 MiB 判定。
|
|
578
|
+
const limit = purpose === 'user_data' ? 32 * 1024 * 1024 : 100 * 1024 * 1024
|
|
579
|
+
if (bytes.length > limit) {
|
|
580
|
+
throw new Error(`文件过大:${bytes.length} 字节,purpose=${purpose} 上限 ${limit} 字节。`)
|
|
581
|
+
}
|
|
582
|
+
const form = new FormData()
|
|
583
|
+
form.append('purpose', purpose) // 顺序有意义:必须在 file 之前
|
|
584
|
+
form.append('file', new Blob([bytes]), path.basename(String(args.path)))
|
|
585
|
+
// 上传 120s + 解析 120s,留余量;默认 180s 可能不够。
|
|
586
|
+
const result = await postForm(endpoint, auth.headers, form, 260000)
|
|
587
|
+
if (!result.ok) {
|
|
588
|
+
throw new Error(`上传失败(HTTP ${result.status},凭证 ${auth.kind}):${apiDetail(result)}${uploadHint(result.status)}`)
|
|
589
|
+
}
|
|
590
|
+
const body = result.body ?? {}
|
|
591
|
+
if (body.error) throw new Error(`上传失败:${body.error.message ?? JSON.stringify(body.error)}`)
|
|
592
|
+
const fileId = typeof body.id === 'string' ? body.id : ''
|
|
593
|
+
if (fileId.length === 0) throw new Error(`上传响应里没有 id:${JSON.stringify(body).slice(0, 300)}`)
|
|
594
|
+
return [
|
|
595
|
+
`上传完成:${fileId}`,
|
|
596
|
+
`文件名:${body.filename ?? path.basename(String(args.path))};用途:${body.purpose ?? purpose};大小:${body.bytes ?? bytes.length} 字节`,
|
|
597
|
+
purpose === 'user_data'
|
|
598
|
+
? '(未解析、未计费;内容在对话引用时由服务端转换后进入上下文。)'
|
|
599
|
+
: '(已按页计费解析完成;文中图表仅在 rich_layout_recognition 下可见。)',
|
|
600
|
+
`引用方式:{"type":"document","source":{"type":"file","file_id":"${fileId}"}};Messages 协议还需请求头 anthropic-beta: files-api-2025-04-14。`,
|
|
601
|
+
].join('\n')
|
|
602
|
+
},
|
|
603
|
+
})), 'dsh-chatbot-tools: chatbot_upload_document')
|
|
604
|
+
|
|
605
|
+
// ── 6. ASR:音频转文字 ────────────────────────────────────────────────────
|
|
606
|
+
ctx.effect(() => ctx.tools.register(defineTool({
|
|
607
|
+
name: 'chatbot_asr',
|
|
608
|
+
description: '把本地音频转写为文字(16-bit PCM WAV 或 Ogg Opus,≤120 秒,≤8 MiB)。',
|
|
609
|
+
parameters: {
|
|
610
|
+
path: { type: 'string', required: true, description: '本地音频绝对路径(wav / ogg)' },
|
|
611
|
+
},
|
|
612
|
+
output: {
|
|
613
|
+
schema: { type: 'string' },
|
|
614
|
+
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
|
615
|
+
},
|
|
616
|
+
async execute(args) {
|
|
617
|
+
const cfg = live()
|
|
618
|
+
const endpoint = `${cfg.apiBaseURL}/v1/tools/asr`
|
|
619
|
+
const auth = await authHeaders(ctx, cfg, endpoint)
|
|
620
|
+
const bytes = await readFile(args.path)
|
|
621
|
+
if (bytes.length > 8 * 1024 * 1024) throw new Error(`音频过大:${bytes.length} 字节,上限 8 MiB。`)
|
|
622
|
+
const form = new FormData()
|
|
623
|
+
form.append('file', new Blob([bytes]), path.basename(String(args.path)))
|
|
624
|
+
const result = await postForm(endpoint, auth.headers, form)
|
|
625
|
+
if (!result.ok) throw new Error(`ASR 失败(HTTP ${result.status},凭证 ${auth.kind}):${apiDetail(result)}${authHint(result, auth)}`)
|
|
626
|
+
const text = typeof result.body?.text === 'string' ? result.body.text : ''
|
|
627
|
+
const ms = Number.isFinite(result.body?.duration_ms) ? result.body.duration_ms : undefined
|
|
628
|
+
if (text.length === 0) return `没有识别出文字${ms !== undefined ? `(音频 ${ms} ms)` : ''}。`
|
|
629
|
+
return `转写结果${ms !== undefined ? `(音频 ${ms} ms)` : ''}:\n${text}`
|
|
630
|
+
},
|
|
631
|
+
})), 'dsh-chatbot-tools: chatbot_asr')
|
|
632
|
+
|
|
633
|
+
// ── 7. TTS:文字转语音,落盘返回路径 ───────────────────────────────────────
|
|
634
|
+
ctx.effect(() => ctx.tools.register(defineTool({
|
|
635
|
+
name: 'chatbot_tts',
|
|
636
|
+
description: '把文本合成为语音文件并返回落盘路径(DeepSeek TTS 工具 API)。',
|
|
637
|
+
parameters: {
|
|
638
|
+
text: { type: 'string', required: true, description: '要朗读的文本,最多 10000 个计费字符' },
|
|
639
|
+
voice: { type: 'string', description: 'stella(女声,默认)或 tide(男声)' },
|
|
640
|
+
format: { type: 'string', description: 'wav(默认)或 pcm' },
|
|
641
|
+
},
|
|
642
|
+
output: {
|
|
643
|
+
schema: { type: 'string' },
|
|
644
|
+
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
|
645
|
+
},
|
|
646
|
+
async execute(args) {
|
|
647
|
+
const cfg = live()
|
|
648
|
+
// 本地把 Markdown 转成可朗读文本:行内代码必须保留(服务端会剥掉),代码块按 ttsCodeMode 处理。
|
|
649
|
+
const spoken = applyTerms(
|
|
650
|
+
toSpeakable(String(args.text ?? ''), { codeMode: cfg.ttsCodeMode }),
|
|
651
|
+
parseTermMap(cfg.ttsTermMap),
|
|
652
|
+
).slice(0, cfg.ttsMaxChars)
|
|
653
|
+
if (spoken.trim().length === 0) throw new Error('没有可朗读的文本。')
|
|
654
|
+
const voice = typeof args.voice === 'string' && args.voice.length > 0 ? args.voice : cfg.ttsVoice
|
|
655
|
+
const format = typeof args.format === 'string' && args.format.length > 0 ? args.format : cfg.ttsFormat
|
|
656
|
+
const endpoint = `${cfg.apiBaseURL}/v1/tools/tts`
|
|
657
|
+
const auth = await authHeaders(ctx, cfg, endpoint)
|
|
658
|
+
const result = await send(endpoint, {
|
|
659
|
+
method: 'POST',
|
|
660
|
+
headers: { 'content-type': 'application/json', ...auth.headers },
|
|
661
|
+
body: JSON.stringify({ text: spoken, voice_id: voice, format, filter_markdown: cfg.ttsFilterMarkdown }),
|
|
662
|
+
}, 120000)
|
|
663
|
+
if (!result.ok) throw new Error(`TTS 失败(HTTP ${result.status},凭证 ${auth.kind}):${apiDetail(result)}${authHint(result, auth)}`)
|
|
664
|
+
if (result.buffer.length === 0) throw new Error('TTS 返回了空音频。')
|
|
665
|
+
const dir = cfg.ttsOutDir && cfg.ttsOutDir.length > 0
|
|
666
|
+
? cfg.ttsOutDir
|
|
667
|
+
: path.join(os.homedir(), '.dsh', 'chatbot-tools', 'out')
|
|
668
|
+
mkdirSync(dir, { recursive: true })
|
|
669
|
+
const file = path.join(dir, `tts-${Date.now()}.${format === 'pcm' ? 'pcm' : 'wav'}`)
|
|
670
|
+
await writeFile(file, result.buffer)
|
|
671
|
+
return `已生成语音:${file}(${voice},${format},${result.buffer.length} 字节,朗读 ${spoken.length} 字符)`
|
|
672
|
+
},
|
|
673
|
+
})), 'dsh-chatbot-tools: chatbot_tts')
|
|
674
|
+
|
|
675
|
+
// ── 7.5 TTS 界面路由:客户端朗读按钮只发 sessionId + messageId ─────────────
|
|
676
|
+
ctx.inject(['webServer'], child => {
|
|
677
|
+
child.effect(() => child.webServer.register({
|
|
678
|
+
path: '/chatbot-voice/tts',
|
|
679
|
+
kind: 'exact',
|
|
680
|
+
resource: async request => {
|
|
681
|
+
const startedAt = Date.now()
|
|
682
|
+
try {
|
|
683
|
+
const url = new URL(request.url, 'http://local')
|
|
684
|
+
const text = messageText(
|
|
685
|
+
ctx,
|
|
686
|
+
url.searchParams.get('sessionId') ?? '',
|
|
687
|
+
url.searchParams.get('messageId') ?? '',
|
|
688
|
+
)
|
|
689
|
+
if (text.trim().length === 0) return new Response('未找到该消息的正文', { status: 404 })
|
|
690
|
+
const cfg = live()
|
|
691
|
+
const spoken = applyTerms(
|
|
692
|
+
toSpeakable(text, { codeMode: cfg.ttsCodeMode }),
|
|
693
|
+
parseTermMap(cfg.ttsTermMap),
|
|
694
|
+
).slice(0, cfg.ttsMaxChars)
|
|
695
|
+
const endpoint = `${cfg.apiBaseURL}/v1/tools/tts`
|
|
696
|
+
const auth = await authHeaders(ctx, cfg, endpoint)
|
|
697
|
+
const result = await send(endpoint, {
|
|
698
|
+
method: 'POST',
|
|
699
|
+
headers: { 'content-type': 'application/json', ...auth.headers },
|
|
700
|
+
body: JSON.stringify({
|
|
701
|
+
text: spoken,
|
|
702
|
+
voice_id: cfg.ttsVoice,
|
|
703
|
+
format: cfg.ttsFormat,
|
|
704
|
+
filter_markdown: cfg.ttsFilterMarkdown,
|
|
705
|
+
}),
|
|
706
|
+
}, 120000)
|
|
707
|
+
if (!result.ok) {
|
|
708
|
+
logEvent(`tts-failed:http=${result.status}`)
|
|
709
|
+
return new Response(`TTS 失败:${apiDetail(result)}${authHint(result, auth)}`, { status: 502 })
|
|
710
|
+
}
|
|
711
|
+
// 审计:谁点了朗读、合成了多少字符、多大音频、耗时多久。
|
|
712
|
+
logEvent(`tts-ok:chars=${spoken.length}:bytes=${result.buffer.length}:ms=${Date.now() - startedAt}`)
|
|
713
|
+
return new Response(result.buffer, {
|
|
714
|
+
headers: {
|
|
715
|
+
'content-type': cfg.ttsFormat === 'pcm' ? 'audio/pcm' : 'audio/wav',
|
|
716
|
+
'cache-control': 'no-store',
|
|
717
|
+
},
|
|
718
|
+
})
|
|
719
|
+
} catch (error) {
|
|
720
|
+
return new Response(String(error && error.message ? error.message : error), { status: 500 })
|
|
721
|
+
}
|
|
722
|
+
},
|
|
723
|
+
}), 'dsh-chatbot-tools: /chatbot-voice/tts')
|
|
724
|
+
})
|
|
725
|
+
|
|
726
|
+
// ── 8. 自检:凭证通道 + safety_check 兼容性 ────────────────────────────────
|
|
727
|
+
ctx.effect(() => ctx.tools.register(defineTool({
|
|
728
|
+
name: 'chatbot_doctor',
|
|
729
|
+
description: '自检插件:报告凭证通道,并验证 safety_check 与普通工具能否共存。',
|
|
730
|
+
parameters: {
|
|
731
|
+
live: { type: 'boolean', description: '为 true 时发起真实请求(会产生少量费用)' },
|
|
732
|
+
},
|
|
733
|
+
output: {
|
|
734
|
+
schema: { type: 'string' },
|
|
735
|
+
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
|
736
|
+
},
|
|
737
|
+
async execute(args) {
|
|
738
|
+
const cfg = live()
|
|
739
|
+
const lines = [
|
|
740
|
+
`- 构建:${BUILD_TAG}`,
|
|
741
|
+
`- 设置:safetyMode=${cfg.safetyMode} level=${cfg.safetyLevel} guard=${cfg.safetyGuardDeferLoading} model=${cfg.model}`,
|
|
742
|
+
]
|
|
743
|
+
const initiator = ctx.get('agents')?.currentInitiator?.()
|
|
744
|
+
const requestContext = initiator?.session?.requestContext?.()
|
|
745
|
+
lines.push(`- 会话 provider:${requestContext?.provider ?? '(未知)'};model:${requestContext?.model ?? '(未知)'}`)
|
|
746
|
+
const stt = ctx.get('speechToText')
|
|
747
|
+
lines.push(`- 语音输入提供方:${stt ? (stt.listProviders().map(p => p.id).join(', ') || '(无)') : '(speechToText 未挂载)'}`)
|
|
748
|
+
const endpoint = `${cfg.messagesBaseURL}/messages`
|
|
749
|
+
let auth
|
|
750
|
+
try {
|
|
751
|
+
auth = await authHeaders(ctx, cfg, endpoint)
|
|
752
|
+
lines.push(`- 凭证通道:${auth.kind}${auth.source ? "/" + auth.source : ""}`)
|
|
753
|
+
} catch (error) {
|
|
754
|
+
lines.push(`- 凭证通道:不可用(${String(error && error.message ? error.message : error)})`)
|
|
755
|
+
return lines.join('\n')
|
|
756
|
+
}
|
|
757
|
+
if (!args.live) {
|
|
758
|
+
lines.push('- safety_check 探测:跳过(live=false)')
|
|
759
|
+
return lines.join('\n')
|
|
760
|
+
}
|
|
761
|
+
const makeBody = thinkingType => ({
|
|
762
|
+
model: cfg.model,
|
|
763
|
+
max_tokens: 16,
|
|
764
|
+
thinking: { type: thinkingType },
|
|
765
|
+
safety_check: { level: cfg.safetyLevel },
|
|
766
|
+
tools: [{ name: 'dsh_ping', description: 'ping', input_schema: { type: 'object', properties: {} } }],
|
|
767
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: '回答一个字:好' }] }],
|
|
768
|
+
})
|
|
769
|
+
// 两种思考模式各打一次:服务端对「client tools + safety_check」的要求随思考模式而变。
|
|
770
|
+
for (const thinkingType of ['enabled', 'disabled']) {
|
|
771
|
+
try {
|
|
772
|
+
const result = await postJSON(
|
|
773
|
+
endpoint,
|
|
774
|
+
{ ...auth.headers, 'anthropic-version': cfg.apiVersion },
|
|
775
|
+
makeBody(thinkingType),
|
|
776
|
+
)
|
|
777
|
+
lines.push(
|
|
778
|
+
`- thinking=${thinkingType} + safety_check + function tool:HTTP ${result.status}`
|
|
779
|
+
+ (result.ok ? '(接受)' : `(拒绝:${apiDetail(result)})`),
|
|
780
|
+
)
|
|
781
|
+
} catch (error) {
|
|
782
|
+
lines.push(`- thinking=${thinkingType} 探测失败:${String(error && error.message ? error.message : error)}`)
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
return lines.join('\n')
|
|
786
|
+
},
|
|
787
|
+
})), 'dsh-chatbot-tools: chatbot_doctor')
|
|
788
|
+
}
|