@goodandready/dsh-messenger-gateway 0.4.33 → 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.
@@ -64,7 +64,7 @@ export class DiscordAdapter {
64
64
  this.stopped = true
65
65
  }
66
66
 
67
- async sendTo(channelId, payload, opts = {}) {
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, parseDocument } from '../documents.js'
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 || ''
@@ -1,9 +1,8 @@
1
1
  import { readFile } from 'node:fs/promises'
2
2
  import {
3
- IMAGE_EXT_TO_MIME, VIDEO_EXT_TO_MIME, basename, cacheName, classifyDocument,
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, webAppUrl = '' } = options
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
@@ -30,7 +30,7 @@ export function resolveSafePath(baseCwd, userPath = '.') {
30
30
  const isDrivePath = /^[a-zA-Z]:/.test(cleanUser)
31
31
  const rel = relative(base, target)
32
32
  if (isAbsolute(cleanUser) || isDrivePath || rel.startsWith('..') || isAbsolute(rel) || (rel && resolve(base, rel) !== target)) {
33
- 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'))
34
34
  err.code = 'ERR_PATH_TRAVERSAL'
35
35
  throw err
36
36
  }
@@ -40,7 +40,7 @@ export function resolveSafePath(baseCwd, userPath = '.') {
40
40
  try {
41
41
  const realTarget = realpathSync(target)
42
42
  if (!isSubpath(realBase, realTarget)) {
43
- 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'))
44
44
  err.code = 'ERR_PATH_TRAVERSAL'
45
45
  throw err
46
46
  }
@@ -52,7 +52,7 @@ export function resolveSafePath(baseCwd, userPath = '.') {
52
52
  try {
53
53
  const realCurr = realpathSync(curr)
54
54
  if (!isSubpath(realBase, realCurr)) {
55
- 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'))
56
56
  err.code = 'ERR_PATH_TRAVERSAL'
57
57
  throw err
58
58
  }
@@ -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, event) {
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)
@@ -1,11 +1,10 @@
1
- import { escapeHtml } from './telegram-format.js'
2
1
  import { t } from './locales/index.js'
3
2
  import {
4
3
  parseCallbackData, parseAskCallback, targetMatchesAsk,
5
4
  releaseCallbacks, buildMultiSelectKeyboard, indexCallbacks, REMOVE_KEYBOARD
6
5
  } from './ask.js'
7
6
  import {
8
- listModelCatalog, buildProvidersKeyboard, buildModelsKeyboard, storeModelSelection,
7
+ listModelCatalog, buildProvidersKeyboard, buildModelsKeyboard,
9
8
  getStoredModelSelection
10
9
  } from './models.js'
11
10
 
@@ -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
  }
@@ -827,7 +827,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
827
827
  ].join('\n'))
828
828
  }
829
829
  const dueAt = Date.now() + delayMs
830
- const task = await gw.scheduler.schedule({
830
+ await gw.scheduler.schedule({
831
831
  platform: platform || 'telegram',
832
832
  chatId,
833
833
  threadId: threadId || 0,
@@ -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, stripReasoningPreamble, splitText } from './text.js'
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 { processDiagramsAndTables, processDiagramsAndTablesAsync } from './artifacts.js'
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, parseReasoningStream, formatReasoningFinal
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'
@@ -279,10 +279,10 @@ export async function runGatewayTurn(gw, chat, input, signal) {
279
279
 
280
280
 
281
281
  const content = await gw.buildUserContent(input, signal)
282
- chat.agent.followup(createUserMessage({
282
+ chat.agent.followup(createUserMessage(/** @type {any} */ ({
283
283
  content: ensureContentArray(content),
284
284
  source: { kind: 'user', plugin: PLUGIN, form: 'relay', origin: 'telegram' },
285
- }))
285
+ })))
286
286
  const turnTimeoutMs = Number(gw.config.agent?.turnTimeoutMs) || 600_000
287
287
  await whenIdleWithTimeout(chat.agent, turnTimeoutMs, signal)
288
288
  if (signal.aborted) {
@@ -310,7 +310,7 @@ export async function runGatewayTurn(gw, chat, input, signal) {
310
310
  chatId: input.chatId,
311
311
  webAppUrl: gw.resolveWebAppUrl?.() || '',
312
312
  })
313
- const answer = processed.text
313
+ let answer = processed.text
314
314
  if (collector.reason?.kind === 'error') {
315
315
  const err = collector.reason.error
316
316
  const msg = t('msg.agent_error', { code: err?.code || 'error', message: err?.message || 'unknown' }, gw.resolveLocale(input))
package/lib/gateway.js CHANGED
@@ -457,7 +457,7 @@ export class Gateway {
457
457
  }
458
458
 
459
459
  async handleMessage(input) {
460
- const { platform, chatId, threadId = 0, text, reply } = input
460
+ const { text, reply } = input
461
461
  const key = this.sessionKeyFor(input)
462
462
  const body = String(text || '').trim()
463
463
  let attachments = [...(input.attachments || [])]
@@ -544,10 +544,10 @@ export class Gateway {
544
544
  text: steerText,
545
545
  steer: true,
546
546
  }, undefined)
547
- chat.agent.followup(createUserMessage({
547
+ chat.agent.followup(createUserMessage(/** @type {any} */ ({
548
548
  content: ensureContentArray(content),
549
549
  source: { kind: 'user', plugin: PLUGIN, form: 'steer', origin: 'telegram' },
550
- }))
550
+ })))
551
551
  chat.lastUsed = Date.now()
552
552
  try { await reply(t('msg.steer_added', {}, this.resolveLocale(input))) } catch (err) { this.recordApiFailure('reply.steer_added', err) }
553
553
  return
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 и т. п.) не отдаются браузеру, а карточка сохраняет секции
@@ -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
- export async function recordTurnMemory({ config, userId, userText, assistantText, signal, logger }) {
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
 
@@ -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
@@ -70,6 +70,7 @@ export function listPersonas() {
70
70
  return Object.values(BUILTIN_PERSONAS)
71
71
  }
72
72
 
73
+ /** @param {string} filePath @param {any} [opts] */
73
74
  export function createPersonaStore(filePath, { logger } = {}) {
74
75
  let cache = { personas: {}, presets: {} }
75
76
  try {
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
- function wrapTls(socket, servername, { signal } = {}) {
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,
@@ -1,4 +1,4 @@
1
- export function exportSessionToMarkdown(session, opts = {}) {
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'
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)) {
@@ -15,6 +15,7 @@ function writeJsonAtomicSync(filePath, data) {
15
15
  }
16
16
  }
17
17
 
18
+ /** @param {string} filePath @param {any} [opts] */
18
19
  export function createVoicePrefs(filePath, { logger } = {}) {
19
20
  /** @type {Record<string, boolean>} */
20
21
  let state = {}
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, normalize, basename } from 'node:path'
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.33",
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/schemastery": "^3.18.2",
64
- "@deepseek-ai/dsh-tools": "^0.1.7-rc.2 || ^0.2.0-rc.1"
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
  }