@goodandready/dsh-messenger-gateway 0.4.20 → 0.4.22

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/commands.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { truncateSafe } from "./text.js"
1
2
  export const DEFAULT_TELEGRAM_COMMANDS = [
2
3
  { command: 'start', description: 'Connect and show greeting' },
3
4
  { command: 'help', description: 'Show commands help' },
@@ -46,7 +47,7 @@ export function normalizeTelegramCommands(commands) {
46
47
  command = command.slice(0, 32).toLowerCase()
47
48
  if (seen.has(command)) continue
48
49
  seen.add(command)
49
- out.push({ command, description: description.slice(0, 256) })
50
+ out.push({ command, description: truncateSafe(description, 256) })
50
51
  }
51
52
  return out.length ? out : [...DEFAULT_TELEGRAM_COMMANDS]
52
53
  }
@@ -65,7 +66,7 @@ export function mergeDynamicCommands(baseCommands = DEFAULT_TELEGRAM_COMMANDS, d
65
66
  if (!command || seen.has(command)) continue
66
67
  let description = String(item.description || item.title || `Skill ${command}`).trim()
67
68
  if (!description) description = `Skill ${command}`
68
- description = description.slice(0, 256)
69
+ description = truncateSafe(description, 256)
69
70
  seen.add(command)
70
71
  out.push({ command, description })
71
72
  }
@@ -1,31 +1,81 @@
1
1
  import { mergeDynamicCommands } from './commands.js'
2
2
  import { t } from './locales/index.js'
3
- import { stripReasoningPreamble, splitText } from './text.js'
3
+ import { stripReasoningPreamble, splitText, truncateSafe } from './text.js'
4
4
  import { stripImageUrls } from './outbound.js'
5
5
 
