dsh-team-bots 0.3.98 → 0.3.105
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/package.json +1 -1
- package/src/db-migrations.js +5 -1
- package/src/feishu/channel.js +15 -11
- package/src/feishu/format.js +37 -1
- package/src/services/core.js +3 -2
- package/src/services/questions.js +35 -11
- package/src/services/run-finish.js +4 -1
- package/src/services/runtime/session.js +6 -3
- package/src/services/vision-proxy.js +58 -3
- package/src/services/wechat.js +23 -7
- package/src/util.js +17 -0
- package/src/wechat/channel.js +3 -1
- package/src/wechat/commands.js +13 -1
- package/ui/modules/events-click.js +14 -1
- package/ui/modules/file-preview.js +22 -10
- package/ui/modules/markdown.js +10 -8
- package/ui/styles/modal.css +4 -0
package/package.json
CHANGED
package/src/db-migrations.js
CHANGED
|
@@ -40,7 +40,8 @@ export const RUNS_DDL = `
|
|
|
40
40
|
usage_output INTEGER NOT NULL DEFAULT 0,
|
|
41
41
|
usage_cost REAL,
|
|
42
42
|
cancel_requested INTEGER NOT NULL DEFAULT 0,
|
|
43
|
-
merged_messages TEXT
|
|
43
|
+
merged_messages TEXT,
|
|
44
|
+
image_offload INTEGER NOT NULL DEFAULT 0
|
|
44
45
|
`
|
|
45
46
|
|
|
46
47
|
export const RUNS_INDEXES = `
|
|
@@ -209,6 +210,9 @@ function migrateRuns(db) {
|
|
|
209
210
|
addColumn(db, 'runs', 'model_effort', 'TEXT')
|
|
210
211
|
// 入站消息合批(DSHBOTS-231):领取时同通道排队消息被合并进来,存被合并消息的 id 列表(JSON)。
|
|
211
212
|
addColumn(db, 'runs', 'merged_messages', 'TEXT')
|
|
213
|
+
// 续答运行(DSHBOTS-112 闭环):转写写回后同消息再排一次 chat/solo_chat,
|
|
214
|
+
// 不下发二进制图(首轮已因主模型无视觉失败),转写正文由提示词近期窗口带入。
|
|
215
|
+
addColumn(db, 'runs', 'image_offload', "INTEGER NOT NULL DEFAULT 0")
|
|
212
216
|
db.exec(`UPDATE runs SET mode = 'read' WHERE kind IN ('chat', 'review', 'handle') AND mode = 'write'`)
|
|
213
217
|
}
|
|
214
218
|
|
package/src/feishu/channel.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { outboundChunks, failureText, welcomeAdmin } from './format.js'
|
|
2
2
|
import { handleCommand, NON_OWNER_NOTICE } from './commands.js'
|
|
3
|
+
import { stripCarriageReturns } from '../util.js'
|
|
3
4
|
|
|
4
5
|
/** 出站最大尝试次数(含首次):达到上限废弃,永不补发(与微信通道同治理口径)。 */
|
|
5
6
|
const OUTBOX_MAX_ATTEMPTS = 3
|
|
@@ -131,17 +132,19 @@ function sdkLogger(log , secret ) {
|
|
|
131
132
|
}
|
|
132
133
|
}
|
|
133
134
|
|
|
134
|
-
/**
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
135
|
+
/**
|
|
136
|
+
* 出站载荷:一律走交互卡片的富文本(markdown)组件,卡片用 JSON 2.0 结构。
|
|
137
|
+
* 2.0 才支持标题、引用、表格等标准 markdown——1.0 里 "# 标题" 会原样显示成井号文本,
|
|
138
|
+
* 表格也是一串竖线。width_mode=fill 等同 1.0 的 wide_screen_mode(撑满聊天窗口)。
|
|
139
|
+
* 客户端需 7.20 及以上(更低版本会显示升级提示兜底文案)。
|
|
140
|
+
*/
|
|
141
|
+
export function outboundPayload(text) {
|
|
142
|
+
const card = {
|
|
143
|
+
schema: '2.0',
|
|
144
|
+
config: { width_mode: 'fill' },
|
|
145
|
+
body: { elements: [{ tag: 'markdown', content: String(text ?? '') }] },
|
|
143
146
|
}
|
|
144
|
-
return { msgType: '
|
|
147
|
+
return { msgType: 'interactive', content: JSON.stringify(card) }
|
|
145
148
|
}
|
|
146
149
|
|
|
147
150
|
/** SDK 抛出的错误归一:尽量取出飞书业务错误码(axios 响应体 code / 错误文案里的 code),
|
|
@@ -395,7 +398,8 @@ export class FeishuChannel {
|
|
|
395
398
|
async sendFeishu(messageId, text, idempotencyKey) {
|
|
396
399
|
if (!messageId) throw new Error('缺少飞书回复目标消息 id')
|
|
397
400
|
if (!idempotencyKey) throw new Error('缺少幂等键(应为 outbox 行 id)')
|
|
398
|
-
|
|
401
|
+
// 出站边界去 CR:模型文本偶发带 CR,飞书按行尾渲染会把一句话劈成多段。
|
|
402
|
+
const chunks = outboundChunks(stripCarriageReturns(text))
|
|
399
403
|
for (let index = 0; index < chunks.length; index++) {
|
|
400
404
|
const key = index > 0 ? `${idempotencyKey}#${index}` : idempotencyKey
|
|
401
405
|
for (let attempt = 1; ; attempt++) {
|
package/src/feishu/format.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// src/feishu/format.ts —— 飞书出站消息排版层(markdown 文本,DSHBOTS-323 卡①)
|
|
2
2
|
// 角色对齐 src/wechat/format.ts:通道全部回程/回执文案在此集中格式化。
|
|
3
|
-
// 飞书原生支持 markdown
|
|
3
|
+
// 飞书原生支持 markdown:出站一律走交互卡片的富文本(markdown)组件——卡片里单个 \n 即换行,
|
|
4
|
+
// 纯文本消息的 \n 是段落间距(版面松);加粗、列表、分割线也都原生渲染。
|
|
4
5
|
// 不做微信式的 markdown 噪点过滤,只负责长文分块(飞书单条文本有长度上限)与固定文案。
|
|
5
6
|
|
|
6
7
|
/** markdown 分隔线:区分消息头与正文。 */
|
|
@@ -45,6 +46,41 @@ export function outboundChunks(text, maxChars = CHUNK_MAX_CHARS) {
|
|
|
45
46
|
return chunks
|
|
46
47
|
}
|
|
47
48
|
|
|
49
|
+
/**
|
|
50
|
+
* 提问卡片(markdown):题头加粗、选项列表化。
|
|
51
|
+
* 信息口径与微信纯文本镜像一致,但排版按 markdown 给——飞书直接渲染,不必再降成纯文本。
|
|
52
|
+
*/
|
|
53
|
+
export function questionCard(projectName, botName, items, token) {
|
|
54
|
+
const lines = [`**【提问】${botName}(${projectName})**`]
|
|
55
|
+
for (const [index, item] of (items ?? []).entries()) {
|
|
56
|
+
// 题块之间空行分段:markdown 里列表/段落靠空行断开,否则下一题会被吞进上一题的列表。
|
|
57
|
+
lines.push('')
|
|
58
|
+
lines.push(`**Q${index + 1}: ${item.question}**`)
|
|
59
|
+
if (item.detail) lines.push(item.detail)
|
|
60
|
+
for (const [optionIndex, option] of (item.options ?? []).entries()) {
|
|
61
|
+
const description = option.description ? ` — ${option.description}` : ''
|
|
62
|
+
// 用「1:」不用「- 1.」:markdown 列表标记会被飞书重新编号(整卡编成 a./b./c.…),
|
|
63
|
+
// 「1:」既不是列表标记,又和回复格式「1:选项一」同口径。
|
|
64
|
+
lines.push(`${optionIndex + 1}: ${option.label}${description}`)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
lines.push('')
|
|
68
|
+
lines.push(`回复「答 ${token} 选项号或文字」`)
|
|
69
|
+
if ((items ?? []).length > 1) lines.push(`多个问题用「;」分隔,如:答 ${token} 1:选项一;2:补充说明`)
|
|
70
|
+
return lines.join('\n')
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 审批卡片(markdown):与提问卡同版式。 */
|
|
74
|
+
export function approvalCard(projectName, botName, toolName, reason, token) {
|
|
75
|
+
return [
|
|
76
|
+
`**【审批】${botName}(${projectName})**`,
|
|
77
|
+
`工具:${toolName}`,
|
|
78
|
+
`原因:${reason}`,
|
|
79
|
+
'',
|
|
80
|
+
`回复「批 ${token} 允许」或「批 ${token} 拒绝」`,
|
|
81
|
+
].join('\n')
|
|
82
|
+
}
|
|
83
|
+
|
|
48
84
|
/** 管理员绑定欢迎(入站另卡接线时使用)。 */
|
|
49
85
|
export function welcomeAdmin() {
|
|
50
86
|
return '已绑定为本团队管理员\n发送 /? 查看指令'
|
package/src/services/core.js
CHANGED
|
@@ -458,7 +458,7 @@ export const coreMethods = {
|
|
|
458
458
|
* 幂等——两套 outbox 是彼此独立的库与唯一索引,键空间互不干扰。
|
|
459
459
|
* 返回逐通道结果 [{channel, ok, error}],供调用方判断是否至少推成功一路。
|
|
460
460
|
*/
|
|
461
|
-
channelNotify(text, opts
|
|
461
|
+
channelNotify(text, opts = {}) {
|
|
462
462
|
const targets = [
|
|
463
463
|
{ name: 'wechat', channel: this.wechat },
|
|
464
464
|
{ name: 'feishu', channel: this.feishu },
|
|
@@ -467,7 +467,8 @@ export const coreMethods = {
|
|
|
467
467
|
for (const { name, channel } of targets) {
|
|
468
468
|
if (!channel || typeof channel.notify !== 'function') continue
|
|
469
469
|
try {
|
|
470
|
-
|
|
470
|
+
// opts.texts 给逐通道正文(飞书 markdown 卡片 / 微信纯文本镜像),缺省共用同一正文。
|
|
471
|
+
channel.notify(opts.texts?.[name] ?? text, opts)
|
|
471
472
|
results.push({ channel: name, ok: true, error: null })
|
|
472
473
|
} catch (error ) {
|
|
473
474
|
this.logger.warn?.('dsh-team: %s 通道推送失败(其他通道不受影响): %s', name, error?.message ?? error)
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// questionTimeoutMs 窗口,窗口内迟到作答经宿主 userQuestions.answer 回投原 agent;其余 abort 立即失效。
|
|
7
7
|
// 注意:本域自管迁移(db.js 已贴 800 行上限,一行不加),手法与 approvals.js 一致。
|
|
8
8
|
import { badRequest, conflict, forbidden, notFound } from '../errors.js'
|
|
9
|
-
import { id, jsonParse, nowIso, text as textValue } from '../util.js'
|
|
9
|
+
import { flattenWhitespace, id, jsonParse, nowIso, text as textValue } from '../util.js'
|
|
10
10
|
import { effectiveQuestionTimeoutMs } from '../config.js'
|
|
11
11
|
import { columnNotNull, rebuildTable } from '../db-migrations.js'
|
|
12
12
|
|
|
@@ -62,28 +62,50 @@ export function ensureQuestionSchema(store) {
|
|
|
62
62
|
|
|
63
63
|
// 问题条目清洗:文案统一过密钥掩码(会进群聊与 bot 可见范围),并夹取长度防单条撑爆卡片。
|
|
64
64
|
// intent 只保留 plan-review 的展示字段;未知 intent 一律按通用选项列表渲染(协议允许)。
|
|
65
|
-
|
|
65
|
+
// 文案再过一道单行化:模型工具入参偶发把空格写成 CR(U+000D),渲染器把 CR 当行尾,
|
|
66
|
+
// 一句话会被劈成多段(飞书卡片里「(推荐)」裂成两行)。此处折成单行,落库即干净。
|
|
67
|
+
export function cleanQuestionItem(item) {
|
|
66
68
|
const cleaned = {
|
|
67
69
|
id: String(item?.id ?? '').slice(0, 100),
|
|
68
|
-
question: textValue(item?.question, 4_000),
|
|
70
|
+
question: textValue(flattenWhitespace(item?.question), 4_000),
|
|
69
71
|
}
|
|
70
|
-
if (item?.detail) cleaned.detail = textValue(item.detail, 20_000)
|
|
71
|
-
if (item?.header) cleaned.header = textValue(item.header, 200)
|
|
72
|
+
if (item?.detail) cleaned.detail = textValue(flattenWhitespace(item.detail), 20_000)
|
|
73
|
+
if (item?.header) cleaned.header = textValue(flattenWhitespace(item.header), 200)
|
|
72
74
|
if (Array.isArray(item?.options)) {
|
|
73
75
|
cleaned.options = item.options.slice(0, 20).map(option => {
|
|
74
|
-
const row = { label: textValue(option?.label, 200) }
|
|
75
|
-
if (option?.description) row.description = textValue(option.description, 1_000)
|
|
76
|
+
const row = { label: textValue(flattenWhitespace(option?.label), 200) }
|
|
77
|
+
if (option?.description) row.description = textValue(flattenWhitespace(option.description), 1_000)
|
|
76
78
|
return row
|
|
77
79
|
})
|
|
78
80
|
}
|
|
79
81
|
if (item?.multiSelect === true) cleaned.multiSelect = true
|
|
80
82
|
if (item?.intent?.kind === 'plan-review') {
|
|
81
|
-
|
|
83
|
+
// approve 标签必须与选项 label 同一口径(宿主按「approve ∈ options」校验 intent)。
|
|
84
|
+
cleaned.intent = { kind: 'plan-review', approve: textValue(flattenWhitespace(item.intent.approve), 200) }
|
|
82
85
|
if (item.intent.callId) cleaned.intent.callId = String(item.intent.callId)
|
|
83
86
|
}
|
|
84
87
|
return cleaned
|
|
85
88
|
}
|
|
86
89
|
|
|
90
|
+
// 答案条目清洗:selected 是选项 label(与 cleanQuestionItem 同口径,保证前端高亮匹配),
|
|
91
|
+
// custom 是自由文本——同样折成单行,答复回宿主时不再带坏版面。
|
|
92
|
+
export function cleanAnswerItem(answer) {
|
|
93
|
+
const cleaned = { id: String(answer?.id ?? '') }
|
|
94
|
+
cleaned.selected = (Array.isArray(answer?.selected) ? answer.selected : [])
|
|
95
|
+
.map(value => flattenWhitespace(value))
|
|
96
|
+
.filter(Boolean)
|
|
97
|
+
.slice(0, 20)
|
|
98
|
+
const custom = answer?.custom ? flattenWhitespace(answer.custom) : ''
|
|
99
|
+
if (custom) cleaned.custom = custom
|
|
100
|
+
return cleaned
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// 答复批次清洗:{answers:[...]} 结构逐条过 cleanAnswerItem;非批次结构原样返回。
|
|
104
|
+
export function cleanAnswerPayload(answer) {
|
|
105
|
+
if (!answer || !Array.isArray(answer.answers)) return answer
|
|
106
|
+
return { ...answer, answers: answer.answers.map(cleanAnswerItem) }
|
|
107
|
+
}
|
|
108
|
+
|
|
87
109
|
// DSHBOTS-294:该 bot 是否仍有活跃项目语境(成员或总监)。无语境的控制面会话按单聊承接。
|
|
88
110
|
export function botInActiveProject(store, botId) {
|
|
89
111
|
if (!botId) return false
|
|
@@ -308,7 +330,7 @@ export const questionsMethods = {
|
|
|
308
330
|
const selected = (Array.isArray(answer?.selected) ? answer.selected : [])
|
|
309
331
|
.map(value => String(value)).filter(Boolean).slice(0, 20)
|
|
310
332
|
const custom = answer?.custom ? String(answer.custom).slice(0, 2_000) : undefined
|
|
311
|
-
return { id: String(item.id), selected,
|
|
333
|
+
return cleanAnswerItem({ id: String(item.id), selected, custom })
|
|
312
334
|
})
|
|
313
335
|
const decidedBy = `${actor.type}:${actor.id}`
|
|
314
336
|
const hostAnswer = { answers }
|
|
@@ -327,8 +349,10 @@ export const questionsMethods = {
|
|
|
327
349
|
// 视图缺该字段时,提交作答后的服务端终态覆盖乐观对象即丢键,下一轮旧 pending
|
|
328
350
|
// 轮询快照会把「已回答」卡闪回问题卡;提问卡 pill 的作答时间戳也读它。
|
|
329
351
|
...(row.status === 'answered' ? { answered_at: row.ended_at } : {}),
|
|
330
|
-
|
|
331
|
-
|
|
352
|
+
// 存量行可能带 CR 坏空白(模型工具入参污染,落库前的老数据):读出时再洗一遍,
|
|
353
|
+
// 历史提问卡与答复展示同步恢复单行版面;洗后 label 与 selected 仍是同一口径。
|
|
354
|
+
questions: jsonParse(row.questions, []).map(cleanQuestionItem),
|
|
355
|
+
answer: cleanAnswerPayload(jsonParse(row.answer, null)),
|
|
332
356
|
botName: bot?.name ?? 'Bot',
|
|
333
357
|
// 会话归属(DSHBOTS-218):单聊提问没有项目,UI 据此显示来源列并决定跳转目标。
|
|
334
358
|
scope: row.project_id ? 'project' : 'solo',
|
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
transientBackoffMs,
|
|
20
20
|
} from './backoff.js'
|
|
21
21
|
import { ensureAttentionSchema, normalizeAttention } from './attention-schema.js'
|
|
22
|
-
import { completeVisionRun, maybeSpawnVisionAfterFailure } from './vision-proxy.js'
|
|
22
|
+
import { completeVisionRun, isImageUnsupportedError, maybeSpawnVisionAfterFailure } from './vision-proxy.js'
|
|
23
23
|
import { chatReply } from '../wechat/format.js'
|
|
24
24
|
|
|
25
25
|
// ── 失败终态白名单分类(DSHBOTS-267)──────────────────────────────────────
|
|
@@ -42,6 +42,8 @@ const FAILURE_CATEGORY_NOTICES = {
|
|
|
42
42
|
stalled: { label: '停滞', summary: '运行长时间无进展,已被看门狗中止。' },
|
|
43
43
|
network: { label: '网络', summary: '网络瞬态失败,已按退避策略自动重试。' },
|
|
44
44
|
blocked: { label: '会话受阻', summary: '宿主拒绝执行该会话(可能已被归档),未产生任何模型输出。' },
|
|
45
|
+
// DSHBOTS-112:主模型无视觉导致带图消息失败,与「未知」区分——读图代理已接手转写。
|
|
46
|
+
no_vision: { label: '模型无视觉', summary: '主模型不支持图片输入,已转交读图代理转写。' },
|
|
45
47
|
internal: { label: '内部错误', summary: '服务内部错误。' },
|
|
46
48
|
unknown: { label: '未知', summary: '运行失败,完整原因见运行日志。' },
|
|
47
49
|
}
|
|
@@ -49,6 +51,7 @@ export function classifyFailure(error) {
|
|
|
49
51
|
const raw = `${String(error?.code ?? '')} ${String(error?.message ?? '')}`
|
|
50
52
|
if (isQuotaExhausted(error)) return FAILURE_CATEGORY_NOTICES.quota
|
|
51
53
|
if (isRateLimitError(error)) return FAILURE_CATEGORY_NOTICES.rate_limited
|
|
54
|
+
if (isImageUnsupportedError(error)) return FAILURE_CATEGORY_NOTICES.no_vision
|
|
52
55
|
if (SANDBOX_DENIED_PATTERN.test(raw)) return FAILURE_CATEGORY_NOTICES.sandbox_denied
|
|
53
56
|
if (error?.code === 'RUN_TIMEOUT') return FAILURE_CATEGORY_NOTICES.run_timeout
|
|
54
57
|
if (error?.code === 'RUN_STALLED') return FAILURE_CATEGORY_NOTICES.stalled
|
|
@@ -820,7 +820,7 @@ export const sessionMethods = {
|
|
|
820
820
|
this.sessionCreates.delete(key)
|
|
821
821
|
}
|
|
822
822
|
},
|
|
823
|
-
async startRun({ run, bot, project, task, chatMessage, extraMessages, sessionKind }
|
|
823
|
+
async startRun({ run, bot, project, task, chatMessage, extraMessages, sessionKind } ) {
|
|
824
824
|
if (!this.ctx?.sessionController) throw new AppError('DSH_UNAVAILABLE', 'DSH Session 服务不可用')
|
|
825
825
|
// 备用模型覆盖:派生运行在 runs 行里带 model_* 三列,指明这条运行改用备用模型下发。
|
|
826
826
|
// 不带 override 的运行照旧走 Bot 主模型——「运行结束自动回退」就靠这条默认路径实现。
|
|
@@ -888,9 +888,12 @@ export const sessionMethods = {
|
|
|
888
888
|
)
|
|
889
889
|
try {
|
|
890
890
|
// 聊天附图:首条 prompt 一并带上 image 分片,模型这轮就能看到用户发的图。
|
|
891
|
-
//
|
|
891
|
+
// 宿主对吃不了图片的模型直接抛 attachment-invalid(不降级),所以续答运行
|
|
892
|
+
// (image_offload=1)跳过附图,转写正文已由提示词近期窗口带入。
|
|
892
893
|
// 附图随消息住在聊天库里(chat-db-split Phase 1)。
|
|
893
|
-
const imageParts = chatMessage?.id
|
|
894
|
+
const imageParts = chatMessage?.id && !run.image_offload
|
|
895
|
+
? imageContentPartsForMessage(pending.chatStore ?? this.store, chatMessage.id)
|
|
896
|
+
: []
|
|
894
897
|
await this.ctx.sessionController.prompt({
|
|
895
898
|
requestId: randomUUID(),
|
|
896
899
|
sessionId,
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// src/services/vision-proxy.js —— 读图代理域(DSHBOTS-112)
|
|
2
2
|
// Bot 主模型无视觉能力却收到带图消息时,自动派生 kind='vision'、mode='read' 的
|
|
3
3
|
// 只读转写运行:用配置的代理模型(visionProxyProvider/visionProxyModel)把图片
|
|
4
|
-
// 转写成中文结构化文本,以「[图片转写] …」system
|
|
5
|
-
//
|
|
4
|
+
// 转写成中文结构化文本,以「[图片转写] …」system 消息写回原消息所在会话,并给同
|
|
5
|
+
// 一条消息派生续答运行(image_offload=1,不再下发二进制图),主模型当轮即可基于
|
|
6
|
+
// 转写正文回答用户。原对话不受派生阻塞:原 chat 运行照常带图下发,
|
|
6
7
|
// 宿主仍按现状报「模型不支持图片」(不静默);转写失败或代理未配置时同样
|
|
7
8
|
// 只留审计(vision.fallback),不重试、不刷额度。
|
|
8
9
|
// 本文件是纯函数模块(手法同 message-images.js):service 实例由调用方显式传入,
|
|
@@ -150,9 +151,56 @@ export function maybeSpawnVisionAfterFailure(service, { run, bot, error }) {
|
|
|
150
151
|
}
|
|
151
152
|
}
|
|
152
153
|
|
|
154
|
+
// 续答派生(闭环):转写写回后同一条消息再排一次 chat/solo_chat 运行,让主模型基于
|
|
155
|
+
// 转写正文回答用户。首发运行已因主模型无视觉失败,其幂等键(chat:<msg>:<bot>)会被
|
|
156
|
+
// enqueueChatRun 的既有行查询挡下,所以续答自带新键;image_offload=1 让 startRun
|
|
157
|
+
// 跳过二进制附图,转写正文由提示词近期窗口带入。
|
|
158
|
+
export function spawnVisionFollowupRun(service, { run, bot, message }) {
|
|
159
|
+
if (!bot || !message?.id) return null
|
|
160
|
+
const isSolo = !run?.project_id
|
|
161
|
+
const idempotencyKey = isSolo
|
|
162
|
+
? `solo_chat:${message.id}:vision`
|
|
163
|
+
: `chat:${message.id}:${bot.id}:vision`
|
|
164
|
+
const existing = service.store.get('SELECT * FROM runs WHERE idempotency_key = ?', idempotencyKey)
|
|
165
|
+
if (existing) return existing
|
|
166
|
+
// 沿用首发运行的 trigger_type:通道直达(微信/飞书)的回推语义不能丢。
|
|
167
|
+
const source = service.store.get(
|
|
168
|
+
`SELECT trigger_type FROM runs WHERE trigger_ref = ? AND bot_id = ?
|
|
169
|
+
AND kind IN ('chat', 'solo_chat') ORDER BY queued_at DESC LIMIT 1`,
|
|
170
|
+
message.id, bot.id,
|
|
171
|
+
)
|
|
172
|
+
const runId = id('run')
|
|
173
|
+
const createdAt = nowIso()
|
|
174
|
+
try {
|
|
175
|
+
service.store.transaction(() => {
|
|
176
|
+
service.store.run(
|
|
177
|
+
`INSERT INTO runs(id, project_id, bot_id, kind, mode, trigger_type, trigger_ref,
|
|
178
|
+
status, attempt, idempotency_key, image_offload, queued_at)
|
|
179
|
+
VALUES (?, ?, ?, ?, 'read', ?, ?, 'queued', 1, ?, 1, ?)`,
|
|
180
|
+
runId, run?.project_id ?? null, bot.id, isSolo ? 'solo_chat' : 'chat',
|
|
181
|
+
source?.trigger_type ?? 'mention', message.id, idempotencyKey, createdAt,
|
|
182
|
+
)
|
|
183
|
+
service.runChatStore({ id: runId, project_id: run?.project_id ?? null, bot_id: bot.id }).run(
|
|
184
|
+
'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
|
|
185
|
+
id('evt'), runId, 'queued',
|
|
186
|
+
`转写完成,续答消息 ${message.id}(本轮不下发二进制图)`,
|
|
187
|
+
createdAt,
|
|
188
|
+
)
|
|
189
|
+
})
|
|
190
|
+
} catch (insertError ) {
|
|
191
|
+
if (String(insertError).includes('UNIQUE')) {
|
|
192
|
+
return service.store.get('SELECT * FROM runs WHERE idempotency_key = ?', idempotencyKey) ?? null
|
|
193
|
+
}
|
|
194
|
+
throw insertError
|
|
195
|
+
}
|
|
196
|
+
service.logger?.info?.('dsh-team: vision followup run %s queued for message %s', runId, message.id)
|
|
197
|
+
void service.tick()
|
|
198
|
+
return service.store.get('SELECT * FROM runs WHERE id = ?', runId)
|
|
199
|
+
}
|
|
200
|
+
|
|
153
201
|
// 转写运行收尾(runs.finishRun 的 kind='vision' 分支):成功且产出非空 → 以
|
|
154
202
|
// 「[图片转写] …」system 消息写回原消息所在会话(群聊挂 reply_to 原消息,单聊
|
|
155
|
-
// 落 solo_messages),并审计 vision.transcribe
|
|
203
|
+
// 落 solo_messages),并审计 vision.transcribe,随后派生续答运行;失败或空产出 → 只审计
|
|
156
204
|
// vision.fallback(原对话已按现状报过「模型不支持图片」,这里不再插消息、不重试)。
|
|
157
205
|
export async function completeVisionRun(service, { run, bot, status, output, error }) {
|
|
158
206
|
const actor = { type: 'bot', id: bot?.id }
|
|
@@ -188,6 +236,13 @@ export async function completeVisionRun(service, { run, bot, status, output, err
|
|
|
188
236
|
service.audit(actor, 'vision.transcribe', 'bot', bot.id, {
|
|
189
237
|
runId: run.id, messageId: message?.id ?? run.trigger_ref,
|
|
190
238
|
})
|
|
239
|
+
// 闭环:转写已写回,同一条消息再排一次续答运行,让主模型基于转写正文回答用户
|
|
240
|
+
// (首发运行已因主模型无视觉失败,不会自己产出正文)。派生失败只告警,不拖累收尾。
|
|
241
|
+
try {
|
|
242
|
+
if (message) spawnVisionFollowupRun(service, { run, bot, message })
|
|
243
|
+
} catch (followupError ) {
|
|
244
|
+
service.logger?.warn?.('dsh-team: vision followup spawn failed: %s', followupError?.message ?? followupError)
|
|
245
|
+
}
|
|
191
246
|
return
|
|
192
247
|
}
|
|
193
248
|
service.audit(actor, 'vision.fallback', 'bot', bot.id, {
|
package/src/services/wechat.js
CHANGED
|
@@ -7,8 +7,10 @@ import { createRequire } from 'node:module'
|
|
|
7
7
|
import { effectiveWechatEnabled } from '../config.js'
|
|
8
8
|
import { AppError, conflict } from '../errors.js'
|
|
9
9
|
import { WechatIlinkError } from '../wechat/commands.js'
|
|
10
|
-
import { jsonParse, nowIso, parseMentions } from '../util.js'
|
|
10
|
+
import { flattenWhitespace, jsonParse, nowIso, parseMentions } from '../util.js'
|
|
11
11
|
import { answerFailed, answerReceipt, approvalCard, questionCard, wechatToken } from '../wechat/format.js'
|
|
12
|
+
import { approvalCard as feishuApprovalCard, questionCard as feishuQuestionCard } from '../feishu/format.js'
|
|
13
|
+
import { cleanQuestionItem } from './questions.js'
|
|
12
14
|
import { recordWechatTriggerRow } from './wechat-trigger-schema.js'
|
|
13
15
|
|
|
14
16
|
// 微信登录二维码:服务端直接出 SVG,UI 注入即可,无需前端 QR 库(vendor/qrcode,MIT)。
|
|
@@ -243,9 +245,16 @@ export const wechatMethods = {
|
|
|
243
245
|
* (各通道 outbox 库彼此独立,同键在两套库里各自幂等,互不干扰)。
|
|
244
246
|
* DSHBOTS-326:出站经 channelNotify 扇出到微信与飞书,单通道失败不阻断另一通道。 */
|
|
245
247
|
wechatQuestion(project, row, items) {
|
|
248
|
+
const token = wechatToken(row.id)
|
|
249
|
+
const projectName = project.name || project.key
|
|
250
|
+
const botName = row.bot_name ?? 'Bot'
|
|
246
251
|
const results = this.channelNotify?.(
|
|
247
|
-
questionCard(
|
|
248
|
-
{
|
|
252
|
+
questionCard(projectName, botName, items, token),
|
|
253
|
+
{
|
|
254
|
+
receiptKey: `question:${row.id}`,
|
|
255
|
+
// 飞书原生渲染 markdown:给 markdown 卡片;微信仍走纯文本镜像(窄屏、字数受限)。
|
|
256
|
+
texts: { feishu: feishuQuestionCard(projectName, botName, items, token) },
|
|
257
|
+
},
|
|
249
258
|
) ?? []
|
|
250
259
|
return results.some(result => result.ok)
|
|
251
260
|
},
|
|
@@ -254,9 +263,15 @@ export const wechatMethods = {
|
|
|
254
263
|
* 幂等收据键(A3/DSHBOTS-323):approval:<row.id>(各通道 outbox 库内各自幂等)。
|
|
255
264
|
* DSHBOTS-326:出站经 channelNotify 扇出,单通道失败只留痕不阻断另一通道。 */
|
|
256
265
|
wechatApproval(project, row) {
|
|
266
|
+
const token = wechatToken(row.id)
|
|
267
|
+
const projectName = project.name || project.key
|
|
268
|
+
const botName = row.bot_name ?? 'Bot'
|
|
257
269
|
const results = this.channelNotify?.(
|
|
258
|
-
approvalCard(
|
|
259
|
-
{
|
|
270
|
+
approvalCard(projectName, botName, row.tool_name, row.reason, token),
|
|
271
|
+
{
|
|
272
|
+
receiptKey: `approval:${row.id}`,
|
|
273
|
+
texts: { feishu: feishuApprovalCard(projectName, botName, row.tool_name, row.reason, token) },
|
|
274
|
+
},
|
|
260
275
|
) ?? []
|
|
261
276
|
return results.some(result => result.ok)
|
|
262
277
|
},
|
|
@@ -345,7 +360,8 @@ export const wechatMethods = {
|
|
|
345
360
|
async wechatAnswerQuestion(token, body, fallbackKey = null) {
|
|
346
361
|
const row = this.pendingWechatRow('questions', token, fallbackKey)
|
|
347
362
|
if (!row) return answerFailed(token, '没有匹配的待答提问(可能已作答或已过期)')
|
|
348
|
-
|
|
363
|
+
// 选项 label 与工作台同口径(单行化):存量行带 CR 时也能按清洗后的文字命中。
|
|
364
|
+
const items = jsonParse(row.questions, []).map(cleanQuestionItem)
|
|
349
365
|
const parsed = parseWechatAnswers(items, body)
|
|
350
366
|
if (parsed.error) return answerFailed(token, parsed.error)
|
|
351
367
|
this.settleQuestion(row.id, 'answered', { answers: parsed.answers }, 'user:wechat')
|
|
@@ -427,7 +443,7 @@ function parseWechatAnswers(items, body) {
|
|
|
427
443
|
answers.push({ id: String(item.id), selected })
|
|
428
444
|
parts.push(`Q${i + 1}: ${selected.join('、')}`)
|
|
429
445
|
} else {
|
|
430
|
-
answers.push({ id: String(item.id), selected: [], ...(raw ? { custom: raw } : {}) })
|
|
446
|
+
answers.push({ id: String(item.id), selected: [], ...(raw ? { custom: flattenWhitespace(raw) } : {}) })
|
|
431
447
|
parts.push(`Q${i + 1}: ${raw || '(未填)'}`)
|
|
432
448
|
}
|
|
433
449
|
}
|
package/src/util.js
CHANGED
|
@@ -24,6 +24,23 @@ export const projectKey = (value) => String(value ?? '')
|
|
|
24
24
|
|
|
25
25
|
export const text = (value, max = 20_000) => String(value ?? '').trim().slice(0, max)
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* 去 CR:CRLF 归一为 LF,其余孤立 CR 直接丢弃。
|
|
29
|
+
* 模型工具入参偶发把空格写成 CR(U+000D)——渲染器按行尾处理,一句话会被劈成多段
|
|
30
|
+
* (飞书卡片 markdown、聊天气泡都把 CR 当换行)。
|
|
31
|
+
*/
|
|
32
|
+
export const stripCarriageReturns = (value) => String(value ?? '')
|
|
33
|
+
.replace(/\r\n/g, '\n')
|
|
34
|
+
.replace(/\r/g, '')
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 单行化:去 CR 后把其余空白(空格/Tab/换行)折叠成单个半角空格并去首尾空白。
|
|
38
|
+
* 提问、选项这类单行字段统一过这一道,避免残留空白把版面撑散。
|
|
39
|
+
*/
|
|
40
|
+
export const flattenWhitespace = (value) => stripCarriageReturns(value)
|
|
41
|
+
.replace(/\s+/g, ' ')
|
|
42
|
+
.trim()
|
|
43
|
+
|
|
27
44
|
export const jsonParse = (value, fallback) => {
|
|
28
45
|
if (value === null || value === undefined || value === '') return fallback
|
|
29
46
|
try { return JSON.parse(value) } catch { return fallback }
|
package/src/wechat/channel.js
CHANGED
|
@@ -5,6 +5,7 @@ import { TencentIlinkTransport } from '../../vendor/wechat-ilink/index.js'
|
|
|
5
5
|
import { handleCommand, isRetryable, outboundChunks, WechatBusinessError, WechatIlinkError } from './commands.js'
|
|
6
6
|
import { batchDigest, failureText, welcomeAdmin } from './format.js'
|
|
7
7
|
import { AppError } from '../errors.js'
|
|
8
|
+
import { stripCarriageReturns } from '../util.js'
|
|
8
9
|
|
|
9
10
|
const { version: PLUGIN_VERSION } = createRequire(import.meta.url)('../../package.json')
|
|
10
11
|
const RECONNECT_DELAYS_MS = [1_000, 2_000, 5_000, 10_000, 30_000]
|
|
@@ -455,7 +456,8 @@ export class WechatChannel {
|
|
|
455
456
|
const peer = this.peers.get(peerId)
|
|
456
457
|
// 尚无会话凭证属于可恢复状态(等对方发来消息即可),重试有意义
|
|
457
458
|
if (!peer?.contextToken) throw new Error('尚无该联系人的会话凭证,等待对方发来消息')
|
|
458
|
-
|
|
459
|
+
// 出站边界去 CR:模型文本偶发带 CR,按行尾渲染会把一句话劈成多段。
|
|
460
|
+
const body = stripCarriageReturns(text).trim()
|
|
459
461
|
if (!body) return
|
|
460
462
|
// 拒发观测上下文:桥接 fetch 记录 ret!=0,vendor 抛错后由 attachRejectDetail 拼进文案
|
|
461
463
|
await ilinkRejectSlot.run({}, async () => {
|
package/src/wechat/commands.js
CHANGED
|
@@ -63,7 +63,8 @@ export async function handleCommand(service, rawText, ctx = null) {
|
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
// DSHBOTS-249 固定指令:/ 前缀一律不进对话链路,未知 /xxx 回简短帮助提示。
|
|
66
|
-
|
|
66
|
+
const command = normalizeCommandPrefix(body)
|
|
67
|
+
if (command.startsWith('/')) return handleFixedCommand(service, command, ctx)
|
|
67
68
|
|
|
68
69
|
// DSHBOTS-215 问答回路:微信答复/审批按 token 路由回对应条目,绝不进普通对话。
|
|
69
70
|
// 仅在 service 实现了对应方法时拦截(测试桩未实现时按普通文本处理)。
|
|
@@ -103,6 +104,17 @@ export async function handleCommand(service, rawText, ctx = null) {
|
|
|
103
104
|
return ''
|
|
104
105
|
}
|
|
105
106
|
|
|
107
|
+
/**
|
|
108
|
+
* 固定指令前缀归一化:中文输入法常把指令里的 "/" 与 "?" 打成全角(/ 与 ?),
|
|
109
|
+
* 不归一化时 "/?" 匹配不上固定指令集,会被当成普通文本发进对话链路,用户看到的
|
|
110
|
+
* 却是「没有这个指令」。只改指令符号本身,正文原样保留。
|
|
111
|
+
*/
|
|
112
|
+
function normalizeCommandPrefix(body) {
|
|
113
|
+
return String(body ?? '')
|
|
114
|
+
.replace(/^\uFF0F/, '/')
|
|
115
|
+
.replace(/^\/([a-z??]+)/i, (matched, verb) => `/${verb.replace(/?/g, '?')}`)
|
|
116
|
+
}
|
|
117
|
+
|
|
106
118
|
/**
|
|
107
119
|
* / 前缀固定指令集(DSHBOTS-249)。只读指令对群成员开放;写操作(ADMIN_VERBS)
|
|
108
120
|
* 走 admin 门(与 答/批 同口径,分档依据见 handleCommand 注释)。
|
|
@@ -9,7 +9,7 @@ import { exportUsageCsv, switchUsageWindow, usageMode } from './usage.js'
|
|
|
9
9
|
import { focusApprovalCard, focusQuestionCard, questionDraftSelection, questionSelectOption } from './cards.js'
|
|
10
10
|
import { loadSoloDetail } from './chat.js'
|
|
11
11
|
import { searchMemories } from './tasks.js'
|
|
12
|
-
import { openFilePreview } from './file-preview.js'
|
|
12
|
+
import { ARTIFACT_IMAGE, openFilePreview } from './file-preview.js'
|
|
13
13
|
import { handleBoardAction } from './events-board.js'
|
|
14
14
|
import { refresh, renderKeepingChatScroll, render, beginChatPending, endChatPending } from '../app.js'
|
|
15
15
|
|
|
@@ -28,6 +28,19 @@ document.addEventListener('click', async (event) => {
|
|
|
28
28
|
openInlineImage(bubbleImg)
|
|
29
29
|
return
|
|
30
30
|
}
|
|
31
|
+
// 本地文件链接(markdown.ts 把消息里的相对路径图片/链接统一改写成 /api/dsh-team/file):
|
|
32
|
+
// 点击不跳页,按扩展分流——图片扩展进现有查看器,其余进交付产物同款文本预览弹层,
|
|
33
|
+
// 非白名单类型由弹层显示加载失败;中键/Ctrl 点仍走浏览器原生新窗口。
|
|
34
|
+
const fileLink = (event.target ).closest?.('a[href^="/api/dsh-team/file"]')
|
|
35
|
+
if (fileLink) {
|
|
36
|
+
event.preventDefault()
|
|
37
|
+
const href = fileLink.getAttribute('href') ?? ''
|
|
38
|
+
let linkPath = ''
|
|
39
|
+
try { linkPath = new URL(href, location.href).searchParams.get('path') ?? '' } catch { /* 非法 href 按无路径处理 */ }
|
|
40
|
+
if (linkPath && ARTIFACT_IMAGE.test(linkPath)) openInlineImage({ currentSrc: href, getAttribute: () => '' })
|
|
41
|
+
else await openFilePreview(href, linkPath)
|
|
42
|
+
return
|
|
43
|
+
}
|
|
31
44
|
const target = (event.target ).closest('[data-action]')
|
|
32
45
|
if (!target) return
|
|
33
46
|
const action = target.dataset.action
|
|
@@ -2,6 +2,7 @@ import { state } from './state.js'
|
|
|
2
2
|
import { attr, esc } from './util.js'
|
|
3
3
|
import { t } from './i18n.js'
|
|
4
4
|
import { modalShell, renderModalLayer } from './modal-layer.js'
|
|
5
|
+
import { mdChatScope, richText } from './markdown.js'
|
|
5
6
|
|
|
6
7
|
// file-preview-logic:start —— 文本预览纯逻辑(tests/file-preview.test.js 抽取此块断言)。
|
|
7
8
|
// 白名单与后端 chatFile 的文本扩展同口径;SVG 可执行脚本、.env 常带密钥,永不入列。
|
|
@@ -11,6 +12,11 @@ const PREVIEW_MAX_LINES = 2000
|
|
|
11
12
|
function isPreviewableText(path) {
|
|
12
13
|
return FILE_TEXT_EXT.test(String(path ?? ''))
|
|
13
14
|
}
|
|
15
|
+
// markdown 扩展走渲染预览(richText 管线),与纯文本展示分开。
|
|
16
|
+
const FILE_MD_EXT = /\.(md|markdown)$/i
|
|
17
|
+
function isMarkdownPath(path) {
|
|
18
|
+
return FILE_MD_EXT.test(String(path ?? ''))
|
|
19
|
+
}
|
|
14
20
|
// 超限截断:256KB 与 2000 行先到先裁;弹层只提示,不改写内容本身。
|
|
15
21
|
function clipPreviewText(text) {
|
|
16
22
|
const source = String(text ?? '')
|
|
@@ -38,8 +44,8 @@ const artifactFileUrl = (runId, path) =>
|
|
|
38
44
|
const artifactExt = (path) =>
|
|
39
45
|
(String(path).match(/\.([a-z0-9]+)$/i)?.[1] ?? 'file').toUpperCase().slice(0, 6)
|
|
40
46
|
|
|
41
|
-
//
|
|
42
|
-
//
|
|
47
|
+
// 文件预览弹层:文本走 textContent 通道;markdown 走与聊天气泡同一条 richText
|
|
48
|
+
// 消毒管线(marked → DOMPurify),不经手拼 HTML。footer 保留「新窗口打开」。
|
|
43
49
|
function modalFilePreview(modal) {
|
|
44
50
|
const path = String(modal?.path ?? '')
|
|
45
51
|
if (modal?.error) {
|
|
@@ -53,34 +59,40 @@ function modalFilePreview(modal) {
|
|
|
53
59
|
return modalShell({
|
|
54
60
|
title: path || t("文件预览"),
|
|
55
61
|
subtitle: modal?.truncated ? t("文件较大,已截断,仅显示开头部分。") : '',
|
|
56
|
-
body:
|
|
62
|
+
body: modal?.kind === 'md'
|
|
63
|
+
? '<div class="comment-body" id="dsh-file-preview-md"></div>'
|
|
64
|
+
: '<pre class="detail-pre" id="dsh-file-preview-pre"></pre>',
|
|
57
65
|
footer: `<button class="btn" data-action="close-modal">${t("关闭")}</button><button class="btn" data-action="open-artifact" data-url="${attr(modal?.url ?? '')}">${t("新窗口打开")}</button>`,
|
|
58
66
|
size: 'wide',
|
|
59
67
|
})
|
|
60
68
|
}
|
|
61
69
|
|
|
62
|
-
//
|
|
70
|
+
// 正文水合:把已取回的内容写进占位节点。滚动守卫可能把补拍延后约 120ms,
|
|
63
71
|
// 首拍未命中节点时短重试,避免补拍后弹层空白。
|
|
64
72
|
function hydrateFilePreview(retry = 3) {
|
|
65
|
-
|
|
66
|
-
|
|
73
|
+
if (state.modal?.type !== 'file-preview') return
|
|
74
|
+
const isMd = state.modal.kind === 'md'
|
|
75
|
+
const node = document.getElementById(isMd ? 'dsh-file-preview-md' : 'dsh-file-preview-pre')
|
|
76
|
+
if (!node) {
|
|
67
77
|
if (retry > 0) setTimeout(() => hydrateFilePreview(retry - 1), 150)
|
|
68
78
|
return
|
|
69
79
|
}
|
|
70
|
-
if (
|
|
80
|
+
if (isMd) node.innerHTML = richText(state.modal.content ?? '', mdChatScope())
|
|
81
|
+
else node.textContent = state.modal.content ?? ''
|
|
71
82
|
}
|
|
72
83
|
|
|
73
84
|
async function openFilePreview(url, path) {
|
|
74
85
|
if (!url) return
|
|
75
|
-
|
|
86
|
+
const kind = isMarkdownPath(path) ? 'md' : 'text'
|
|
87
|
+
state.modal = { type: 'file-preview', loading: true, kind, title: String(path ?? '').split('/').pop() || t("文件预览"), url, path }
|
|
76
88
|
renderModalLayer()
|
|
77
89
|
try {
|
|
78
90
|
const res = await fetch(url)
|
|
79
91
|
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
|
80
92
|
const { body, truncated } = clipPreviewText(await res.text())
|
|
81
|
-
state.modal = { type: 'file-preview', url, path, content: body, truncated }
|
|
93
|
+
state.modal = { type: 'file-preview', kind, url, path, content: body, truncated }
|
|
82
94
|
} catch (error ) {
|
|
83
|
-
state.modal = { type: 'file-preview', url, path, error: String(error?.message ?? error) }
|
|
95
|
+
state.modal = { type: 'file-preview', kind, url, path, error: String(error?.message ?? error) }
|
|
84
96
|
}
|
|
85
97
|
renderModalLayer()
|
|
86
98
|
hydrateFilePreview()
|
package/ui/modules/markdown.js
CHANGED
|
@@ -3,13 +3,15 @@ import { esc, inSoloContext, botById, pageProject } from './util.js'
|
|
|
3
3
|
import { t } from './i18n.js'
|
|
4
4
|
|
|
5
5
|
// markdown-render:start —— 聊天 markdown 渲染纯逻辑(tests/markdown.test.js 抽取此块断言)。
|
|
6
|
-
// 管线固定:md →
|
|
6
|
+
// 管线固定:md → mdRewriteFileSources → marked.parse → DOMPurify.sanitize → innerHTML。
|
|
7
7
|
// 消毒不可绕:marked 或 DOMPurify 缺席、或 DOMPurify.isSupported=false(node/损坏安装)时
|
|
8
8
|
// mdCreateRenderer 返回 null,调用方回退 esc 纯文本,绝不裸插 HTML。
|
|
9
|
-
//
|
|
9
|
+
// 工作区相对路径的图片与文件链接都改写成 GET /api/dsh-team/file(服务端再做 MIME 白名单与防穿越),
|
|
10
|
+
// 与 DSH 宿主一致:消息里的本地文件引用可预览,而不是按页面 URL 解析成死链。
|
|
10
11
|
const MD_SCHEME = /^(?:[a-z][a-z0-9+.-]*:|#|\/\/)/i
|
|
11
|
-
//
|
|
12
|
-
|
|
12
|
+
// 图片/链接语法同构:(!?) 前缀区分两种语法;href 允许含空格(到标题或右括号前止),
|
|
13
|
+
// 标题可为 "..." / '...' / (...)。单遍匹配,已改写的图片 URL 不会被链接分支二次处理。
|
|
14
|
+
const MD_MEDIA = /(!?)\[([^\]]*)\]\(([^)\n]*?)(?:\s+("[^"]*"|'[^']*'|\([^)]*\)))?\s*\)/g
|
|
13
15
|
// 只剥尾部标题:含空格的路径若被标题正则误切会丢文件名,故仅匹配整段结尾的引号/括号标题。
|
|
14
16
|
const MD_IMAGE_TITLE = /\s+("[^"]*"|'[^']*'|\([^)]*\))$/
|
|
15
17
|
function mdImageTarget(inner) {
|
|
@@ -46,10 +48,10 @@ function mdImageFileUrl(href, scope) {
|
|
|
46
48
|
params.set('path', rel)
|
|
47
49
|
return `/api/dsh-team/file?${params.toString()}`
|
|
48
50
|
}
|
|
49
|
-
function
|
|
50
|
-
return String(source ?? '').replace(
|
|
51
|
+
function mdRewriteFileSources(source, scope) {
|
|
52
|
+
return String(source ?? '').replace(MD_MEDIA, (whole, bang, label, inner) => {
|
|
51
53
|
const url = mdImageFileUrl(mdImageTarget(inner), scope)
|
|
52
|
-
return url ? `${
|
|
54
|
+
return url ? `${bang}[${label}](${url})` : whole
|
|
53
55
|
})
|
|
54
56
|
}
|
|
55
57
|
function mdCreateRenderer(deps) {
|
|
@@ -81,7 +83,7 @@ function mdCreateRenderer(deps) {
|
|
|
81
83
|
cache.set(key, hit)
|
|
82
84
|
return hit
|
|
83
85
|
}
|
|
84
|
-
const html = marked.parse(
|
|
86
|
+
const html = marked.parse(mdRewriteFileSources(body, scope), { gfm: true, breaks: true })
|
|
85
87
|
const safe = DOMPurify.sanitize(html, { USE_PROFILES: { html: true } })
|
|
86
88
|
cache.set(key, safe)
|
|
87
89
|
if (cache.size > MD_RENDER_CACHE_MAX) cache.delete(cache.keys().next().value)
|