@goodandready/dsh-messenger-gateway 0.4.23 → 0.4.25

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/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,12 @@ 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
+ mediaGroupDebounceMs: z.number().default(650),
40
+ showReasoning: z.boolean().default(true).description('Display model reasoning/thought process in chat'),
41
+ thoughtCollapse: z.boolean().default(true).description('Collapse finished thoughts into expandable blockquote'),
39
42
  approvalsEnabled: z.boolean().default(true),
43
+ approvalsSensitivity: z.union([z.const('all'), z.const('mutations'), z.const('disabled')]).default('mutations').description('Sensitivity level: mutations only, all tool calls, or disabled'),
44
+ approvalsTimeoutMs: z.number().default(300000).description('Timeout in ms before auto-rejecting pending approval (default 5m)'),
40
45
  groupsEnabled: z.boolean().default(true).description('Process group/supergroup messages'),
41
46
  groupRequireMention: z.boolean().default(true).description('In groups, only respond to @mention, reply-to-bot, or /commands'),
42
47
  reactionsEnabled: z.boolean().default(true).description('React with 👀 while processing a turn'),
package/lib/documents.js CHANGED
@@ -14,7 +14,11 @@ export function formatInboundDocument(att, parsed = null) {
14
14
 
15
15
  if (parsed?.text) {
16
16
  const truncNote = parsed.truncated ? ' (content truncated)' : ''
17
- base += `\n\n[Extracted text from file${truncNote}]:\n\`\`\`\n${parsed.text}\n\`\`\``
17
+ if (parsed.type === 'zip') {
18
+ base += `\n\n[Extracted archive structure and code${truncNote}]:\n\`\`\`\n${parsed.text}\n\`\`\``
19
+ } else {
20
+ base += `\n\n[Extracted text from file${truncNote}]:\n\`\`\`\n${parsed.text}\n\`\`\``
21
+ }
18
22
  }
19
23
  return base
20
24
  }
@@ -127,6 +131,160 @@ export function extractDocxText(buffer) {
127
131
  return ''
128
132
  }
129
133
 