6
- export function collectDynamicSkills(ctx) {
7
- const skills = []
8
- try {
9
- const skillsService = ctx.get?.('skills') || ctx?.skills
10
- const allSkills = skillsService?.list?.() || []
11
- for (const s of allSkills) {
12
- if (!s || !s.name) continue
13
- if (s.userInvocable === false) continue
14
- skills.push({
15
- name: String(s.name),
16
- description: String(s.description || s.title || `Skill ${s.name}`).slice(0, 256),
17
- })
18
- }
19
- } catch (err) {
20
- ctx?.logger?.debug?.(`Failed to collect dynamic skills: ${err?.message || err}`)
6
+ export async function collectDynamicSkills(ctx) {
7
+ const skills = []
8
+ try {
9
+ const skillsService = ctx?.get ? ctx.get("skills") : ctx?.skills
10
+ if (!skillsService) return skills
11
+ const rawSkills = typeof skillsService.list === "function" ? skillsService.list() : []
12
+ const allSkills = (rawSkills && typeof rawSkills.then === "function") ? await rawSkills : (rawSkills || [])
13
+ for (const s of allSkills) {
14
+ if (!s || !s.name) continue
15
+ if (s.invocation?.userInvocable === false || s.userInvocable === false) continue
16
+ const rawDesc = String(s.description || s.title || `Skill ${s.name}`).trim()
17
+ skills.push({
18
+ name: String(s.name),
19
+ description: truncateSafe(rawDesc || `Skill ${s.name}`, 80),
20
+ })
21
21
  }
22
- return skills
22
+ } catch (err) {
23
+ ctx?.logger?.debug?.(`Failed to collect dynamic skills: ${err?.message || err}`)
24
+ }
25
+ return skills
26
+ }
27
+ /**
28
+ * Restore original hyphenated skill name from Telegram sanitized underscore command.
29
+ * E.g. /code_review -> /code-review
30
+ * Does not rewrite if the skill literally exists with underscores.
31
+ * Also strips optional @BotName mention.
32
+ */
33
+ export function restoreSkillGesture(gw, body) {
34
+ if (!body || !body.startsWith('/')) return body
35
+ const parts = body.split(/\s+/)
36
+ const firstToken = parts[0]
37
+ const atIdx = firstToken.indexOf('@')
38
+ const rawCmd = (atIdx !== -1 ? firstToken.slice(1, atIdx) : firstToken.slice(1)).toLowerCase()
39
+
40
+ // If a skill literally named `rawCmd` exists, do NOT rewrite
41
+ if (gw?.rawSkillNames?.has(rawCmd)) {
42
+ return atIdx !== -1 ? `/${rawCmd}${body.slice(firstToken.length)}` : body
43
+ }
44
+
45
+ // If mapped from sanitized form (e.g. code_review -> code-review)
46
+ const original = gw?.skillNameMap?.get(rawCmd)
47
+ if (original) {
48
+ return `/${original}${body.slice(firstToken.length)}`
23
49
  }
50
+
51
+ // Just strip @bot if present
52
+ if (atIdx !== -1) {
53
+ return `/${rawCmd}${body.slice(firstToken.length)}`
54
+ }
55
+
56
+ return body
57
+ }
58
+
24
59
  export async function syncTelegramCommands(gw) {
25
60
  const tgAdapter = gw.adapters.get('telegram')
26
61
  if (!tgAdapter || typeof tgAdapter.registerCommands !== 'function') return
27
62
  const baseCommands = gw.config.telegram?.commands || []
28
- const dynamicSkills = collectDynamicSkills(gw.ctx)
63
+ const dynamicSkills = await collectDynamicSkills(gw.ctx)
64
+
65
+ if (!gw.skillNameMap) gw.skillNameMap = new Map()
66
+ if (!gw.rawSkillNames) gw.rawSkillNames = new Set()
67
+ gw.skillNameMap.clear()
68
+ gw.rawSkillNames.clear()
69
+
70
+ for (const s of dynamicSkills) {
71
+ const rawName = String(s.name || '').trim()
72
+ if (!rawName) continue
73
+ gw.rawSkillNames.add(rawName.toLowerCase())
74
+ const sanitized = rawName.replace(/^\//, '').toLowerCase().replace(/[^a-z0-9_]/g, '_').slice(0, 32)
75
+ if (sanitized && sanitized !== rawName) {
76
+ gw.skillNameMap.set(sanitized, rawName)
77
+ }
78
+ }
29
79
  const merged = mergeDynamicCommands(baseCommands, dynamicSkills, 100)
30
80
  try {
31
81
  await tgAdapter.registerCommands(merged)
@@ -601,5 +601,6 @@ export async function handleGatewayCommand(gw, key, text, input) {
601
601
  return reply(t('msg.muted_off', {}, locale))
602
602
  }
603
603
 
604
- return reply(t('msg.unknown_command', { cmd }, locale))
604
+ // Unrecognized slash command: let it pass through to the underlying DSH agent (runtime commands, skills)
605
+ return { forwardToAgent: true }
605
606
  }
package/lib/gateway.js CHANGED
@@ -26,6 +26,7 @@ import { runGatewayTurn, buildUserContent, answerApproval } from './gateway-turn
26
26
  import {
27
27
  collectDynamicSkills, syncTelegramCommands,
28
28
  mirrorSessionToForumTopic, relayTurnToForumMirror,
29
+ restoreSkillGesture,
29
30
  } from './forum-mirror.js'
30
31
  import { resolveInternalBaseUrl } from './config.js'
31
32
  import { resolveEffectiveCwd, registerSessionInWorkspace } from './workspace.js'
@@ -84,6 +85,8 @@ export class Gateway {
84
85
  }, { logger: this.ctx?.logger || console })
85
86
  this.stats = { sent: 0, errors: 0, startedAt: Date.now() }
86
87
  this.apiHealth = new ApiHealthTracker({ logger: this.logger })
88
+ this.skillNameMap = new Map()
89
+ this.rawSkillNames = new Set()
87
90
  }
88
91
 
89
92
  get consecutiveApiFailures() {
@@ -390,7 +393,10 @@ export class Gateway {
390
393
  let attachments = [...(input.attachments || [])]
391
394
  const hasMedia = attachments.length > 0
392
395
  if (!body && !hasMedia) return
393
- if (body.startsWith('/')) { await this.handleCommand(key, body, input); return }
396
+ if (body.startsWith('/')) {
397
+ const cmdResult = await this.handleCommand(key, body, input)
398
+ if (!cmdResult?.forwardToAgent) return
399
+ }
394
400
  try {
395
401
  const chat = await this.getOrCreateChat(key, input)
396
402
  const photoOnlyMode = this.config.agent?.photoOnlyMode ?? 'prompt'
@@ -418,7 +424,38 @@ export class Gateway {
418
424
  break
419
425
  }
420
426
  }
421
- const turnInput = { ...input, text: body, attachments, inboundWasVoice, personaOverride }
427
+ const cleanBody = restoreSkillGesture(this, body)
428
+
429
+ // Try DSH runtime command execution (e.g. /compact, /goal, plugin commands)
430
+ if (body.startsWith('/')) {
431
+ const commandsService = this.ctx.get ? this.ctx.get('commands') : this.ctx?.commands
432
+ if (commandsService && typeof commandsService.execute === 'function') {
433
+ try {
434
+ const outcome = await commandsService.execute(chat.agent, cleanBody, attachments || [], chat.abort?.signal)
435
+ if (outcome !== undefined) {
436
+ const replyText = outcome?.result?.kind === 'text'
437
+ ? outcome.result.text
438
+ : (typeof outcome?.result?.text === 'string'
439
+ ? outcome.result.text
440
+ : (outcome?.result?.kind === 'error' ? (outcome.result.text || 'Command execution error') : undefined))
441
+ const cmdName = cleanBody.split(/\s+/)[0]
442
+ const msg = replyText ?? t('msg.command_done', { cmd: cmdName }, this.resolveLocale(input))
443
+ if (msg) {
444
+ await reply(msg)
445
+ }
446
+ return
447
+ }
448
+ } catch (cmdErr) {
449
+ if (chat.abort?.signal?.aborted) return
450
+ const errMsg = cmdErr instanceof Error ? cmdErr.message : String(cmdErr)
451
+ this.ctx.logger?.warn?.(`dsh-messenger-gateway: runtime command: ${errMsg}`)
452
+ try { await reply(t('msg.exception', { message: errMsg }, this.resolveLocale(input))) } catch (repErr) { this.recordApiFailure('reply.exception', repErr) }
453
+ return
454
+ }
455
+ }
456
+ }
457
+
458
+ const turnInput = { ...input, text: cleanBody, attachments, inboundWasVoice, personaOverride }
422
459
 
423
460
  // Hermes-like steer: while a turn is running, inject followup instead of abort+restart
424
461
  if (this.isChatBusy(chat)) {
@@ -468,8 +505,22 @@ export class Gateway {
468
505
  return handleGatewayCommand(this, key, text, input)
469
506
  }
470
507
 
471
- collectDynamicSkills() {
472
- return collectDynamicSkills(this.ctx)
508
+ async collectDynamicSkills() {
509
+ const skills = await collectDynamicSkills(this.ctx)
510
+ if (!this.skillNameMap) this.skillNameMap = new Map()
511
+ if (!this.rawSkillNames) this.rawSkillNames = new Set()
512
+ this.skillNameMap.clear()
513
+ this.rawSkillNames.clear()
514
+ for (const s of skills) {
515
+ const rawName = String(s.name || '').trim()
516
+ if (!rawName) continue
517
+ this.rawSkillNames.add(rawName.toLowerCase())
518
+ const sanitized = rawName.replace(/^\//, '').toLowerCase().replace(/[^a-z0-9_]/g, '_').slice(0, 32)
519
+ if (sanitized && sanitized !== rawName) {
520
+ this.skillNameMap.set(sanitized, rawName)
521
+ }
522
+ }
523
+ return skills
473
524
  }
474
525
 
475
526
  async syncTelegramCommands() {
package/lib/locales/en.js CHANGED
@@ -36,6 +36,7 @@ export const en = {
36
36
  'msg.start': 'Gateway connected. Send messages to the agent. /help for commands.',
37
37
  'msg.steer_added': '↪️ Added to current turn',
38
38
  'msg.turn_stopped': 'Turn interrupted.',
39
+ 'msg.command_done': 'Command {cmd} completed.',
39
40
  'msg.no_active_session': 'No active session found.',
40
41
  'msg.unknown_command': 'Unknown command {cmd}. /help',
41
42
  'msg.not_allowed': 'Access denied. Ask the owner to whitelist your ID.',
package/lib/locales/zh.js CHANGED
@@ -36,6 +36,7 @@ export const zh = {
36
36
  'msg.start': '网关已连接。请向智能体发送消息。发送 /help 查看命令。',
37
37
  'msg.steer_added': '↪️ 已追加到当前回答',
38
38
  'msg.turn_stopped': '回答已中断。',
39
+ 'msg.command_done': '命令 {cmd} 执行完成。',
39
40
  'msg.no_active_session': '未找到活跃会话。',
40
41
  'msg.unknown_command': '未知命令 {cmd}。发送 /help',
41
42
  'msg.not_allowed': '访问受限。请联系管理员将您的ID加入白名单。',
package/lib/text.js CHANGED
@@ -37,3 +37,21 @@ export function stripReasoningPreamble(text) {
37
37
  }
38
38
 
39
39
  export const MESSENGER_RELAY_INSTRUCTION = 'Channel: Messenger. Reply concisely and directly to the user. Do not leak internal reasoning or planning traces.'
40
+
41
+ /**
42
+ * Truncate string to maxLen without splitting UTF-16 surrogate pairs.
43
+ * If the cut falls on a high surrogate, drops the high surrogate so the string is well-formed.
44
+ */
45
+ export function truncateSafe(str, maxLen = 80) {
46
+ const raw = String(str ?? '')
47
+ if (raw.length <= maxLen) return raw
48
+ let sliced = raw.slice(0, maxLen)
49
+ const lastCode = sliced.charCodeAt(sliced.length - 1)
50
+ if (lastCode >= 0xD800 && lastCode <= 0xDBFF) {
51
+ sliced = sliced.slice(0, -1)
52
+ }
53
+ if (typeof sliced.isWellFormed === 'function' && !sliced.isWellFormed()) {
54
+ sliced = sliced.replace(/[\uD800-\uDFFF]+$/, '')
55
+ }
56
+ return sliced
57
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-messenger-gateway",
3
- "version": "0.4.20",
3
+ "version": "0.4.22",
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",