@goodandready/dsh-messenger-gateway 0.4.32 → 0.4.34
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/discord.js +1 -1
- package/lib/adapters/telegram-inbound.js +1 -1
- package/lib/adapters/telegram.js +4 -5
- package/lib/artifacts.js +1 -1
- package/lib/ask.js +1 -1
- package/lib/client.js +0 -13
- package/lib/file-manager.js +8 -7
- package/lib/forum-mirror.js +1 -1
- package/lib/gateway-callbacks.js +8 -7
- package/lib/gateway-commands.js +46 -23
- package/lib/gateway-turn.js +9 -8
- package/lib/gateway.js +33 -15
- package/lib/http.js +2 -2
- package/lib/index.js +0 -1
- package/lib/memory-brain.js +6 -1
- package/lib/messenger-api.js +17 -17
- package/lib/pairing.js +3 -2
- package/lib/personas.js +1 -0
- package/lib/proxy.js +5 -3
- package/lib/session-ops.js +1 -1
- package/lib/telegram-errors.js +0 -0
- package/lib/tts.js +1 -0
- package/lib/voice-prefs.js +1 -0
- package/lib/webapp.js +1 -0
- package/lib/workspace.js +2 -1
- package/package.json +12 -3
package/lib/adapters/discord.js
CHANGED
|
@@ -64,7 +64,7 @@ export class DiscordAdapter {
|
|
|
64
64
|
this.stopped = true
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
async sendTo(channelId, payload,
|
|
67
|
+
async sendTo(channelId, payload, _opts = {}) {
|
|
68
68
|
if (this.stopped) throw new Error('discord adapter stopped')
|
|
69
69
|
const body = typeof payload === 'string' ? { text: payload } : (payload || {})
|
|
70
70
|
const text = String(body.text || '')
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
IMAGE_EXT_TO_MIME, VIDEO_EXT_TO_MIME, classifyDocument,
|
|
4
4
|
extOf, TELEGRAM_MAX_DOC_BYTES,
|
|
5
5
|
} from '../media.js'
|
|
6
|
-
import { TEXT_INJECT_EXTS,
|
|
6
|
+
import { TEXT_INJECT_EXTS, } from '../documents.js'
|
|
7
7
|
|
|
8
8
|
export async function extractTelegramInboundMedia(adapter, msg, initialText, maxDocBytes = TELEGRAM_MAX_DOC_BYTES, maxTextInjectBytes = 100 * 1024) {
|
|
9
9
|
let text = initialText || ''
|
package/lib/adapters/telegram.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises'
|
|
2
2
|
import {
|
|
3
|
-
|
|
3
|
+
cacheName,
|
|
4
4
|
extOf, saveToCache, safeName, TELEGRAM_MAX_DOC_BYTES,
|
|
5
5
|
} from '../media.js'
|
|
6
|
-
import { TEXT_INJECT_EXTS } from '../documents.js'
|
|
7
6
|
import { splitText } from '../text.js'
|
|
8
7
|
import { prepareTelegramText } from '../telegram-format.js'
|
|
9
8
|
import { normalizeTelegramCommands } from '../commands.js'
|
|
@@ -363,7 +362,7 @@ export class TelegramAdapter {
|
|
|
363
362
|
editMessage: async (text, replyMarkup) => {
|
|
364
363
|
const { text: formatted, parseMode } = this.formatOutgoingText(text)
|
|
365
364
|
const params = { chat_id: chatId, message_id: messageId, text: formatted, reply_markup: replyMarkup }
|
|
366
|
-
if (parseMode) params.parse_mode = parseMode
|
|
365
|
+
if (parseMode) /** @type {any} */ (params).parse_mode = parseMode
|
|
367
366
|
try {
|
|
368
367
|
return await this.call('editMessageText', params)
|
|
369
368
|
} catch (err) {
|
|
@@ -687,7 +686,7 @@ export class TelegramAdapter {
|
|
|
687
686
|
const { text: formatted, parseMode } = this.formatOutgoingText(String(text || ''), payload)
|
|
688
687
|
const chunk = splitText(formatted, TELEGRAM_MAX)[0] || '…'
|
|
689
688
|
const params = { chat_id: chatId, message_id: messageId, text: chunk }
|
|
690
|
-
if (parseMode) params.parse_mode = parseMode
|
|
689
|
+
if (parseMode) /** @type {any} */ (params).parse_mode = parseMode
|
|
691
690
|
try {
|
|
692
691
|
await this.call('editMessageText', params)
|
|
693
692
|
} catch (err) {
|
|
@@ -760,7 +759,7 @@ export class TelegramAdapter {
|
|
|
760
759
|
reply_markup: i === 0 ? effectiveMarkup : undefined,
|
|
761
760
|
...telegramThreadParams(threadId),
|
|
762
761
|
}
|
|
763
|
-
if (parseMode) params.parse_mode = parseMode
|
|
762
|
+
if (parseMode) /** @type {any} */ (params).parse_mode = parseMode
|
|
764
763
|
try {
|
|
765
764
|
await this.sendWithRetry('sendMessage', params)
|
|
766
765
|
} catch (err) {
|
package/lib/artifacts.js
CHANGED
|
@@ -404,7 +404,7 @@ export function processDiagramsAndTables(rawText, options = {}) {
|
|
|
404
404
|
}
|
|
405
405
|
|
|
406
406
|
export async function processDiagramsAndTablesAsync(rawText, options = {}) {
|
|
407
|
-
const { artifactPreviews = true, artifactStore = null, chatId = null
|
|
407
|
+
const { artifactPreviews = true, artifactStore = null, chatId = null } = options
|
|
408
408
|
const createdArtifacts = []
|
|
409
409
|
let text = String(rawText || "")
|
|
410
410
|
const files = []
|
package/lib/ask.js
CHANGED
|
@@ -12,7 +12,7 @@ export function makeAskToken() {
|
|
|
12
12
|
export function buildCallbackData(token, buttonId) {
|
|
13
13
|
const data = `${token}:${buttonId}`
|
|
14
14
|
if (data.length > TELEGRAM_CALLBACK_DATA_MAX) {
|
|
15
|
-
const err = new Error(`callback_data too long (${data.length} > ${TELEGRAM_CALLBACK_DATA_MAX})`)
|
|
15
|
+
const err = /** @type {any} */ (new Error(`callback_data too long (${data.length} > ${TELEGRAM_CALLBACK_DATA_MAX})`))
|
|
16
16
|
err.status = 400
|
|
17
17
|
throw err
|
|
18
18
|
}
|
package/lib/client.js
CHANGED
|
@@ -334,19 +334,6 @@ window.__ModuleLoader__.load({
|
|
|
334
334
|
'badge.api_degraded': 'Telegram API 异常 ({count} 次连续错误)',
|
|
335
335
|
}
|
|
336
336
|
|
|
337
|
-
function useActiveLocale(ctx) {
|
|
338
|
-
const loc = ctx?.get?.('locale') || ctx?.locale
|
|
339
|
-
return React.useSyncExternalStore(
|
|
340
|
-
React.useMemo(() => (cb) => (loc ? loc.subscribe(cb) : () => {}), [loc]),
|
|
341
|
-
React.useCallback(() => {
|
|
342
|
-
if (loc) {
|
|
343
|
-
const active = loc.getSnapshot?.()?.active
|
|
344
|
-
if (typeof active === 'string' && active) return active
|
|
345
|
-
}
|
|
346
|
-
return typeof navigator !== 'undefined' ? String(navigator.language || '').slice(0, 2) : 'en'
|
|
347
|
-
}, [loc]),
|
|
348
|
-
)
|
|
349
|
-
}
|
|
350
337
|
|
|
351
338
|
function makeT(locale) {
|
|
352
339
|
const DICT = String(locale || '').startsWith('zh') ? zh : en
|
package/lib/file-manager.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { escapeHtml } from './telegram-format.js'
|
|
1
2
|
import { realpathSync } from 'node:fs'
|
|
2
3
|
import { readdir, stat, readFile } from 'node:fs/promises'
|
|
3
4
|
import { resolve, normalize, relative, join, extname, isAbsolute, sep, dirname } from 'node:path'
|
|
@@ -29,7 +30,7 @@ export function resolveSafePath(baseCwd, userPath = '.') {
|
|
|
29
30
|
const isDrivePath = /^[a-zA-Z]:/.test(cleanUser)
|
|
30
31
|
const rel = relative(base, target)
|
|
31
32
|
if (isAbsolute(cleanUser) || isDrivePath || rel.startsWith('..') || isAbsolute(rel) || (rel && resolve(base, rel) !== target)) {
|
|
32
|
-
const err = new Error('Access denied: path traversal out of workspace')
|
|
33
|
+
const err = /** @type {any} */ (new Error('Access denied: path traversal out of workspace'))
|
|
33
34
|
err.code = 'ERR_PATH_TRAVERSAL'
|
|
34
35
|
throw err
|
|
35
36
|
}
|
|
@@ -39,7 +40,7 @@ export function resolveSafePath(baseCwd, userPath = '.') {
|
|
|
39
40
|
try {
|
|
40
41
|
const realTarget = realpathSync(target)
|
|
41
42
|
if (!isSubpath(realBase, realTarget)) {
|
|
42
|
-
const err = new Error('Access denied: symlink resolves out of workspace')
|
|
43
|
+
const err = /** @type {any} */ (new Error('Access denied: symlink resolves out of workspace'))
|
|
43
44
|
err.code = 'ERR_PATH_TRAVERSAL'
|
|
44
45
|
throw err
|
|
45
46
|
}
|
|
@@ -51,7 +52,7 @@ export function resolveSafePath(baseCwd, userPath = '.') {
|
|
|
51
52
|
try {
|
|
52
53
|
const realCurr = realpathSync(curr)
|
|
53
54
|
if (!isSubpath(realBase, realCurr)) {
|
|
54
|
-
const err = new Error('Access denied: symlink ancestor resolves out of workspace')
|
|
55
|
+
const err = /** @type {any} */ (new Error('Access denied: symlink ancestor resolves out of workspace'))
|
|
55
56
|
err.code = 'ERR_PATH_TRAVERSAL'
|
|
56
57
|
throw err
|
|
57
58
|
}
|
|
@@ -103,7 +104,7 @@ export async function listFiles(baseCwd, subPath = '.', opts = {}) {
|
|
|
103
104
|
isDirectory: false,
|
|
104
105
|
currentPath: relativePath,
|
|
105
106
|
entries: [{ name: relativePath, size: st.size, isDirectory: false }],
|
|
106
|
-
formattedText: `📄 <b>${relativePath}</b> (${formatFileSize(st.size)})\nDownload: <code>/get ${relativePath}</code>`,
|
|
107
|
+
formattedText: `📄 <b>${escapeHtml(relativePath)}</b> (${formatFileSize(st.size)})\nDownload: <code>/get ${escapeHtml(relativePath)}</code>`,
|
|
107
108
|
}
|
|
108
109
|
}
|
|
109
110
|
|
|
@@ -153,9 +154,9 @@ export async function listFiles(baseCwd, subPath = '.', opts = {}) {
|
|
|
153
154
|
|
|
154
155
|
for (const e of sliced) {
|
|
155
156
|
if (e.isDirectory) {
|
|
156
|
-
lines.push(`📁 <code>${e.name}/</code>`)
|
|
157
|
+
lines.push(`📁 <code>${escapeHtml(e.name)}/</code>`)
|
|
157
158
|
} else {
|
|
158
|
-
lines.push(`📄 <code>${e.name}</code> (${formatFileSize(e.size)})`)
|
|
159
|
+
lines.push(`📄 <code>${escapeHtml(e.name)}</code> (${formatFileSize(e.size)})`)
|
|
159
160
|
}
|
|
160
161
|
}
|
|
161
162
|
|
|
@@ -245,7 +246,7 @@ export async function handleGetCommand(agentCwd, targetRel, maxDocBytes = 50 * 1
|
|
|
245
246
|
dataBase64: res.bytes.toString('base64'),
|
|
246
247
|
}
|
|
247
248
|
return {
|
|
248
|
-
text: `📄 File: <b>${res.name}</b> (${formatFileSize(res.size)})`,
|
|
249
|
+
text: `📄 File: <b>${escapeHtml(res.name)}</b> (${formatFileSize(res.size)})`,
|
|
249
250
|
files: [file],
|
|
250
251
|
}
|
|
251
252
|
}
|
package/lib/forum-mirror.js
CHANGED
|
@@ -115,7 +115,7 @@ export async function mirrorSessionToForumTopic(gw, session) {
|
|
|
115
115
|
gw.ctx?.logger?.warn?.(`Failed to mirror session ${sessionId} to forum topic: ${err?.message || err}`)
|
|
116
116
|
}
|
|
117
117
|
}
|
|
118
|
-
export async function relayTurnToForumMirror(gw, session,
|
|
118
|
+
export async function relayTurnToForumMirror(gw, session, _event) {
|
|
119
119
|
if (!session || !session.id) return
|
|
120
120
|
const sessionId = String(session.id)
|
|
121
121
|
const threadInfo = gw.sessionToThread.get(sessionId)
|
package/lib/gateway-callbacks.js
CHANGED
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
releaseCallbacks, buildMultiSelectKeyboard, indexCallbacks, REMOVE_KEYBOARD
|
|
5
5
|
} from './ask.js'
|
|
6
6
|
import {
|
|
7
|
-
listModelCatalog, buildProvidersKeyboard, buildModelsKeyboard,
|
|
7
|
+
listModelCatalog, buildProvidersKeyboard, buildModelsKeyboard,
|
|
8
8
|
getStoredModelSelection
|
|
9
9
|
} from './models.js'
|
|
10
10
|
|
|
@@ -157,16 +157,17 @@ export async function handleGatewayCallback(gw, cb) {
|
|
|
157
157
|
}
|
|
158
158
|
const { provider, model } = stored
|
|
159
159
|
try {
|
|
160
|
-
|
|
160
|
+
let saved = false
|
|
161
|
+
const adm = gw.ctx.get?.('agentDefaultModel') || gw.ctx.agentDefaultModel
|
|
161
162
|
if (adm?.saveSelection) {
|
|
162
163
|
await adm.saveSelection({ provider, model })
|
|
164
|
+
saved = true
|
|
163
165
|
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
} catch (e) {
|
|
168
|
-
gw.ctx.logger?.warn?.(`persist agent model: ${e.message}`)
|
|
166
|
+
if (!saved && gw.hooks?.persistAgentModel) {
|
|
167
|
+
await gw.hooks.persistAgentModel({ provider, model })
|
|
168
|
+
saved = true
|
|
169
169
|
}
|
|
170
|
+
gw.config.agent = { ...gw.config.agent, provider, model }
|
|
170
171
|
await cb.answer(t('ask.chose', { choice: model }, 'en'))
|
|
171
172
|
try {
|
|
172
173
|
if (cb.editMessage) await cb.editMessage(t('model.switched', { provider, model }, 'en'), REMOVE_KEYBOARD)
|
package/lib/gateway-commands.js
CHANGED
|
@@ -44,14 +44,14 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
44
44
|
return reply(sub === 'zh' ? '语言已切换为中文 (zh)' : 'Language switched to English (en)')
|
|
45
45
|
}
|
|
46
46
|
const cur = gw.chatLocales.get(chatId) || gw.config?.defaultLocale || 'en'
|
|
47
|
-
return reply(`Current language: <b>${cur}</b>\nSwitch: <code>/lang en</code> or <code>/lang zh</code>`)
|
|
47
|
+
return reply(`Current language: <b>${escapeHtml(cur)}</b>\nSwitch: <code>/lang en</code> or <code>/lang zh</code>`)
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
if (cmd === '/bind') {
|
|
51
51
|
const targetRole = parts[1]?.toLowerCase()
|
|
52
52
|
if (!targetRole || targetRole === 'list') {
|
|
53
53
|
const cur = gw.personas.getPersonaForChat(chatId, threadId)
|
|
54
|
-
return reply(`${t('persona.title', {}, locale)}\nCurrent bound role: <b>${cur}</b>\nUsage: <code>/bind <role></code> (or /bind reset)`)
|
|
54
|
+
return reply(`${t('persona.title', {}, locale)}\nCurrent bound role: <b>${escapeHtml(cur)}</b>\nUsage: <code>/bind <role></code> (or /bind reset)`)
|
|
55
55
|
}
|
|
56
56
|
if (targetRole === 'reset' || targetRole === 'default') {
|
|
57
57
|
gw.personas.set(chatId, 'default', threadId)
|
|
@@ -67,7 +67,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
67
67
|
const presetName = parts[1]
|
|
68
68
|
if (!presetName || presetName === 'list') {
|
|
69
69
|
const cur = gw.personas.getPreset(chatId, threadId) || '(none)'
|
|
70
|
-
return reply(`🎭 <b>Presets:</b>\nCurrent topic preset: <code>${cur}</code>\nUsage: <code>/preset <name></code> or <code>/preset reset</code>`)
|
|
70
|
+
return reply(`🎭 <b>Presets:</b>\nCurrent topic preset: <code>${escapeHtml(cur)}</code>\nUsage: <code>/preset <name></code> or <code>/preset reset</code>`)
|
|
71
71
|
}
|
|
72
72
|
if (presetName === 'reset' || presetName === 'clear') {
|
|
73
73
|
gw.personas.setPreset(chatId, threadId, null)
|
|
@@ -85,7 +85,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
85
85
|
const lines = [t('cron.list_title', {}, locale)]
|
|
86
86
|
for (const task of list) {
|
|
87
87
|
const left = formatRemaining(task.dueAt - Date.now(), locale)
|
|
88
|
-
lines.push(`• <code>${task.id}</code> (every ${formatRemaining(task.intervalMs, locale)}, next in ${left}): ${task.prompt || task.text}`)
|
|
88
|
+
lines.push(`• <code>${escapeHtml(task.id)}</code> (every ${formatRemaining(task.intervalMs, locale)}, next in ${left}): ${escapeHtml(task.prompt || task.text || "")}`)
|
|
89
89
|
}
|
|
90
90
|
lines.push('\nCancel: <code>/cron cancel ID</code>')
|
|
91
91
|
return reply(lines.join('\n'))
|
|
@@ -94,7 +94,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
94
94
|
const targetId = parts[2]
|
|
95
95
|
if (!targetId) return reply('Specify cron task ID: <code>/cron cancel ID</code>')
|
|
96
96
|
const ok = await gw.scheduler.cancel(targetId, chatId)
|
|
97
|
-
return reply(ok ? t('cron.cancelled', { id: targetId }, locale) : `Task not found: <code>${targetId}</code>`)
|
|
97
|
+
return reply(ok ? t('cron.cancelled', { id: targetId }, locale) : `Task not found: <code>${escapeHtml(targetId)}</code>`)
|
|
98
98
|
}
|
|
99
99
|
const specArg = parts[1]
|
|
100
100
|
const promptArg = parts.slice(2).join(' ')
|
|
@@ -133,7 +133,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
133
133
|
if (!res.updated) {
|
|
134
134
|
return reply(t('update.already_latest', { version: res.currentVersion }, locale))
|
|
135
135
|
}
|
|
136
|
-
return reply(t('update.success', { version: res.updatedVersion }, locale))
|
|
136
|
+
return reply(t('update.success', { version: /** @type {any} */ (res).updatedVersion }, locale))
|
|
137
137
|
} catch (err) {
|
|
138
138
|
return reply(t('update.failed', { error: err.message }, locale))
|
|
139
139
|
}
|
|
@@ -182,7 +182,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
182
182
|
const toolsList = []
|
|
183
183
|
if (tools?.tools) {
|
|
184
184
|
for (const [name, tDef] of tools.tools.entries()) {
|
|
185
|
-
toolsList.push(`• <b>${name}</b>: ${tDef.description || '(no description)'}`)
|
|
185
|
+
toolsList.push(`• <b>${escapeHtml(name)}</b>: ${escapeHtml(tDef.description || '(no description)')}`)
|
|
186
186
|
}
|
|
187
187
|
}
|
|
188
188
|
if (!toolsList.length) {
|
|
@@ -524,7 +524,9 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
524
524
|
const titleSnap = await sessionQuery.readTitle(id)
|
|
525
525
|
title = titleSnap?.title || titleSnap?.value || ''
|
|
526
526
|
} catch { /* best effort */ }
|
|
527
|
-
if (!title
|
|
527
|
+
if (!title || title.startsWith('Channel: Messenger') || title.startsWith('[Channel: Messenger')) {
|
|
528
|
+
title = (r.header.title && !r.header.title.startsWith('Channel: Messenger') && !r.header.title.startsWith('[Channel: Messenger')) ? r.header.title : id
|
|
529
|
+
}
|
|
528
530
|
const cwd = r.header.cwd || r.header.meta?.cwd || ''
|
|
529
531
|
const dir = cwd ? cwd.split(/[\\/]/).filter(Boolean).slice(-2).join('/') : ''
|
|
530
532
|
return { id, title, dir }
|
|
@@ -533,8 +535,8 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
533
535
|
gw.recentSessions.set(key, items)
|
|
534
536
|
const lines = ['📋 <b>Recent Sessions:</b>', '']
|
|
535
537
|
items.forEach((item, index) => {
|
|
536
|
-
const dirSuffix = item.dir ? ` (<i>${item.dir}</i>)` : ''
|
|
537
|
-
lines.push(`${index + 1}. <b>${item.title}</b>${dirSuffix}\n <code>/resume ${index + 1}</code>`)
|
|
538
|
+
const dirSuffix = item.dir ? ` (<i>${escapeHtml(item.dir)}</i>)` : ''
|
|
539
|
+
lines.push(`${index + 1}. <b>${escapeHtml(item.title)}</b>${dirSuffix}\n <code>/resume ${index + 1}</code>`)
|
|
538
540
|
})
|
|
539
541
|
lines.push('', 'Switch using <code>/resume <number></code>')
|
|
540
542
|
return reply(lines.join('\n'))
|
|
@@ -688,21 +690,42 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
688
690
|
}
|
|
689
691
|
|
|
690
692
|
if (cmd === '/model') {
|
|
693
|
+
const wantsList = /^(?:list|ls|all)$/i.test(parts[1] || '')
|
|
694
|
+
if (wantsList) {
|
|
695
|
+
try {
|
|
696
|
+
const current = gw.resolveAgentModel()
|
|
697
|
+
const catalog = await listModelCatalog(gw.ctx, current)
|
|
698
|
+
const lines = ['🧠 <b>Models</b>', `Current: <code>${escapeHtml(current.provider)}/${escapeHtml(current.model)}</code>`, '']
|
|
699
|
+
for (const p of catalog.providers) {
|
|
700
|
+
lines.push(`<b>${escapeHtml(p.name || p.id)}</b>`)
|
|
701
|
+
for (const m of catalog.modelsByProvider.get(p.id) || []) {
|
|
702
|
+
const mark = (m.id === current.model && p.id === current.provider) ? ' ✅' : ''
|
|
703
|
+
lines.push(`• <code>/model ${escapeHtml(p.id)} ${escapeHtml(m.id)}</code>${mark}`)
|
|
704
|
+
}
|
|
705
|
+
lines.push('')
|
|
706
|
+
}
|
|
707
|
+
return reply(lines.join('\n'))
|
|
708
|
+
} catch (e) {
|
|
709
|
+
return reply(`Failed to list models: ${e.message}`)
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
691
713
|
if (parts.length >= 3) {
|
|
692
714
|
if (!gw.isUserAllowed(userId)) return reply(t('msg.not_allowed', {}, locale))
|
|
693
715
|
const provider = parts[1]
|
|
694
716
|
const model = parts.slice(2).join(' ')
|
|
695
717
|
try {
|
|
696
|
-
|
|
718
|
+
let saved = false
|
|
719
|
+
const adm = gw.ctx.get?.('agentDefaultModel') || gw.ctx.agentDefaultModel
|
|
697
720
|
if (adm?.saveSelection) {
|
|
698
721
|
await adm.saveSelection({ provider, model })
|
|
722
|
+
saved = true
|
|
699
723
|
}
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
} catch (e) {
|
|
704
|
-
gw.ctx.logger?.warn?.(`persist agent model: ${e.message}`)
|
|
724
|
+
if (!saved && gw.hooks?.persistAgentModel) {
|
|
725
|
+
await gw.hooks.persistAgentModel({ provider, model })
|
|
726
|
+
saved = true
|
|
705
727
|
}
|
|
728
|
+
gw.config.agent = { ...gw.config.agent, provider, model }
|
|
706
729
|
return reply(t('model.switched', { provider, model }, locale))
|
|
707
730
|
} catch (e) {
|
|
708
731
|
return reply(`Failed to switch model: ${e.message}`)
|
|
@@ -712,7 +735,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
712
735
|
const current = gw.resolveAgentModel()
|
|
713
736
|
const catalog = await listModelCatalog(gw.ctx, current)
|
|
714
737
|
if (!catalog.providers.length) {
|
|
715
|
-
return reply(`Current model: <code>${current.provider}/${current.model}</code>\nSwitch: <code>/model <provider> <model></code>`)
|
|
738
|
+
return reply(`Current model: <code>${escapeHtml(current.provider)}/${escapeHtml(current.model)}</code>\nSwitch: <code>/model <provider> <model></code>`)
|
|
716
739
|
}
|
|
717
740
|
const kb = buildProvidersKeyboard(catalog.providers, current)
|
|
718
741
|
return reply([
|
|
@@ -778,7 +801,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
778
801
|
'',
|
|
779
802
|
...active.map((tItem) => {
|
|
780
803
|
const left = formatRemaining(tItem.dueAt - Date.now(), locale)
|
|
781
|
-
return `• <code>${tItem.id}</code> (in ${left}): ${tItem.text}`
|
|
804
|
+
return `• <code>${escapeHtml(tItem.id)}</code> (in ${left}): ${escapeHtml(tItem.text || '')}`
|
|
782
805
|
}),
|
|
783
806
|
'',
|
|
784
807
|
'Cancel: <code>/remind cancel ID</code>',
|
|
@@ -789,7 +812,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
789
812
|
const targetId = parts[2]?.trim()
|
|
790
813
|
if (!targetId) return reply('Specify reminder ID: <code>/remind cancel ID</code>')
|
|
791
814
|
const ok = await gw.scheduler.cancel(targetId, chatId)
|
|
792
|
-
return reply(ok ? `✅ Reminder <code>${targetId}</code> cancelled.` : `❌ Reminder <code>${targetId}</code> not found.`)
|
|
815
|
+
return reply(ok ? `✅ Reminder <code>${escapeHtml(targetId)}</code> cancelled.` : `❌ Reminder <code>${escapeHtml(targetId)}</code> not found.`)
|
|
793
816
|
}
|
|
794
817
|
const timeArg = parts[1]
|
|
795
818
|
const textArg = parts.slice(2).join(' ').trim()
|
|
@@ -804,7 +827,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
804
827
|
].join('\n'))
|
|
805
828
|
}
|
|
806
829
|
const dueAt = Date.now() + delayMs
|
|
807
|
-
|
|
830
|
+
await gw.scheduler.schedule({
|
|
808
831
|
platform: platform || 'telegram',
|
|
809
832
|
chatId,
|
|
810
833
|
threadId: threadId || 0,
|
|
@@ -851,10 +874,10 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
851
874
|
try {
|
|
852
875
|
const res = await tgAdapter.createForumTopic(chatId, topicName)
|
|
853
876
|
const newThreadId = res?.message_thread_id
|
|
854
|
-
await reply(`🎯 Created new topic <b>«${topicName}»</b> (ID: <code>${newThreadId}</code>).\nSwitch to the topic to continue working!`)
|
|
877
|
+
await reply(`🎯 Created new topic <b>«${escapeHtml(topicName)}»</b> (ID: <code>${newThreadId}</code>).\nSwitch to the topic to continue working!`)
|
|
855
878
|
if (newThreadId) {
|
|
856
879
|
await tgAdapter.sendTo(chatId, {
|
|
857
|
-
text: `👋 Hello! This is an isolated session for task <b>«${topicName}»</b>.\nHow can I help?`,
|
|
880
|
+
text: `👋 Hello! This is an isolated session for task <b>«${escapeHtml(topicName)}»</b>.\nHow can I help?`,
|
|
858
881
|
}, { threadId: newThreadId })
|
|
859
882
|
}
|
|
860
883
|
return
|
|
@@ -888,7 +911,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
888
911
|
`• <b>Uptime:</b> ${hh}:${mm}:${ss}`,
|
|
889
912
|
`• <b>Active chats:</b> ${gw.chats.size}`,
|
|
890
913
|
`• <b>Queued reminders:</b> ${activeReminders}`,
|
|
891
|
-
`• <b>Active model:</b> <code>${currentModel}</code>`,
|
|
914
|
+
`• <b>Active model:</b> <code>${escapeHtml(currentModel)}</code>`,
|
|
892
915
|
`• <b>Messages sent:</b> ${gw.stats.sent}`,
|
|
893
916
|
`• <b>Errors:</b> ${gw.stats.errors}`,
|
|
894
917
|
].join('\n'))
|
package/lib/gateway-turn.js
CHANGED
|
@@ -2,17 +2,17 @@ import { readFile } from 'node:fs/promises'
|
|
|
2
2
|
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
3
3
|
import { ensureContentArray } from './content-guard.js'
|
|
4
4
|
import { getPersona } from './personas.js'
|
|
5
|
-
import { MESSENGER_RELAY_INSTRUCTION,
|
|
5
|
+
import { MESSENGER_RELAY_INSTRUCTION, splitText } from './text.js'
|
|
6
6
|
import { formatInboundDocument, documentOnlyHint, parseDocument } from './documents.js'
|
|
7
7
|
import { t } from './locales/index.js'
|
|
8
|
-
import {
|
|
8
|
+
import { 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, formatReasoningFinal
|
|
16
16
|
} from './stream.js'
|
|
17
17
|
import { escapeHtml } from './telegram-format.js'
|
|
18
18
|
import { formatCostFooter, normalizeUsage, extractSessionStats, calculateEstimatedCostUsd, checkBudgetThreshold } from './cost-tracker.js'
|
|
@@ -139,7 +139,9 @@ export async function answerApproval(gw, chatKeyValue, req, next) {
|
|
|
139
139
|
export async function buildUserContent(gw, input, signal) {
|
|
140
140
|
const { text, attachments = [], replyText, steer, personaOverride, userId } = input
|
|
141
141
|
const parts = []
|
|
142
|
-
parts.push(
|
|
142
|
+
if (text?.trim()) parts.push(text.trim())
|
|
143
|
+
const relayInstruction = String(gw.config.agent?.instructionPrefix || MESSENGER_RELAY_INSTRUCTION)
|
|
144
|
+
if (relayInstruction) parts.push(`[${relayInstruction}]`)
|
|
143
145
|
if (gw.config?.memory?.enabled !== false && gw.config?.memory?.autoInject !== false && userId) {
|
|
144
146
|
try {
|
|
145
147
|
const recalled = await recallUserMemories({
|
|
@@ -206,7 +208,6 @@ export async function buildUserContent(gw, input, signal) {
|
|
|
206
208
|
if (photoHint) parts.push(photoHint)
|
|
207
209
|
const docHint = documentOnlyHint(attachments, text)
|
|
208
210
|
if (docHint) parts.push(docHint)
|
|
209
|
-
if (text?.trim()) parts.push(text.trim())
|
|
210
211
|
const textBlock = parts.filter(Boolean).join('\n\n')
|
|
211
212
|
if (textBlock) blocks.unshift({ type: 'text', text: textBlock })
|
|
212
213
|
if (!blocks.length) blocks.push({ type: 'text', text: '(empty message)' })
|
|
@@ -278,10 +279,10 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
278
279
|
|
|
279
280
|
|
|
280
281
|
const content = await gw.buildUserContent(input, signal)
|
|
281
|
-
chat.agent.followup(createUserMessage({
|
|
282
|
+
chat.agent.followup(createUserMessage(/** @type {any} */ ({
|
|
282
283
|
content: ensureContentArray(content),
|
|
283
284
|
source: { kind: 'user', plugin: PLUGIN, form: 'relay', origin: 'telegram' },
|
|
284
|
-
}))
|
|
285
|
+
})))
|
|
285
286
|
const turnTimeoutMs = Number(gw.config.agent?.turnTimeoutMs) || 600_000
|
|
286
287
|
await whenIdleWithTimeout(chat.agent, turnTimeoutMs, signal)
|
|
287
288
|
if (signal.aborted) {
|
|
@@ -309,7 +310,7 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
309
310
|
chatId: input.chatId,
|
|
310
311
|
webAppUrl: gw.resolveWebAppUrl?.() || '',
|
|
311
312
|
})
|
|
312
|
-
|
|
313
|
+
let answer = processed.text
|
|
313
314
|
if (collector.reason?.kind === 'error') {
|
|
314
315
|
const err = collector.reason.error
|
|
315
316
|
const msg = t('msg.agent_error', { code: err?.code || 'error', message: err?.message || 'unknown' }, gw.resolveLocale(input))
|
package/lib/gateway.js
CHANGED
|
@@ -53,6 +53,7 @@ export class Gateway {
|
|
|
53
53
|
this.pendingAsks = new Map()
|
|
54
54
|
this.adapters = new Map()
|
|
55
55
|
this.adapterList = []
|
|
56
|
+
this.recentSessions = new Map()
|
|
56
57
|
// true после stop(): start() обязан прекратить работу, если его обогнали.
|
|
57
58
|
this.stopped = false
|
|
58
59
|
this.disposeListener = undefined
|
|
@@ -362,6 +363,7 @@ export class Gateway {
|
|
|
362
363
|
this.sessionToChat.clear()
|
|
363
364
|
this.sessionToThread.clear()
|
|
364
365
|
this.threadToSession.clear()
|
|
366
|
+
this.recentSessions.clear()
|
|
365
367
|
for (const pending of this.pendingAsks.values()) {
|
|
366
368
|
releaseCallbacks(this.callbackIndex, pending.callbackKeys)
|
|
367
369
|
rejectPendingAsk(pending, new Error('gateway stopped'))
|
|
@@ -455,7 +457,7 @@ export class Gateway {
|
|
|
455
457
|
}
|
|
456
458
|
|
|
457
459
|
async handleMessage(input) {
|
|
458
|
-
const {
|
|
460
|
+
const { text, reply } = input
|
|
459
461
|
const key = this.sessionKeyFor(input)
|
|
460
462
|
const body = String(text || '').trim()
|
|
461
463
|
let attachments = [...(input.attachments || [])]
|
|
@@ -542,10 +544,10 @@ export class Gateway {
|
|
|
542
544
|
text: steerText,
|
|
543
545
|
steer: true,
|
|
544
546
|
}, undefined)
|
|
545
|
-
chat.agent.followup(createUserMessage({
|
|
547
|
+
chat.agent.followup(createUserMessage(/** @type {any} */ ({
|
|
546
548
|
content: ensureContentArray(content),
|
|
547
549
|
source: { kind: 'user', plugin: PLUGIN, form: 'steer', origin: 'telegram' },
|
|
548
|
-
}))
|
|
550
|
+
})))
|
|
549
551
|
chat.lastUsed = Date.now()
|
|
550
552
|
try { await reply(t('msg.steer_added', {}, this.resolveLocale(input))) } catch (err) { this.recordApiFailure('reply.steer_added', err) }
|
|
551
553
|
return
|
|
@@ -661,19 +663,35 @@ export class Gateway {
|
|
|
661
663
|
const self = this
|
|
662
664
|
const agents = this.ctx.get?.('agents') || this.ctx.agents
|
|
663
665
|
const targetSessionId = existingSessionId ? SessionId(existingSessionId) : SessionId(`msgw-${randomUUID()}`)
|
|
664
|
-
const
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
666
|
+
const setup = (agentCtx) => {
|
|
667
|
+
installModelSelection(agentCtx, { current: { provider, model }, assembled: undefined })
|
|
668
|
+
if (self.tg().approvalsEnabled !== false) {
|
|
669
|
+
agentCtx.on('approval/request', (req, next) => self.answerApproval(key, req, next))
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
const handle = existingSessionId
|
|
673
|
+
? (agents.resume
|
|
674
|
+
? await agents.resume({
|
|
675
|
+
resumeSessionId: SessionId(existingSessionId),
|
|
676
|
+
agentOptions: { provider, model },
|
|
677
|
+
setup,
|
|
678
|
+
})
|
|
679
|
+
: await agents.create({
|
|
680
|
+
sessionId: targetSessionId,
|
|
681
|
+
meta: { cwd },
|
|
682
|
+
agentOptions: { provider, model },
|
|
683
|
+
setup,
|
|
684
|
+
}))
|
|
685
|
+
: await agents.create({
|
|
686
|
+
sessionId: targetSessionId,
|
|
687
|
+
meta: { cwd },
|
|
688
|
+
agentOptions: { provider, model },
|
|
689
|
+
setup,
|
|
690
|
+
})
|
|
675
691
|
await handle.agent.whenIdle()
|
|
676
|
-
|
|
692
|
+
if (!existingSessionId) {
|
|
693
|
+
await registerSessionInWorkspace(this.ctx, targetSessionId, cwd, this.ctx.logger).catch((e) => { this.logger?.debug?.('registerSessionInWorkspace error:', e?.message || e) })
|
|
694
|
+
}
|
|
677
695
|
// Opt-in: name the session after the chat that opened it, so a bot serving
|
|
678
696
|
// several chats keeps an unambiguous session list.
|
|
679
697
|
if (!existingSessionId && agentCfg.sessionTitleFromChat === true) {
|
package/lib/http.js
CHANGED
|
@@ -3,7 +3,7 @@ import { timingSafeEqual } from 'node:crypto'
|
|
|
3
3
|
export async function readBody(req, maxBytes = 1_048_576) {
|
|
4
4
|
const cl = Number(req?.headers?.['content-length'])
|
|
5
5
|
if (Number.isFinite(cl) && cl > maxBytes) {
|
|
6
|
-
const err = new Error(`Payload Too Large: content-length ${cl} exceeds ${maxBytes}`)
|
|
6
|
+
const err = /** @type {any} */ (new Error(`Payload Too Large: content-length ${cl} exceeds ${maxBytes}`))
|
|
7
7
|
err.status = 413
|
|
8
8
|
err.statusCode = 413
|
|
9
9
|
throw err
|
|
@@ -13,7 +13,7 @@ export async function readBody(req, maxBytes = 1_048_576) {
|
|
|
13
13
|
for await (const chunk of req) {
|
|
14
14
|
total += chunk.length
|
|
15
15
|
if (total > maxBytes) {
|
|
16
|
-
const err = new Error(`Payload Too Large: exceeded ${maxBytes} bytes`)
|
|
16
|
+
const err = /** @type {any} */ (new Error(`Payload Too Large: exceeded ${maxBytes} bytes`))
|
|
17
17
|
err.status = 413
|
|
18
18
|
err.statusCode = 413
|
|
19
19
|
throw err
|
package/lib/index.js
CHANGED
|
@@ -168,7 +168,6 @@ export function apply(ctx, config) {
|
|
|
168
168
|
let gateway
|
|
169
169
|
let source = () => entry
|
|
170
170
|
let settingsApi
|
|
171
|
-
const turnStarts = new Map()
|
|
172
171
|
const getWebServer = () => ctx.get?.('webServer') || ctx.webServer
|
|
173
172
|
|
|
174
173
|
// Секреты (botToken и т. п.) не отдаются браузеру, а карточка сохраняет секции
|
package/lib/memory-brain.js
CHANGED
|
@@ -149,6 +149,7 @@ export async function callMemoryMcp(rawConfig, toolName, args, signal) {
|
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
+
/** @param {any} opts */
|
|
152
153
|
export async function listUserMemories({ config, userId, limit = 20, signal }) {
|
|
153
154
|
if (!userId) return { ok: false, error: 'missing_user_id', items: [] }
|
|
154
155
|
const scope = `user:${userId}`
|
|
@@ -160,6 +161,7 @@ export async function listUserMemories({ config, userId, limit = 20, signal }) {
|
|
|
160
161
|
return { ok: true, items, raw: res.text }
|
|
161
162
|
}
|
|
162
163
|
|
|
164
|
+
/** @param {any} opts */
|
|
163
165
|
export async function recallUserMemories({ config, userId, query = '', budget, signal }) {
|
|
164
166
|
if (!userId) return ''
|
|
165
167
|
const scope = `user:${userId}`
|
|
@@ -184,6 +186,7 @@ export async function recallUserMemories({ config, userId, query = '', budget, s
|
|
|
184
186
|
return formatMemoryContext(res.text, userId)
|
|
185
187
|
}
|
|
186
188
|
|
|
189
|
+
/** @param {any} opts */
|
|
187
190
|
export async function rememberUserFact({ config, userId, content, category = 'preference', signal }) {
|
|
188
191
|
if (!userId) return { ok: false, error: 'missing_user_id' }
|
|
189
192
|
const text = String(content || '').trim()
|
|
@@ -211,6 +214,7 @@ export async function rememberUserFact({ config, userId, content, category = 'pr
|
|
|
211
214
|
return { ok: true, memoryId, text: res.text }
|
|
212
215
|
}
|
|
213
216
|
|
|
217
|
+
/** @param {any} opts */
|
|
214
218
|
export async function forgetUserMemory({ config, userId, memoryId, signal }) {
|
|
215
219
|
if (!userId) return { ok: false, error: 'missing_user_id' }
|
|
216
220
|
const target = String(memoryId || '').trim()
|
|
@@ -248,7 +252,8 @@ export async function forgetUserMemory({ config, userId, memoryId, signal }) {
|
|
|
248
252
|
return res
|
|
249
253
|
}
|
|
250
254
|
|
|
251
|
-
|
|
255
|
+
/** @param {any} opts */
|
|
256
|
+
export async function recordTurnMemory({ config, userId, userText, assistantText: _assistantText, signal, logger }) {
|
|
252
257
|
const extracted = extractConversationalPreferences(userText)
|
|
253
258
|
if (!extracted) return { ok: true, skipped: true }
|
|
254
259
|
|
package/lib/messenger-api.js
CHANGED
|
@@ -41,7 +41,7 @@ export function parseMessengerBody(raw) {
|
|
|
41
41
|
try {
|
|
42
42
|
return JSON.parse(String(raw || '{}') || '{}')
|
|
43
43
|
} catch {
|
|
44
|
-
const err = new Error('invalid json')
|
|
44
|
+
const err = /** @type {any} */ (new Error('invalid json'))
|
|
45
45
|
err.status = 400
|
|
46
46
|
throw err
|
|
47
47
|
}
|
|
@@ -49,13 +49,13 @@ export function parseMessengerBody(raw) {
|
|
|
49
49
|
|
|
50
50
|
export function validateTarget(target) {
|
|
51
51
|
if (!target || typeof target !== 'object') {
|
|
52
|
-
const err = new Error('target is required')
|
|
52
|
+
const err = /** @type {any} */ (new Error('target is required'))
|
|
53
53
|
err.status = 400
|
|
54
54
|
throw err
|
|
55
55
|
}
|
|
56
56
|
const platform = String(target.platform || '').trim()
|
|
57
57
|
if (!platform) {
|
|
58
|
-
const err = new Error('target.platform is required')
|
|
58
|
+
const err = /** @type {any} */ (new Error('target.platform is required'))
|
|
59
59
|
err.status = 400
|
|
60
60
|
throw err
|
|
61
61
|
}
|
|
@@ -74,13 +74,13 @@ export function validateTarget(target) {
|
|
|
74
74
|
export function normalizeButtons(buttons) {
|
|
75
75
|
if (buttons === undefined || buttons === null) return []
|
|
76
76
|
if (!Array.isArray(buttons)) {
|
|
77
|
-
const err = new Error('buttons must be a 2d array')
|
|
77
|
+
const err = /** @type {any} */ (new Error('buttons must be a 2d array'))
|
|
78
78
|
err.status = 400
|
|
79
79
|
throw err
|
|
80
80
|
}
|
|
81
81
|
return buttons.map((row, ri) => {
|
|
82
82
|
if (!Array.isArray(row)) {
|
|
83
|
-
const err = new Error(`buttons[${ri}] must be an array`)
|
|
83
|
+
const err = /** @type {any} */ (new Error(`buttons[${ri}] must be an array`))
|
|
84
84
|
err.status = 400
|
|
85
85
|
throw err
|
|
86
86
|
}
|
|
@@ -88,7 +88,7 @@ export function normalizeButtons(buttons) {
|
|
|
88
88
|
const id = String(btn?.id ?? btn?.buttonId ?? '').trim()
|
|
89
89
|
const text = String(btn?.text ?? '').trim()
|
|
90
90
|
if (!id || !text) {
|
|
91
|
-
const err = new Error(`buttons[${ri}][${bi}] requires id and text`)
|
|
91
|
+
const err = /** @type {any} */ (new Error(`buttons[${ri}][${bi}] requires id and text`))
|
|
92
92
|
err.status = 400
|
|
93
93
|
throw err
|
|
94
94
|
}
|
|
@@ -100,13 +100,13 @@ export function normalizeButtons(buttons) {
|
|
|
100
100
|
export function normalizeFiles(files) {
|
|
101
101
|
if (!files) return []
|
|
102
102
|
if (!Array.isArray(files)) {
|
|
103
|
-
const err = new Error('files must be an array')
|
|
103
|
+
const err = /** @type {any} */ (new Error('files must be an array'))
|
|
104
104
|
err.status = 400
|
|
105
105
|
throw err
|
|
106
106
|
}
|
|
107
107
|
return files.map((file, i) => {
|
|
108
108
|
if (!file || typeof file !== 'object') {
|
|
109
|
-
const err = new Error(`files[${i}] must be an object`)
|
|
109
|
+
const err = /** @type {any} */ (new Error(`files[${i}] must be an object`))
|
|
110
110
|
err.status = 400
|
|
111
111
|
throw err
|
|
112
112
|
}
|
|
@@ -122,7 +122,7 @@ export function normalizeFiles(files) {
|
|
|
122
122
|
buf = Buffer.from(file.bytes, 'utf8')
|
|
123
123
|
}
|
|
124
124
|
if (!buf) {
|
|
125
|
-
const err = new Error(`files[${i}].bytes must be a Buffer, Uint8Array, or array of bytes`)
|
|
125
|
+
const err = /** @type {any} */ (new Error(`files[${i}].bytes must be a Buffer, Uint8Array, or array of bytes`))
|
|
126
126
|
err.status = 400
|
|
127
127
|
throw err
|
|
128
128
|
}
|
|
@@ -141,7 +141,7 @@ export function normalizeFiles(files) {
|
|
|
141
141
|
name: file.name || 'file',
|
|
142
142
|
}
|
|
143
143
|
}
|
|
144
|
-
const err = new Error(`files[${i}] needs bytes or dataBase64`)
|
|
144
|
+
const err = /** @type {any} */ (new Error(`files[${i}] needs bytes or dataBase64`))
|
|
145
145
|
err.status = 400
|
|
146
146
|
throw err
|
|
147
147
|
})
|
|
@@ -151,7 +151,7 @@ export function normalizeSendBody(payload) {
|
|
|
151
151
|
const text = typeof payload?.text === 'string' ? payload.text.trim() : ''
|
|
152
152
|
const files = normalizeFiles(payload?.files)
|
|
153
153
|
if (!text && !files.length) {
|
|
154
|
-
const err = new Error('text or files required')
|
|
154
|
+
const err = /** @type {any} */ (new Error('text or files required'))
|
|
155
155
|
err.status = 400
|
|
156
156
|
throw err
|
|
157
157
|
}
|
|
@@ -165,7 +165,7 @@ export function normalizeSendBody(payload) {
|
|
|
165
165
|
export function normalizeAskBody(payload) {
|
|
166
166
|
const text = String(payload?.text || '').trim()
|
|
167
167
|
if (!text) {
|
|
168
|
-
const err = new Error('text is required for ask')
|
|
168
|
+
const err = /** @type {any} */ (new Error('text is required for ask'))
|
|
169
169
|
err.status = 400
|
|
170
170
|
throw err
|
|
171
171
|
}
|
|
@@ -173,7 +173,7 @@ export function normalizeAskBody(payload) {
|
|
|
173
173
|
if (mode === 'multi' || (Array.isArray(payload?.options) && payload.options.length > 0)) {
|
|
174
174
|
const rawOptions = Array.isArray(payload?.options) ? payload.options : (Array.isArray(payload?.buttons) ? payload.buttons : [])
|
|
175
175
|
if (!rawOptions.length || (Array.isArray(rawOptions[0]) && !rawOptions.some((r) => r.length > 0))) {
|
|
176
|
-
const err = new Error('ask requires at least one option')
|
|
176
|
+
const err = /** @type {any} */ (new Error('ask requires at least one option'))
|
|
177
177
|
err.status = 400
|
|
178
178
|
throw err
|
|
179
179
|
}
|
|
@@ -189,7 +189,7 @@ export function normalizeAskBody(payload) {
|
|
|
189
189
|
}
|
|
190
190
|
const buttons = normalizeButtons(payload?.buttons)
|
|
191
191
|
if (!buttons.length || !buttons.some((row) => row.length > 0)) {
|
|
192
|
-
const err = new Error('ask requires at least one button')
|
|
192
|
+
const err = /** @type {any} */ (new Error('ask requires at least one button'))
|
|
193
193
|
err.status = 400
|
|
194
194
|
throw err
|
|
195
195
|
}
|
|
@@ -199,7 +199,7 @@ export function normalizeAskBody(payload) {
|
|
|
199
199
|
export function normalizeProgressBody(payload) {
|
|
200
200
|
const text = String(payload?.text || '').trim()
|
|
201
201
|
if (!text) {
|
|
202
|
-
const err = new Error('text is required for progress')
|
|
202
|
+
const err = /** @type {any} */ (new Error('text is required for progress'))
|
|
203
203
|
err.status = 400
|
|
204
204
|
throw err
|
|
205
205
|
}
|
|
@@ -223,7 +223,7 @@ export function httpStatusForError(err) {
|
|
|
223
223
|
|
|
224
224
|
export async function dispatchMessenger(gw, action, payload) {
|
|
225
225
|
if (!gw) {
|
|
226
|
-
const err = new Error('gateway not running')
|
|
226
|
+
const err = /** @type {any} */ (new Error('gateway not running'))
|
|
227
227
|
err.status = 503
|
|
228
228
|
throw err
|
|
229
229
|
}
|
|
@@ -240,7 +240,7 @@ export async function dispatchMessenger(gw, action, payload) {
|
|
|
240
240
|
const result = await gw.messenger.ask(target, normalizeAskBody(payload), resolveAskTimeoutMs(payload?.timeoutMs))
|
|
241
241
|
return { ok: true, result }
|
|
242
242
|
}
|
|
243
|
-
const err = new Error(`unknown messenger action: ${action}`)
|
|
243
|
+
const err = /** @type {any} */ (new Error(`unknown messenger action: ${action}`))
|
|
244
244
|
err.status = 400
|
|
245
245
|
throw err
|
|
246
246
|
}
|
package/lib/pairing.js
CHANGED
|
@@ -24,6 +24,7 @@ function writeJsonAtomicSync(filePath, data) {
|
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/** @param {string} filePath @param {any} [opts] */
|
|
27
28
|
export function createPairingStore(filePath, { logger } = {}) {
|
|
28
29
|
const state = { pending: {}, /** @type {number[]} */ approved: [] }
|
|
29
30
|
if (filePath && existsSync(filePath)) {
|
|
@@ -79,12 +80,12 @@ export function createPairingStore(filePath, { logger } = {}) {
|
|
|
79
80
|
}
|
|
80
81
|
const recent = Object.values(state.pending).find((r) => Number(r.userId) === uid && Date.now() - Number(r.createdAt || 0) < 600_000)
|
|
81
82
|
if (recent) {
|
|
82
|
-
const err = new Error('pairing rate limited')
|
|
83
|
+
const err = /** @type {any} */ (new Error('pairing rate limited'))
|
|
83
84
|
err.code = 'RATE_LIMIT'
|
|
84
85
|
throw err
|
|
85
86
|
}
|
|
86
87
|
if (Object.keys(state.pending).length >= 20) {
|
|
87
|
-
const err = new Error('too many pending pairing codes')
|
|
88
|
+
const err = /** @type {any} */ (new Error('too many pending pairing codes'))
|
|
88
89
|
err.code = 'FULL'
|
|
89
90
|
throw err
|
|
90
91
|
}
|
package/lib/personas.js
CHANGED
package/lib/proxy.js
CHANGED
|
@@ -382,7 +382,9 @@ async function openTunnel(spec, host, port, options) {
|
|
|
382
382
|
: connectViaHttpProxy(spec, host, port, options)
|
|
383
383
|
}
|
|
384
384
|
|
|
385
|
-
|
|
385
|
+
/** @param {any} [opts] */
|
|
386
|
+
function wrapTls(socket, servername, opts = {}) {
|
|
387
|
+
const { signal } = opts
|
|
386
388
|
return new Promise((resolve, reject) => {
|
|
387
389
|
const cleanup = () => {
|
|
388
390
|
if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
|
|
@@ -554,8 +556,8 @@ function requestOverTunnel({ spec, url, method, headers, body, signal, timeoutMs
|
|
|
554
556
|
reject(abortReason(signal))
|
|
555
557
|
return
|
|
556
558
|
}
|
|
557
|
-
const agent = new ProxyTunnelAgent({ spec, timeoutMs, logger })
|
|
558
|
-
req = mod.request({
|
|
559
|
+
const agent = /** @type {any} */ (new ProxyTunnelAgent({ spec, timeoutMs, logger }))
|
|
560
|
+
req = /** @type {any} */ (mod).request({
|
|
559
561
|
protocol: url.protocol,
|
|
560
562
|
host: url.hostname,
|
|
561
563
|
hostname: url.hostname,
|
package/lib/session-ops.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export function exportSessionToMarkdown(session,
|
|
1
|
+
export function exportSessionToMarkdown(session, _opts = {}) {
|
|
2
2
|
if (!session) return { filename: 'session-export.md', content: '# Empty session\n', buffer: Buffer.from('# Empty session\n') }
|
|
3
3
|
|
|
4
4
|
const id = session.id || 'unknown'
|
package/lib/telegram-errors.js
CHANGED
|
File without changes
|
package/lib/tts.js
CHANGED
|
@@ -97,6 +97,7 @@ export async function convertToOggOpus(audioBytes, inputMime = 'audio/mpeg') {
|
|
|
97
97
|
* Build a Telegram voice-note file from dsh-tts output.
|
|
98
98
|
* Prefer OGG/Opus; if conversion fails and binary missing, fall back to audio (not voice-note).
|
|
99
99
|
*/
|
|
100
|
+
/** @param {any} spoken @param {any} [opts] */
|
|
100
101
|
export async function toTelegramVoiceFile(spoken, { logger } = {}) {
|
|
101
102
|
if (!spoken?.audio?.length) return null
|
|
102
103
|
if (isOggOpusMime(spoken.mime)) {
|
package/lib/voice-prefs.js
CHANGED
package/lib/webapp.js
CHANGED
|
@@ -10,6 +10,7 @@ import { timingSafeCompare, isTrustedSettingsRequest, readBody, writeJson } from
|
|
|
10
10
|
* @param {number} [maxAgeSec=86400] - Maximum allowed age of initData in seconds (default 24h)
|
|
11
11
|
* @returns {{ ok: boolean, user?: object, authDate?: number, queryId?: string, chatType?: string, error?: string }}
|
|
12
12
|
*/
|
|
13
|
+
/** @returns {any} TMA auth result */
|
|
13
14
|
export function validateTelegramWebAppData(rawInitData, botToken, maxAgeSec = 86400) {
|
|
14
15
|
if (!rawInitData || typeof rawInitData !== 'string') {
|
|
15
16
|
return { ok: false, error: 'empty_init_data' }
|
package/lib/workspace.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { resolve,
|
|
1
|
+
import { resolve, basename } from 'node:path'
|
|
2
2
|
import { statSync, realpathSync, existsSync } from 'node:fs'
|
|
3
3
|
import { readFile } from 'node:fs/promises'
|
|
4
4
|
import { readFileSync } from 'node:fs'
|
|
@@ -170,6 +170,7 @@ export function inspectGitWorkspace(dirPath) {
|
|
|
170
170
|
return { isGit: false, isWorktree: false }
|
|
171
171
|
}
|
|
172
172
|
|
|
173
|
+
/** @param {string} filePath @param {any} [opts] */
|
|
173
174
|
export function createTopicWorkspaceStore(filePath, { logger } = {}) {
|
|
174
175
|
let cache = { workspaces: {} }
|
|
175
176
|
try {
|
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.34",
|
|
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",
|
|
@@ -36,6 +36,9 @@
|
|
|
36
36
|
"test": "node --test test/*.test.mjs",
|
|
37
37
|
"test:load": "node scripts/verify-dsh-load.mjs",
|
|
38
38
|
"test:all": "npm test && npm run test:load && npm run pack:check",
|
|
39
|
+
"test:coverage": "node --test --experimental-test-coverage test/*.test.mjs",
|
|
40
|
+
"lint": "eslint .",
|
|
41
|
+
"typecheck": "tsc --noEmit",
|
|
39
42
|
"smoke:http": "node scripts/smoke-http.mjs",
|
|
40
43
|
"pack:check": "node scripts/pack-check.mjs"
|
|
41
44
|
},
|
|
@@ -60,8 +63,8 @@
|
|
|
60
63
|
"@deepseek-ai/dsh-llm": "^0.1.7-rc.2 || ^0.2.0-rc.1",
|
|
61
64
|
"@deepseek-ai/dsh-session": "^0.1.7-rc.2 || ^0.2.0-rc.1",
|
|
62
65
|
"@deepseek-ai/dsh-settings": "^0.1.7-rc.2 || ^0.2.0-rc.1",
|
|
63
|
-
"@deepseek-ai/
|
|
64
|
-
"@deepseek-ai/
|
|
66
|
+
"@deepseek-ai/dsh-tools": "^0.1.7-rc.2 || ^0.2.0-rc.1",
|
|
67
|
+
"@deepseek-ai/schemastery": "^3.18.2"
|
|
65
68
|
},
|
|
66
69
|
"publishConfig": {
|
|
67
70
|
"access": "public"
|
|
@@ -72,5 +75,11 @@
|
|
|
72
75
|
"overrides": {
|
|
73
76
|
"zod": "^4.6.6",
|
|
74
77
|
"fast-uri": "^3.1.9"
|
|
78
|
+
},
|
|
79
|
+
"devDependencies": {
|
|
80
|
+
"@types/node": "^24.19.2",
|
|
81
|
+
"eslint": "^9.39.5",
|
|
82
|
+
"globals": "^15.15.0",
|
|
83
|
+
"typescript": "^5.9.3"
|
|
75
84
|
}
|
|
76
85
|
}
|