@goodandready/dsh-messenger-gateway 0.4.22 → 0.4.24
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/lib/adapters/telegram.js +16 -2
- package/lib/client.js +38 -0
- package/lib/config.js +4 -0
- package/lib/gateway-turn.js +131 -43
- package/lib/gateway.js +19 -8
- package/lib/index.js +5 -0
- package/lib/locales/en.js +6 -4
- package/lib/locales/zh.js +5 -3
- package/lib/stream.js +128 -4
- package/lib/telegram-format.js +9 -4
- package/package.json +1 -1
package/lib/adapters/telegram.js
CHANGED
|
@@ -487,11 +487,25 @@ export class TelegramAdapter {
|
|
|
487
487
|
const messageId = result?.message_id
|
|
488
488
|
return {
|
|
489
489
|
messageId,
|
|
490
|
-
edit: async (text) => {
|
|
490
|
+
edit: async (text, options = {}) => {
|
|
491
491
|
const plain = String(text || '…').slice(0, TELEGRAM_MAX)
|
|
492
|
+
const params = { chat_id: chatId, message_id: messageId, text: plain || '…' }
|
|
493
|
+
if (options?.parseMode || options?.parse_mode) {
|
|
494
|
+
params.parse_mode = options.parseMode || options.parse_mode
|
|
495
|
+
}
|
|
492
496
|
try {
|
|
493
|
-
await this.call('editMessageText',
|
|
497
|
+
await this.call('editMessageText', params)
|
|
494
498
|
} catch (err) {
|
|
499
|
+
if (params.parse_mode) {
|
|
500
|
+
try {
|
|
501
|
+
await this.call('editMessageText', { chat_id: chatId, message_id: messageId, text: plain || '…' })
|
|
502
|
+
return
|
|
503
|
+
} catch (innerErr) {
|
|
504
|
+
const msg = String(innerErr.message || '')
|
|
505
|
+
if (!msg.includes('message is not modified')) throw innerErr
|
|
506
|
+
return
|
|
507
|
+
}
|
|
508
|
+
}
|
|
495
509
|
const msg = String(err.message || '')
|
|
496
510
|
if (!msg.includes('message is not modified')) throw err
|
|
497
511
|
}
|
package/lib/client.js
CHANGED
|
@@ -94,6 +94,11 @@ window.__ModuleLoader__.load({
|
|
|
94
94
|
groupMention: 'Require @mention, reply, or /command in groups',
|
|
95
95
|
reactionsEnable: 'React with 👀 while processing turn',
|
|
96
96
|
progressEnable: 'Progress status message (Thinking → Delete → Final)',
|
|
97
|
+
showReasoning: 'Show reasoning / thought process in chat',
|
|
98
|
+
thoughtCollapse: 'Collapse finished thoughts into expandable blockquote',
|
|
99
|
+
approvalsEnable: 'Human-in-the-Loop action approvals (interactive cards)',
|
|
100
|
+
approvalsSensitivity: 'Action Approval Sensitivity',
|
|
101
|
+
approvalsTimeout: 'Approval Timeout (seconds)',
|
|
97
102
|
statusIndicator: 'Bot Status Description Indicator (Online/Offline)',
|
|
98
103
|
statusIndicatorHint: 'Sets bot short description via Telegram API (visible to all users).',
|
|
99
104
|
transport: 'Telegram Transport Mode',
|
|
@@ -243,6 +248,11 @@ window.__ModuleLoader__.load({
|
|
|
243
248
|
groupMention: '群组中需 @提及、回复或 /命令',
|
|
244
249
|
reactionsEnable: '处理中添加 👀 表情反应',
|
|
245
250
|
progressEnable: '进度状态提示 (思考中 → 删除 → 最终回复)',
|
|
251
|
+
showReasoning: '在聊天中显示推理思考过程',
|
|
252
|
+
thoughtCollapse: '将已完成的思考折叠为可展开的引用块',
|
|
253
|
+
approvalsEnable: '人在回路操作授权确认(交互式卡片)',
|
|
254
|
+
approvalsSensitivity: '操作授权敏感度',
|
|
255
|
+
approvalsTimeout: '授权确认超时时间 (秒)',
|
|
246
256
|
statusIndicator: '机器人状态描述指示器 (Online/Offline)',
|
|
247
257
|
statusIndicatorHint: '通过 Telegram API 设置机器人简介(所有人可见)。',
|
|
248
258
|
transport: 'Telegram 传输模式',
|
|
@@ -505,7 +515,11 @@ window.__ModuleLoader__.load({
|
|
|
505
515
|
streaming: t.streaming === true,
|
|
506
516
|
streamEditIntervalMs: Number(t.streamEditIntervalMs) || 1200,
|
|
507
517
|
progressEnabled: t.progressEnabled !== false,
|
|
518
|
+
showReasoning: t.showReasoning !== false,
|
|
519
|
+
thoughtCollapse: t.thoughtCollapse !== false,
|
|
508
520
|
approvalsEnabled: t.approvalsEnabled !== false,
|
|
521
|
+
approvalsSensitivity: t.approvalsSensitivity || 'mutations',
|
|
522
|
+
approvalsTimeoutMs: Number(t.approvalsTimeoutMs) || 300000,
|
|
509
523
|
groupsEnabled: t.groupsEnabled !== false,
|
|
510
524
|
groupRequireMention: t.groupRequireMention !== false,
|
|
511
525
|
reactionsEnabled: t.reactionsEnabled !== false,
|
|
@@ -995,6 +1009,30 @@ window.__ModuleLoader__.load({
|
|
|
995
1009
|
}),
|
|
996
1010
|
t('progressEnable')
|
|
997
1011
|
),
|
|
1012
|
+
React.createElement('label', { className: 'msgw-check' },
|
|
1013
|
+
React.createElement('input', {
|
|
1014
|
+
type: 'checkbox',
|
|
1015
|
+
checked: cfg.telegram?.showReasoning !== false,
|
|
1016
|
+
onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, showReasoning: e.target.checked } }),
|
|
1017
|
+
}),
|
|
1018
|
+
t('showReasoning')
|
|
1019
|
+
),
|
|
1020
|
+
React.createElement('label', { className: 'msgw-check' },
|
|
1021
|
+
React.createElement('input', {
|
|
1022
|
+
type: 'checkbox',
|
|
1023
|
+
checked: cfg.telegram?.thoughtCollapse !== false,
|
|
1024
|
+
onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, thoughtCollapse: e.target.checked } }),
|
|
1025
|
+
}),
|
|
1026
|
+
t('thoughtCollapse')
|
|
1027
|
+
),
|
|
1028
|
+
React.createElement('label', { className: 'msgw-check' },
|
|
1029
|
+
React.createElement('input', {
|
|
1030
|
+
type: 'checkbox',
|
|
1031
|
+
checked: cfg.telegram?.approvalsEnabled !== false,
|
|
1032
|
+
onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, approvalsEnabled: e.target.checked } }),
|
|
1033
|
+
}),
|
|
1034
|
+
t('approvalsEnable')
|
|
1035
|
+
),
|
|
998
1036
|
React.createElement('label', { className: 'msgw-check' },
|
|
999
1037
|
React.createElement('input', {
|
|
1000
1038
|
type: 'checkbox',
|
package/lib/config.js
CHANGED
|
@@ -36,7 +36,11 @@ export const PluginConfig = z.object({
|
|
|
36
36
|
streaming: z.boolean().default(false).description('If true, edit one Telegram message while tokens arrive; default off'),
|
|
37
37
|
streamEditIntervalMs: z.number().default(1200),
|
|
38
38
|
progressEnabled: z.boolean().default(true),
|
|
39
|
+
showReasoning: z.boolean().default(true).description('Display model reasoning/thought process in chat'),
|
|
40
|
+
thoughtCollapse: z.boolean().default(true).description('Collapse finished thoughts into expandable blockquote'),
|
|
39
41
|
approvalsEnabled: z.boolean().default(true),
|
|
42
|
+
approvalsSensitivity: z.union([z.const('all'), z.const('mutations'), z.const('disabled')]).default('mutations').description('Sensitivity level: mutations only, all tool calls, or disabled'),
|
|
43
|
+
approvalsTimeoutMs: z.number().default(300000).description('Timeout in ms before auto-rejecting pending approval (default 5m)'),
|
|
40
44
|
groupsEnabled: z.boolean().default(true).description('Process group/supergroup messages'),
|
|
41
45
|
groupRequireMention: z.boolean().default(true).description('In groups, only respond to @mention, reply-to-bot, or /commands'),
|
|
42
46
|
reactionsEnabled: z.boolean().default(true).description('React with 👀 while processing a turn'),
|
package/lib/gateway-turn.js
CHANGED
|
@@ -12,8 +12,9 @@ import { speakText, transcribeVoice } from './integrations.js'
|
|
|
12
12
|
import { attachInboundPhoto, photoOnlyHint } from './photos.js'
|
|
13
13
|
import { buildOutboundFiles, stripImageUrls } from './outbound.js'
|
|
14
14
|
import {
|
|
15
|
-
buildStreamPreview, formatProgressLine, createEditScheduler, startTypingHeartbeat
|
|
15
|
+
buildStreamPreview, formatProgressLine, createEditScheduler, startTypingHeartbeat, parseReasoningStream
|
|
16
16
|
} from './stream.js'
|
|
17
|
+
import { escapeHtml } from './telegram-format.js'
|
|
17
18
|
|
|
18
19
|
const PLUGIN = 'dsh-messenger-gateway'
|
|
19
20
|
|
|
@@ -30,45 +31,109 @@ export function whenIdleWithTimeout(agent, timeoutMs, signal) {
|
|
|
30
31
|
])
|
|
31
32
|
}
|
|
32
33
|
|
|
33
|
-
export
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
34
|
+
export function isSensitiveTool(toolName) {
|
|
35
|
+
if (!toolName) return false
|
|
36
|
+
const tName = String(toolName).toLowerCase()
|
|
37
|
+
const sensitivePatterns = [
|
|
38
|
+
/command/i, /exec/i, /bash/i, /shell/i, /terminal/i,
|
|
39
|
+
/write/i, /edit/i, /delete/i, /remove/i, /patch/i, /create/i,
|
|
40
|
+
/git/i, /deploy/i, /publish/i, /curl/i, /wget/i, /rm$/i,
|
|
41
|
+
]
|
|
42
|
+
return sensitivePatterns.some((p) => p.test(tName))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function formatApprovalCard(req, locale = "en") {
|
|
46
|
+
const tool = req.toolName || "tool"
|
|
47
|
+
const reason = req.reason ? `\n<i>${escapeHtml(req.reason)}</i>` : ""
|
|
48
|
+
let detail = ""
|
|
49
|
+
const input = req.input
|
|
50
|
+
|
|
51
|
+
if (input && typeof input === "object") {
|
|
52
|
+
const cmd = input.CommandLine || input.command || input.cmd
|
|
53
|
+
if (typeof cmd === "string" && cmd.trim()) {
|
|
54
|
+
detail = `\n<pre><code class="language-bash">${escapeHtml(cmd.trim().slice(0, 800))}</code></pre>`
|
|
55
|
+
} else if (typeof input.Path === "string" && (input.Replacement !== undefined || input.Target !== undefined)) {
|
|
56
|
+
const path = input.Path
|
|
57
|
+
const target = String(input.Target ?? "")
|
|
58
|
+
const repl = String(input.Replacement ?? "")
|
|
59
|
+
const fileBasename = path.split(/[\/\\]/).pop() || "file"
|
|
60
|
+
const diffLines = [
|
|
61
|
+
`--- a/${fileBasename}`,
|
|
62
|
+
`+++ b/${fileBasename}`,
|
|
57
63
|
]
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
return 'allowed-once'
|
|
64
|
+
if (target) {
|
|
65
|
+
for (const line of target.slice(0, 400).split("\n")) diffLines.push(`- ${line}`)
|
|
66
|
+
}
|
|
67
|
+
if (repl) {
|
|
68
|
+
for (const line of repl.slice(0, 400).split("\n")) diffLines.push(`+ ${line}`)
|
|
64
69
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
70
|
+
detail = `\n<b>File:</b> <code>${escapeHtml(path)}</code>\n<pre><code class="language-diff">${escapeHtml(diffLines.join("\n"))}</code></pre>`
|
|
71
|
+
} else if (typeof input.Path === "string" && typeof input.Content === "string") {
|
|
72
|
+
const path = input.Path
|
|
73
|
+
const snippet = input.Content.slice(0, 500)
|
|
74
|
+
detail = `\n<b>File:</b> <code>${escapeHtml(path)}</code>\n<pre><code>${escapeHtml(snippet)}</code></pre>`
|
|
75
|
+
} else {
|
|
76
|
+
try {
|
|
77
|
+
const jsonStr = JSON.stringify(input, null, 2)
|
|
78
|
+
detail = `\n<pre><code>${escapeHtml(jsonStr.slice(0, 500))}</code></pre>`
|
|
79
|
+
} catch { /* safe JSON fallback */ }
|
|
69
80
|
}
|
|
70
81
|
}
|
|
71
82
|
|
|
83
|
+
return t("ask.confirm_title", { tool: escapeHtml(tool), reason: reason + detail }, locale, { escape: false })
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function answerApproval(gw, chatKeyValue, req, next) {
|
|
87
|
+
try {
|
|
88
|
+
const tg = gw.tg ? gw.tg() : (gw.config?.telegram || {})
|
|
89
|
+
if (tg.approvalsEnabled === false || tg.approvalsSensitivity === "disabled") {
|
|
90
|
+
return "allowed-once"
|
|
91
|
+
}
|
|
92
|
+
const tool = req.toolName || "tool"
|
|
93
|
+
const sensitivity = tg.approvalsSensitivity || "mutations"
|
|
94
|
+
if (sensitivity === "mutations" && !isSensitiveTool(tool)) {
|
|
95
|
+
return "allowed-once"
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const chat = gw.chats.get(chatKeyValue)
|
|
99
|
+
if (!chat?.target) return next()
|
|
100
|
+
if (chat.sessionAllowlist?.has(tool)) {
|
|
101
|
+
return "allowed-once"
|
|
102
|
+
}
|
|
103
|
+
const locale = gw.resolveLocale ? gw.resolveLocale(chat.target) : "en"
|
|
104
|
+
const text = formatApprovalCard(req, locale)
|
|
105
|
+
const buttons = [
|
|
106
|
+
[
|
|
107
|
+
{ id: "allow_once", text: t("ask.allow_once", {}, locale) },
|
|
108
|
+
{ id: "deny", text: t("ask.deny", {}, locale) },
|
|
109
|
+
],
|
|
110
|
+
[
|
|
111
|
+
{ id: "steer", text: t("ask.steer", {}, locale) },
|
|
112
|
+
{ id: "allow_session", text: t("ask.allow_session", {}, locale) },
|
|
113
|
+
],
|
|
114
|
+
]
|
|
115
|
+
const timeoutMs = Number(tg.approvalsTimeoutMs) || 300_000
|
|
116
|
+
const result = await gw.messengerAsk(chat.target, { text, buttons }, timeoutMs)
|
|
117
|
+
if (result?.buttonId === "allow_once" || result?.buttonId === "allow") return "allowed-once"
|
|
118
|
+
if (result?.buttonId === "allow_session") {
|
|
119
|
+
if (!chat.sessionAllowlist) chat.sessionAllowlist = new Set()
|
|
120
|
+
chat.sessionAllowlist.add(tool)
|
|
121
|
+
return "allowed-once"
|
|
122
|
+
}
|
|
123
|
+
if (result?.buttonId === "steer") {
|
|
124
|
+
try {
|
|
125
|
+
const tgAdapter = gw.adapters?.get ? gw.adapters.get("telegram") : gw.adapters?.telegram
|
|
126
|
+
await tgAdapter?.sendTo?.(chat.target.chatId, { text: t("ask.steer_prompt", {}, locale) }, { threadId: chat.target.threadId || 0 })
|
|
127
|
+
} catch { /* best effort prompt */ }
|
|
128
|
+
return "rejected"
|
|
129
|
+
}
|
|
130
|
+
if (result?.buttonId === "deny" || result?.buttonId === "reject") return "rejected"
|
|
131
|
+
return "rejected"
|
|
132
|
+
} catch {
|
|
133
|
+
return "rejected"
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
72
137
|
export async function buildUserContent(gw, input, signal) {
|
|
73
138
|
const { text, attachments = [], replyText, steer, personaOverride } = input
|
|
74
139
|
const parts = []
|
|
@@ -140,7 +205,7 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
140
205
|
const tg = gw.tg()
|
|
141
206
|
const streaming = tg.streaming === true && typeof startStream === 'function'
|
|
142
207
|
const progressEnabled = tg.progressEnabled !== false
|
|
143
|
-
const collector = { parts: [], lastText: '', streamText: '', toolName: '', images: [], reason: undefined, onStream: undefined }
|
|
208
|
+
const collector = { parts: [], lastText: '', streamText: '', reasoningText: '', toolName: '', images: [], reason: undefined, onStream: undefined }
|
|
144
209
|
gw.pending.set(sessionId, collector)
|
|
145
210
|
let stopTyping = () => {}
|
|
146
211
|
let stream = null
|
|
@@ -155,13 +220,28 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
155
220
|
if (streaming) {
|
|
156
221
|
try {
|
|
157
222
|
stream = await startStream()
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
if (
|
|
162
|
-
|
|
223
|
+
const turnStartTime = Date.now()
|
|
224
|
+
scheduler = createEditScheduler((text) => stream.edit(text, { parseMode: 'HTML' }), Number(tg.streamEditIntervalMs) || 1200, 250, gw.logger)
|
|
225
|
+
collector.onStream = (text, toolName, reasoningText) => {
|
|
226
|
+
if (text || reasoningText) stopTyping()
|
|
227
|
+
if (!progressEnabled && !text && !reasoningText) return
|
|
228
|
+
const preview = buildStreamPreview(text, progressEnabled ? toolName : '', 3500, {
|
|
229
|
+
reasoningText,
|
|
230
|
+
startTime: turnStartTime,
|
|
231
|
+
showReasoning: tg.showReasoning !== false,
|
|
232
|
+
thoughtCollapse: tg.thoughtCollapse !== false,
|
|
233
|
+
locale: gw.resolveLocale(input),
|
|
234
|
+
})
|
|
235
|
+
scheduler.push(preview)
|
|
236
|
+
}
|
|
237
|
+
if (progressEnabled) {
|
|
238
|
+
scheduler.push(buildStreamPreview('', '', 3500, {
|
|
239
|
+
startTime: turnStartTime,
|
|
240
|
+
showReasoning: tg.showReasoning !== false,
|
|
241
|
+
thoughtCollapse: tg.thoughtCollapse !== false,
|
|
242
|
+
locale: gw.resolveLocale(input),
|
|
243
|
+
}))
|
|
163
244
|
}
|
|
164
|
-
if (progressEnabled) scheduler.push(buildStreamPreview('', ''))
|
|
165
245
|
} catch (e) {
|
|
166
246
|
gw.ctx.logger?.warn?.(`stream start: ${e.message}`)
|
|
167
247
|
stream = null
|
|
@@ -200,7 +280,15 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
200
280
|
if (progress) try { await progress.remove() } catch (err) { gw.logger?.debug?.('progress.remove failed after turn:', err?.message || err) }
|
|
201
281
|
progress = null
|
|
202
282
|
if (typeof react === 'function') react('').catch?.((e) => { gw.logger?.debug?.('react clear error:', e?.message || e) })
|
|
203
|
-
const
|
|
283
|
+
const rawText = stripImageUrls(collector.lastText || collector.streamText || collector.parts.join('\n\n'))
|
|
284
|
+
const parsedReasoning = parseReasoningStream(rawText, collector.reasoningText)
|
|
285
|
+
const cleanContent = stripReasoningPreamble(parsedReasoning.content || rawText)
|
|
286
|
+
let rawAnswer = cleanContent
|
|
287
|
+
if (parsedReasoning.hasThought && tg.showReasoning !== false) {
|
|
288
|
+
const quoteTag = tg.thoughtCollapse !== false ? '<blockquote expandable>' : '<blockquote>'
|
|
289
|
+
const thoughtHeader = String(gw.resolveLocale(input)).toLowerCase().startsWith('zh') ? '🧠 <i>思考过程:</i>' : '🧠 <i>Thought process:</i>'
|
|
290
|
+
rawAnswer = `${quoteTag}${thoughtHeader}\n${escapeHtml(parsedReasoning.thought)}</blockquote>\n\n${cleanContent}`
|
|
291
|
+
}
|
|
204
292
|
const processed = processDiagramsAndTables(rawAnswer, {
|
|
205
293
|
artifactPreviews: gw.tg().artifactPreviews !== false,
|
|
206
294
|
})
|
package/lib/gateway.js
CHANGED
|
@@ -9,7 +9,7 @@ import { sessionKey } from './topics.js'
|
|
|
9
9
|
import { resolveNamedHome, listHomes } from './homes.js'
|
|
10
10
|
import { assistantText } from './text.js'
|
|
11
11
|
import { collectAssistantParts } from './outbound.js'
|
|
12
|
-
import { extractTextDelta, extractToolName } from './stream.js'
|
|
12
|
+
import { extractTextDelta, extractReasoningDelta, extractToolName } from './stream.js'
|
|
13
13
|
import { createVoicePrefs } from './voice-prefs.js'
|
|
14
14
|
import { executeMessengerAsk, releaseCallbacks, rejectPendingAsk } from './ask.js'
|
|
15
15
|
import { createPersonaStore, BUILTIN_PERSONAS } from './personas.js'
|
|
@@ -209,16 +209,18 @@ export class Gateway {
|
|
|
209
209
|
for (const img of extra.images) collector.images.push(img)
|
|
210
210
|
} else if (event.type === 'assistant/chunk') {
|
|
211
211
|
const delta = extractTextDelta(event.data?.chunk || event.data)
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
collector.
|
|
212
|
+
const reasoningDelta = extractReasoningDelta(event.data?.chunk || event.data)
|
|
213
|
+
if (delta || reasoningDelta) {
|
|
214
|
+
if (delta) collector.streamText = (collector.streamText || '') + delta
|
|
215
|
+
if (reasoningDelta) collector.reasoningText = (collector.reasoningText || '') + reasoningDelta
|
|
216
|
+
collector.onStream?.(collector.streamText || '', collector.toolName, collector.reasoningText)
|
|
215
217
|
}
|
|
216
218
|
} else if (event.type === 'tool/call') {
|
|
217
219
|
collector.toolName = extractToolName(event.data || event) || collector.toolName
|
|
218
|
-
collector.onStream?.(collector.streamText || '', collector.toolName)
|
|
220
|
+
collector.onStream?.(collector.streamText || '', collector.toolName, collector.reasoningText)
|
|
219
221
|
} else if (event.type === 'tool/result') {
|
|
220
222
|
collector.toolName = ''
|
|
221
|
-
collector.onStream?.(collector.streamText || '', '')
|
|
223
|
+
collector.onStream?.(collector.streamText || '', '', collector.reasoningText)
|
|
222
224
|
} else if (event.type === 'turn/end') {
|
|
223
225
|
collector.reason = event.data?.reason || event.reason || event.data
|
|
224
226
|
}
|
|
@@ -430,8 +432,13 @@ export class Gateway {
|
|
|
430
432
|
if (body.startsWith('/')) {
|
|
431
433
|
const commandsService = this.ctx.get ? this.ctx.get('commands') : this.ctx?.commands
|
|
432
434
|
if (commandsService && typeof commandsService.execute === 'function') {
|
|
435
|
+
const cmdAbort = chat.abort || new AbortController()
|
|
436
|
+
const createdAbort = !chat.abort
|
|
437
|
+
if (createdAbort) {
|
|
438
|
+
chat.abort = cmdAbort
|
|
439
|
+
}
|
|
433
440
|
try {
|
|
434
|
-
const outcome = await commandsService.execute(chat.agent, cleanBody, attachments || [],
|
|
441
|
+
const outcome = await commandsService.execute(chat.agent, cleanBody, attachments || [], cmdAbort.signal)
|
|
435
442
|
if (outcome !== undefined) {
|
|
436
443
|
const replyText = outcome?.result?.kind === 'text'
|
|
437
444
|
? outcome.result.text
|
|
@@ -446,11 +453,15 @@ export class Gateway {
|
|
|
446
453
|
return
|
|
447
454
|
}
|
|
448
455
|
} catch (cmdErr) {
|
|
449
|
-
if (
|
|
456
|
+
if (cmdAbort.signal.aborted) return
|
|
450
457
|
const errMsg = cmdErr instanceof Error ? cmdErr.message : String(cmdErr)
|
|
451
458
|
this.ctx.logger?.warn?.(`dsh-messenger-gateway: runtime command: ${errMsg}`)
|
|
452
459
|
try { await reply(t('msg.exception', { message: errMsg }, this.resolveLocale(input))) } catch (repErr) { this.recordApiFailure('reply.exception', repErr) }
|
|
453
460
|
return
|
|
461
|
+
} finally {
|
|
462
|
+
if (createdAbort && chat.abort === cmdAbort) {
|
|
463
|
+
chat.abort = undefined
|
|
464
|
+
}
|
|
454
465
|
}
|
|
455
466
|
}
|
|
456
467
|
}
|
package/lib/index.js
CHANGED
|
@@ -53,8 +53,13 @@ function publicConfig(cfg, gw, ctx) {
|
|
|
53
53
|
homes: listHomes(cfg.telegram),
|
|
54
54
|
pairingEnabled: cfg.telegram.pairingEnabled,
|
|
55
55
|
streaming: cfg.telegram.streaming,
|
|
56
|
+
streamEditIntervalMs: cfg.telegram.streamEditIntervalMs,
|
|
56
57
|
progressEnabled: cfg.telegram.progressEnabled,
|
|
58
|
+
showReasoning: cfg.telegram.showReasoning,
|
|
59
|
+
thoughtCollapse: cfg.telegram.thoughtCollapse,
|
|
57
60
|
approvalsEnabled: cfg.telegram.approvalsEnabled,
|
|
61
|
+
approvalsSensitivity: cfg.telegram.approvalsSensitivity,
|
|
62
|
+
approvalsTimeoutMs: cfg.telegram.approvalsTimeoutMs,
|
|
58
63
|
groupsEnabled: cfg.telegram.groupsEnabled,
|
|
59
64
|
groupRequireMention: cfg.telegram.groupRequireMention,
|
|
60
65
|
reactionsEnabled: cfg.telegram.reactionsEnabled,
|
package/lib/locales/en.js
CHANGED
|
@@ -58,10 +58,12 @@ export const en = {
|
|
|
58
58
|
'doc.hint': '[Document attached: {name}]',
|
|
59
59
|
|
|
60
60
|
// Interactive buttons & ask
|
|
61
|
-
'ask.confirm_title': '⚠️ Confirmation Required
|
|
62
|
-
'ask.allow_once': '✅
|
|
63
|
-
'ask.allow_session': '
|
|
64
|
-
'ask.deny': '❌
|
|
61
|
+
'ask.confirm_title': '⚠️ <b>Action Confirmation Required</b>\nTool: <code>{tool}</code>{reason}',
|
|
62
|
+
'ask.allow_once': '✅ Approve',
|
|
63
|
+
'ask.allow_session': '⚡ Trust Session',
|
|
64
|
+
'ask.deny': '❌ Reject',
|
|
65
|
+
'ask.steer': '✏️ Steer / Amend',
|
|
66
|
+
'ask.steer_prompt': '✏️ Tool execution rejected. Reply with your instructions or corrections for the agent:',
|
|
65
67
|
'ask.chose': 'Chose: {choice}',
|
|
66
68
|
'ask.done': 'Done',
|
|
67
69
|
'ask.cancel': 'Cancel',
|
package/lib/locales/zh.js
CHANGED
|
@@ -58,10 +58,12 @@ export const zh = {
|
|
|
58
58
|
'doc.hint': '[附加文件: {name}]',
|
|
59
59
|
|
|
60
60
|
// Interactive buttons & ask
|
|
61
|
-
'ask.confirm_title': '⚠️
|
|
62
|
-
'ask.allow_once': '✅
|
|
63
|
-
'ask.allow_session': '
|
|
61
|
+
'ask.confirm_title': '⚠️ <b>需要操作授权确认</b>\n工具: <code>{tool}</code>{reason}',
|
|
62
|
+
'ask.allow_once': '✅ 批准',
|
|
63
|
+
'ask.allow_session': '⚡ 本会话信任',
|
|
64
64
|
'ask.deny': '❌ 拒绝',
|
|
65
|
+
'ask.steer': '✏️ 修改 / 调整',
|
|
66
|
+
'ask.steer_prompt': '✏️ 已拒绝工具执行。请回复您对智能体的指示或修改要求:',
|
|
65
67
|
'ask.chose': '已选择: {choice}',
|
|
66
68
|
'ask.done': '完成',
|
|
67
69
|
'ask.cancel': '取消',
|
package/lib/stream.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { escapeHtml } from './telegram-format.js'
|
|
2
|
+
|
|
1
3
|
/** Helpers for Telegram streaming edits + progress. */
|
|
2
4
|
|
|
3
5
|
export function extractTextDelta(chunk) {
|
|
@@ -23,14 +25,136 @@ export function formatProgressLine(toolName, locale = 'en') {
|
|
|
23
25
|
return `🔧 ${toolName}…`
|
|
24
26
|
}
|
|
25
27
|
|
|
26
|
-
export function
|
|
28
|
+
export function extractReasoningDelta(chunk) {
|
|
29
|
+
if (!chunk || typeof chunk !== 'object') return ''
|
|
30
|
+
if ((chunk.type === 'reasoning-delta' || chunk.type === 'thought-delta') && typeof chunk.text === 'string') return chunk.text
|
|
31
|
+
if (chunk.type === 'reasoning' && typeof chunk.text === 'string') return chunk.text
|
|
32
|
+
if (typeof chunk.reasoning_content === 'string') return chunk.reasoning_content
|
|
33
|
+
if (typeof chunk.reasoning === 'string') return chunk.reasoning
|
|
34
|
+
if (typeof chunk.thought === 'string') return chunk.thought
|
|
35
|
+
return ''
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function parseReasoningStream(streamText = '', deltaReasoning = '') {
|
|
39
|
+
const raw = String(streamText || '')
|
|
40
|
+
let thought = String(deltaReasoning || '')
|
|
41
|
+
let content = raw
|
|
42
|
+
let isThinking = false
|
|
43
|
+
let isComplete = false
|
|
44
|
+
|
|
45
|
+
const completeTagRegex = /<(?:think|thought)>([\s\S]*?)<\/(?:think|thought)>|\[THOUGHT\]([\s\S]*?)\[\/THOUGHT\]|\|begin_of_thought\|([\s\S]*?)\|end_of_thought\|/gi
|
|
46
|
+
|
|
47
|
+
let match
|
|
48
|
+
const thoughtsFromTags = []
|
|
49
|
+
while ((match = completeTagRegex.exec(raw)) !== null) {
|
|
50
|
+
const t = match[1] ?? match[2] ?? match[3] ?? ''
|
|
51
|
+
thoughtsFromTags.push(t)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (thoughtsFromTags.length > 0) {
|
|
55
|
+
content = raw.replace(completeTagRegex, '')
|
|
56
|
+
thought = (thought ? thought + '\n' : '') + thoughtsFromTags.join('\n')
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const openTagRegex = /<(?:think|thought)>([\s\S]*)$|\[THOUGHT\]([\s\S]*)$|\|begin_of_thought\|([\s\S]*)$/i
|
|
60
|
+
const openMatch = content.match(openTagRegex)
|
|
61
|
+
if (openMatch) {
|
|
62
|
+
const unclosedThought = openMatch[1] ?? openMatch[2] ?? openMatch[3] ?? ''
|
|
63
|
+
thought = (thought ? thought + '\n' : '') + unclosedThought
|
|
64
|
+
content = content.replace(openTagRegex, '')
|
|
65
|
+
isThinking = true
|
|
66
|
+
isComplete = false
|
|
67
|
+
} else if (deltaReasoning && !content.trim()) {
|
|
68
|
+
isThinking = true
|
|
69
|
+
isComplete = false
|
|
70
|
+
} else {
|
|
71
|
+
isComplete = Boolean(thought.trim()) && Boolean(content.trim())
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
thought: thought.trim(),
|
|
76
|
+
content: content.trim(),
|
|
77
|
+
isThinking,
|
|
78
|
+
isComplete: !isThinking && isComplete,
|
|
79
|
+
hasThought: Boolean(thought.trim()),
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function buildStreamPreview(streamText, toolName, maxLen = 3500, options = {}) {
|
|
84
|
+
const parsed = parseReasoningStream(streamText, options?.reasoningText)
|
|
85
|
+
const showReasoning = options?.showReasoning !== false
|
|
86
|
+
const thoughtCollapse = options?.thoughtCollapse !== false
|
|
87
|
+
const locale = options?.locale || 'en'
|
|
88
|
+
const elapsedSec = options?.startTime ? Math.max(1, Math.round((Date.now() - options.startTime) / 1000)) : 0
|
|
89
|
+
const timeStr = elapsedSec > 0 ? ` (${elapsedSec}s)` : ''
|
|
90
|
+
|
|
91
|
+
const toolHead = toolName ? `${formatProgressLine(toolName, locale)}\n\n` : ''
|
|
92
|
+
|
|
93
|
+
if (parsed.isThinking) {
|
|
94
|
+
if (!showReasoning || !parsed.thought) {
|
|
95
|
+
const thinkingHeader = toolName
|
|
96
|
+
? formatProgressLine(toolName, locale)
|
|
97
|
+
: (String(locale).toLowerCase().startsWith('zh') ? `⏳ 思考中…${timeStr}` : `⏳ Thinking…${timeStr}`)
|
|
98
|
+
const combined = `${thinkingHeader}\n\n${parsed.content || '…'}`.trim()
|
|
99
|
+
return combined.length <= maxLen ? combined : combined.slice(0, maxLen - 1) + '…'
|
|
100
|
+
}
|
|
101
|
+
const header = toolName
|
|
102
|
+
? `🔧 <b>${escapeHtml(toolName)}…</b>`
|
|
103
|
+
: (String(locale).toLowerCase().startsWith('zh') ? `🧠 <b>思考中…</b><i>${timeStr}</i>` : `🧠 <b>Thinking…</b><i>${timeStr}</i>`)
|
|
104
|
+
const available = Math.max(200, maxLen - header.length - 100)
|
|
105
|
+
let thoughtText = parsed.thought
|
|
106
|
+
if (thoughtText.length > available) {
|
|
107
|
+
thoughtText = '…' + thoughtText.slice(-(available - 1))
|
|
108
|
+
}
|
|
109
|
+
const quote = `<blockquote>${escapeHtml(thoughtText)}</blockquote>`
|
|
110
|
+
const body = parsed.content ? `\n\n${escapeHtml(parsed.content)}` : ''
|
|
111
|
+
const combined = `${header}\n${quote}${body}`
|
|
112
|
+
return combined.length <= maxLen ? combined : combined.slice(0, maxLen - 1) + '…'
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (parsed.hasThought) {
|
|
116
|
+
if (showReasoning) {
|
|
117
|
+
const quoteTag = thoughtCollapse ? '<blockquote expandable>' : '<blockquote>'
|
|
118
|
+
const thoughtHeader = String(locale).toLowerCase().startsWith('zh') ? `🧠 <i>思考过程${timeStr}:</i>` : `🧠 <i>Thought process${timeStr}:</i>`
|
|
119
|
+
const contentText = parsed.content || '…'
|
|
120
|
+
const contentBudget = Math.min(2500, maxLen - 300)
|
|
121
|
+
const thoughtBudget = Math.max(200, maxLen - contentBudget - 150)
|
|
122
|
+
let thoughtText = parsed.thought
|
|
123
|
+
if (thoughtText.length > thoughtBudget) {
|
|
124
|
+
thoughtText = thoughtText.slice(0, thoughtBudget - 1) + '…'
|
|
125
|
+
}
|
|
126
|
+
const quote = `${quoteTag}${thoughtHeader}\n${escapeHtml(thoughtText)}</blockquote>`
|
|
127
|
+
const combined = `${toolHead}${quote}\n\n${escapeHtml(contentText)}`.trim()
|
|
128
|
+
return combined.length <= maxLen ? combined : combined.slice(0, maxLen - 1) + '…'
|
|
129
|
+
} else {
|
|
130
|
+
const contentText = parsed.content || '…'
|
|
131
|
+
const combined = `${toolHead}${escapeHtml(contentText)}`.trim()
|
|
132
|
+
return combined.length <= maxLen ? combined : combined.slice(0, maxLen - 1) + '…'
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
27
136
|
const body = String(streamText || '').trimEnd()
|
|
28
|
-
const
|
|
29
|
-
const combined = head + (body || '…')
|
|
137
|
+
const combined = toolHead + (body || '…')
|
|
30
138
|
if (combined.length <= maxLen) return combined
|
|
31
139
|
return combined.slice(0, maxLen - 1) + '…'
|
|
32
140
|
}
|
|
33
141
|
|
|
142
|
+
export function formatReasoningFinal(rawText, deltaReasoning, options = {}) {
|
|
143
|
+
const showReasoning = options?.showReasoning !== false
|
|
144
|
+
const thoughtCollapse = options?.thoughtCollapse !== false
|
|
145
|
+
const locale = options?.locale || 'en'
|
|
146
|
+
const parsed = parseReasoningStream(rawText, deltaReasoning)
|
|
147
|
+
|
|
148
|
+
if (!parsed.hasThought || !showReasoning) {
|
|
149
|
+
return parsed.content || String(rawText || '')
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const quoteTag = thoughtCollapse ? '<blockquote expandable>' : '<blockquote>'
|
|
153
|
+
const thoughtHeader = String(locale).toLowerCase().startsWith('zh') ? '🧠 <i>思考过程:</i>' : '🧠 <i>Thought process:</i>'
|
|
154
|
+
const thoughtBlock = `${quoteTag}${thoughtHeader}\n${escapeHtml(parsed.thought)}</blockquote>\n\n`
|
|
155
|
+
return `${thoughtBlock}${parsed.content}`
|
|
156
|
+
}
|
|
157
|
+
|
|
34
158
|
export function parseRetryAfter(err) {
|
|
35
159
|
if (!err) return 0
|
|
36
160
|
const msg = err.message || String(err)
|
|
@@ -121,4 +245,4 @@ export function startTypingHeartbeat(typingFn, intervalMs = 4000, logger = null)
|
|
|
121
245
|
active = false
|
|
122
246
|
clearInterval(timer)
|
|
123
247
|
}
|
|
124
|
-
}
|
|
248
|
+
}
|
package/lib/telegram-format.js
CHANGED
|
@@ -35,7 +35,7 @@ export function decodeHtmlEntities(text) {
|
|
|
35
35
|
return String(text ?? '').replace(/&(lt|gt|quot|#39|apos|nbsp);|&/g, (match) => ENTITIES[match] ?? '&')
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
const SAFE_TAG_ANY_RE = new RegExp(`<a\\s+href="([^"]{1,512})"\\s*>|<(/?)(${SAFE_TAG_NAMES}|a)>`, 'gi')
|
|
38
|
+
const SAFE_TAG_ANY_RE = new RegExp(`<a\\s+href="([^"]{1,512})"\\s*>|<blockquote(\\s+expandable)?>|<(/?)(${SAFE_TAG_NAMES}|a)>`, 'gi')
|
|
39
39
|
|
|
40
40
|
/**
|
|
41
41
|
* Вынимает в слоты только сбалансированные теги из белого списка. Незакрытый
|
|
@@ -44,13 +44,17 @@ const SAFE_TAG_ANY_RE = new RegExp(`<a\\s+href="([^"]{1,512})"\\s*>|<(/?)(${SAFE
|
|
|
44
44
|
*/
|
|
45
45
|
function protectSafeTags(text, stash) {
|
|
46
46
|
const open = []
|
|
47
|
-
return text.replace(SAFE_TAG_ANY_RE, (match, href, closing, rawName) => {
|
|
48
|
-
const tag = String(rawName || 'a').toLowerCase()
|
|
47
|
+
return text.replace(SAFE_TAG_ANY_RE, (match, href, expandable, closing, rawName) => {
|
|
49
48
|
if (href !== undefined) {
|
|
50
49
|
if (!isSafeUrl(href)) return match
|
|
51
|
-
open.push(
|
|
50
|
+
open.push('a')
|
|
51
|
+
return stash(match)
|
|
52
|
+
}
|
|
53
|
+
if (expandable !== undefined) {
|
|
54
|
+
open.push('blockquote')
|
|
52
55
|
return stash(match)
|
|
53
56
|
}
|
|
57
|
+
const tag = String(rawName || 'a').toLowerCase()
|
|
54
58
|
if (closing) {
|
|
55
59
|
const index = open.lastIndexOf(tag)
|
|
56
60
|
if (index === -1) return match
|
|
@@ -67,6 +71,7 @@ export function stripSafeTags(text) {
|
|
|
67
71
|
return decodeHtmlEntities(text)
|
|
68
72
|
.replace(SAFE_ANCHOR_RE, '')
|
|
69
73
|
.replace(/<\/a>/gi, '')
|
|
74
|
+
.replace(/<blockquote\b[^>]*>/gi, '')
|
|
70
75
|
.replace(SAFE_TAG_RE, '')
|
|
71
76
|
}
|
|
72
77
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodandready/dsh-messenger-gateway",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.24",
|
|
4
4
|
"description": "Telegram messenger bridge for DeepSeek Harness: sessions, steer, homes, inline asks, notify bridge, and optional TTS voice notes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|