134
+
135
+ const IGNORED_ZIP_DIRS = new Set([
136
+ "node_modules", ".git", ".turbo", "dist", "build", "vendor", "__pycache__", ".venv", ".idea", ".vscode",
137
+ ])
138
+
139
+ const IGNORED_ZIP_FILES = new Set([
140
+ "package-lock.json", "pnpm-lock.yaml", "yarn.lock", "cargo.lock", "gemfile.lock", "poetry.lock",
141
+ ])
142
+
143
+ const BINARY_ZIP_EXTS = new Set([
144
+ ".png", ".jpg", ".jpeg", ".gif", ".ico", ".webp", ".pdf", ".mp3", ".mp4", ".zip", ".tar", ".gz", ".7z", ".rar",
145
+ ".exe", ".dll", ".so", ".dylib", ".class", ".pyc", ".o", ".a", ".woff", ".woff2", ".ttf", ".eot",
146
+ ])
147
+
148
+ export function isSafeZipPath(name) {
149
+ if (!name || typeof name !== "string") return false
150
+ const normalized = name.replace(/\\/g, "/")
151
+ if (normalized.startsWith("/") || /^[a-zA-Z]:/.test(normalized)) return false
152
+ const parts = normalized.split("/")
153
+ if (parts.includes("..") || parts.includes(".")) return false
154
+ return true
155
+ }
156
+
157
+ export function extractZipEntries(buffer, opts = {}) {
158
+ const {
159
+ maxEntries = 100,
160
+ maxUncompressedBytes = 10 * 1024 * 1024,
161
+ maxFileBytes = 512 * 1024,
162
+ } = opts
163
+
164
+ // Locate End of Central Directory Record (EOCD: 0x06054b50)
165
+ let eocdOffset = -1
166
+ for (let i = buffer.length - 22; i >= Math.max(0, buffer.length - 65557); i--) {
167
+ if (buffer[i] === 0x50 && buffer[i + 1] === 0x4b && buffer[i + 2] === 0x05 && buffer[i + 3] === 0x06) {
168
+ eocdOffset = i
169
+ break
170
+ }
171
+ }
172
+ if (eocdOffset === -1) {
173
+ throw new Error("Invalid zip: End of Central Directory signature not found")
174
+ }
175
+
176
+ const totalEntries = buffer.readUInt16LE(eocdOffset + 10)
177
+ const cdOffset = buffer.readUInt32LE(eocdOffset + 16)
178
+
179
+ const entries = []
180
+ let pos = cdOffset
181
+ let totalUncompressed = 0
182
+
183
+ for (let idx = 0; idx < totalEntries && idx < maxEntries; idx++) {
184
+ if (pos + 46 > buffer.length) break
185
+ if (buffer.readUInt32LE(pos) !== 0x02014b50) break
186
+
187
+ const compMethod = buffer.readUInt16LE(pos + 10)
188
+ const compSize = buffer.readUInt32LE(pos + 20)
189
+ const uncompSize = buffer.readUInt32LE(pos + 24)
190
+ const nameLen = buffer.readUInt16LE(pos + 28)
191
+ const extraLen = buffer.readUInt16LE(pos + 30)
192
+ const commentLen = buffer.readUInt16LE(pos + 32)
193
+ const localOffset = buffer.readUInt32LE(pos + 42)
194
+
195
+ if (pos + 46 + nameLen > buffer.length) break
196
+ const rawName = buffer.toString("utf8", pos + 46, pos + 46 + nameLen).replace(/\\/g, "/")
197
+ pos += 46 + nameLen + extraLen + commentLen
198
+
199
+ if (rawName.endsWith("/")) continue
200
+ if (!isSafeZipPath(rawName)) continue
201
+
202
+ totalUncompressed += uncompSize
203
+ if (totalUncompressed > maxUncompressedBytes) {
204
+ break
205
+ }
206
+
207
+ const parts = rawName.split("/")
208
+ if (parts.some((p) => IGNORED_ZIP_DIRS.has(p.toLowerCase()))) continue
209
+ const base = parts[parts.length - 1].toLowerCase()
210
+ if (IGNORED_ZIP_FILES.has(base)) continue
211
+ const ext = extname(base).toLowerCase()
212
+ if (BINARY_ZIP_EXTS.has(ext)) continue
213
+
214
+ if (localOffset + 30 > buffer.length) continue
215
+ if (buffer.readUInt32LE(localOffset) !== 0x04034b50) continue
216
+ const localNameLen = buffer.readUInt16LE(localOffset + 26)
217
+ const localExtraLen = buffer.readUInt16LE(localOffset + 28)
218
+ const dataStart = localOffset + 30 + localNameLen + localExtraLen
219
+
220
+ if (dataStart + compSize > buffer.length) continue
221
+ const compData = buffer.subarray(dataStart, dataStart + compSize)
222
+
223
+ let content = null
224
+ const canExtract = uncompSize <= maxFileBytes && (TEXT_INJECT_EXTS.has(ext) || !ext)
225
+ if (canExtract) {
226
+ try {
227
+ if (compMethod === 8) {
228
+ content = inflateRawSync(compData).toString("utf8")
229
+ } else if (compMethod === 0) {
230
+ content = compData.toString("utf8")
231
+ }
232
+ } catch {
233
+ content = null
234
+ }
235
+ }
236
+
237
+ entries.push({
238
+ name: rawName,
239
+ size: uncompSize,
240
+ ext,
241
+ content,
242
+ })
243
+ }
244
+
245
+ return { entries, totalInArchive: totalEntries, totalUncompressed }
246
+ }
247
+
248
+ export function formatZipSummary(extracted, maxBytes = 64 * 1024) {
249
+ const { entries, totalInArchive } = extracted
250
+ if (!entries.length) {
251
+ return {
252
+ text: `[Archive contains no readable code or text files (${totalInArchive} entries total)]`,
253
+ fileCount: 0,
254
+ truncated: false,
255
+ }
256
+ }
257
+
258
+ let summary = `Archive structure (${entries.length} text files extracted, ${totalInArchive} total entries):\n`
259
+ for (const entry of entries) {
260
+ summary += ` - ${entry.name} (${entry.size} B)\n`
261
+ }
262
+ summary += "\n"
263
+
264
+ let truncated = false
265
+ for (const entry of entries) {
266
+ if (!entry.content) continue
267
+ const header = `--- File: ${entry.name} ---\n`
268
+ const fileBlock = header + entry.content.trim() + "\n\n"
269
+ if (summary.length + fileBlock.length > maxBytes) {
270
+ const remaining = maxBytes - summary.length - header.length - 40
271
+ if (remaining > 100) {
272
+ summary += header + entry.content.slice(0, remaining).trim() + "\n... [File content truncated]\n\n"
273
+ }
274
+ summary += `[Archive ingestion truncated: remaining ${entries.length} files omitted to fit context]\n`
275
+ truncated = true
276
+ break
277
+ }
278
+ summary += fileBlock
279
+ }
280
+
281
+ return {
282
+ text: summary.trim(),
283
+ fileCount: entries.length,
284
+ truncated,
285
+ }
286
+ }
287
+
130
288
  export async function parseDocument(filePath, opts = {}) {
131
289
  const { maxBytes = 64 * 1024 } = opts
132
290
  const ext = extname(filePath).toLowerCase()
@@ -147,7 +305,7 @@ export async function parseDocument(filePath, opts = {}) {
147
305
  const { bytesRead } = await handle.read(buf, 0, toRead, 0)
148
306
  rawBuffer = buf.subarray(0, bytesRead)
149
307
  truncated = st.size > toRead
150
- } else if (ext === '.pdf' || ext === '.docx') {
308
+ } else if (ext === '.pdf' || ext === '.docx' || ext === '.zip') {
151
309
  const maxBinary = Math.max(maxBytes * 4, 10 * 1024 * 1024)
152
310
  if (st.size > maxBinary) {
153
311
  return { parsed: false, error: `File size (${st.size} bytes) exceeds safety parse limit` }
@@ -165,7 +323,13 @@ export async function parseDocument(filePath, opts = {}) {
165
323
  let text = ''
166
324
  let parsedType = 'text'
167
325
 
168
- if (ext === '.pdf') {
326
+ if (ext === '.zip') {
327
+ parsedType = 'zip'
328
+ const extracted = extractZipEntries(rawBuffer, opts)
329
+ const formatted = formatZipSummary(extracted, maxBytes)
330
+ text = formatted.text
331
+ truncated = formatted.truncated
332
+ } else if (ext === '.pdf') {
169
333
  parsedType = 'pdf'
170
334
  text = extractPdfText(rawBuffer)
171
335
  } else if (ext === '.docx') {
@@ -5,15 +5,16 @@ import { getPersona } from './personas.js'
5
5
  import { MESSENGER_RELAY_INSTRUCTION, stripReasoningPreamble, splitText } from './text.js'
6
6
  import { formatInboundDocument, documentOnlyHint, parseDocument } from './documents.js'
7
7
  import { t } from './locales/index.js'
8
- import { processDiagramsAndTables } from './artifacts.js'
8
+ import { processDiagramsAndTables, processDiagramsAndTablesAsync } from './artifacts.js'
9
9
  import { prepareTtsText, toTelegramVoiceFile } from './tts.js'
10
10
  import { shouldSpeakReply } from './voice-prefs.js'
11
11
  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 async function answerApproval(gw, chatKeyValue, req, next) {
34
- try {
35
- const chat = gw.chats.get(chatKeyValue)
36
- if (!chat?.target) return next()
37
- const tool = req.toolName || 'tool'
38
- if (chat.sessionAllowlist?.has(tool)) {
39
- return 'allowed-once'
40
- }
41
- const locale = gw.resolveLocale(chat.target)
42
- const reason = req.reason ? `\n<i>${req.reason}</i>` : ''
43
- let detail = ''
44
- if (req.input && typeof req.input === 'object') {
45
- try {
46
- const jsonStr = JSON.stringify(req.input, null, 2)
47
- detail = `\n<pre><code>${jsonStr.slice(0, 500)}</code></pre>`
48
- } catch { /* safe JSON serialization fallback */ }
49
- }
50
- const text = t('ask.confirm_title', { tool, reason: reason + detail }, locale)
51
- const buttons = [
52
- [
53
- { id: 'allow_once', text: t('ask.allow_once', {}, locale) },
54
- { id: 'allow_session', text: t('ask.allow_session', {}, locale) },
55
- { id: 'deny', text: t('ask.deny', {}, locale) },
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
- const result = await gw.messengerAsk(chat.target, { text, buttons }, 300_000)
59
- if (result?.buttonId === 'allow_once' || result?.buttonId === 'allow') return 'allowed-once'
60
- if (result?.buttonId === 'allow_session') {
61
- if (!chat.sessionAllowlist) chat.sessionAllowlist = new Set()
62
- chat.sessionAllowlist.add(tool)
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
- if (result?.buttonId === 'deny') return 'rejected'
66
- return next()
67
- } catch {
68
- return next()
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
- scheduler = createEditScheduler((text) => stream.edit(text), Number(tg.streamEditIntervalMs) || 1200, 250, gw.logger)
159
- collector.onStream = (text, toolName) => {
160
- if (text) stopTyping()
161
- if (!progressEnabled && !text) return
162
- scheduler.push(buildStreamPreview(text, progressEnabled ? toolName : ''))
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,8 +280,16 @@ 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 rawAnswer = stripReasoningPreamble(stripImageUrls(collector.lastText || collector.streamText || collector.parts.join('\n\n')))
204
- const processed = processDiagramsAndTables(rawAnswer, {
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
+ }
292
+ const processed = await processDiagramsAndTablesAsync(rawAnswer, {
205
293
  artifactPreviews: gw.tg().artifactPreviews !== false,
206
294
  })
207
295
  const answer = processed.text
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
- if (delta) {
213
- collector.streamText = (collector.streamText || '') + delta
214
- collector.onStream?.(collector.streamText, collector.toolName)
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
  }
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\nTool: <code>{tool}</code>{reason}',
62
- 'ask.allow_once': '✅ Allow Once',
63
- 'ask.allow_session': '🛡️ Allow for Session',
64
- 'ask.deny': '❌ 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': '⚠️ 需要授权确认\n工具: <code>{tool}</code>{reason}',
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': '取消',