@goodandready/dsh-messenger-gateway 0.4.45 → 0.4.47

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/README.md CHANGED
@@ -164,6 +164,9 @@ In addition to Telegram, outbound messages can be dispatched to Discord and Slac
164
164
  - All state files (pairing, outbox, voice prefs) are written with `0600` permissions inside `0700` directories
165
165
  - State persistence is durable and versioned: every write is fsynced before the rename (directory fsynced after), each save keeps a `.bak` of the previous good version, files carry a `schemaVersion` with migrations from legacy formats, and a corrupted file is preserved as `.corrupt-<ts>` and recovered from `.bak` — pairing never silently wipes access (fail-closed with an explicit error)
166
166
  - Config sync is granular: changes that do not touch the transport slice (tokens, proxy, Bot API root, poll/webhook mode, adapter enablement, session scope) are applied live on the running gateway — active dialogs, streaming replies, pending asks and the Telegram polling offset survive a settings save; only transport changes recreate the gateway, and recreation is serialized (single-flight)
167
+ - Hot path stays async: cwd resolution is cached (10 s TTL) so inbound messages never run synchronous `stat`/`realpath` (matters on network filesystems), outbox persistence batches enqueue bursts into one debounced write and is forced out on `stop()`; the plugin also loads cleanly into profiles without a webServer service (routes are skipped with a warning), and a reload/dispose never leaves a stopped gateway reachable
168
+ - `/mute` (per chat) stops ALL outbound delivery to that chat — notify bridge, `messenger.send`, HTTP sends, cron prompts and forum mirroring report `{ok, muted}` and skip delivery; the interactive turn conversation is unaffected, and the dashboard shows real outbox/DLQ counters
169
+ - The settings card is generated from the config schema: every setting is visible and editable (the advanced section covers allowlist mode, bot language, approval sensitivity, streaming, Mini App, cost footer, budget alerts, forum mirror and memory injection), secrets are only reported as configured-flags and never returned to the browser
167
170
  - `sessionList`: `true` (default) — enables `/sessions` and `/resume` commands in chat
168
171
  - `sessionTitleFromChat`: `false` (default) — name each new session after its originating chat (`TG · @user`, `TG · Group › topic N`) instead of generic generated titles
169
172
  - `voiceMode`: `mirror` / `always` / `off` — when to speak replies (also `/voice`)
package/README.ru.md CHANGED
@@ -101,6 +101,8 @@ graph LR
101
101
  * Команды `/get` и `/files` доступны только пользователям из белого списка и никогда не отдают скрытые файлы (dotfiles, например `.env`);
102
102
  * Loopback-запросы доверяются только с закреплёнными Host (`localhost` / `127.0.0.1` / `[::1]`) — защита от DNS rebinding; для доверенного локального reverse-proxy есть явный флаг `security.trustProxy`.
103
103
  * Живучесть состояния: записи состояния атомарны с fsync, версионированы (`schemaVersion` + миграции), каждая запись хранит `.bak` прошлой версии, повреждённый файл сохраняется как `.corrupt-*` и восстанавливается из `.bak` — доступ никогда не обнуляется молча (fail-closed + явная ошибка);
104
+ * Карточка настроек строится из схемы конфигурации: все настройки видимы и редактируемы (в расширенной секции — режим белого списка, язык бота, чувствительность подтверждений, стриминг, Mini App, футер стоимости, бюджетные алерты, зеркалирование в форумы и инъекция памяти), секреты отдаются только флагом «настроен» и никогда не возвращаются в браузер; `/mute` останавливает ВСЮ исходящую доставку в чат (notify bridge, messenger.send, HTTP, cron, зеркалирование), не затрагивая живой диалог;
105
+ * Горячий путь асинхронный: резолв cwd кэшируется (TTL 10 с) — входящие сообщения не выполняют синхронных stat/realpath (важно для сетевых ФС); запись outbox батчится (одно отложенное сохранение на всплеск enqueue) и принудительно сбрасывается при остановке; плагин загружается и без сервиса webServer (маршруты пропускаются с предупреждением), а после reload/dispose остановленный gateway недостижим;
104
106
 
105
107
  ### 6. 🤖 Команды бота (`commands.js`)
106
108
  * `/start` — приветствие и запуск сопряжения;
package/README.zh.md CHANGED
@@ -87,6 +87,8 @@ dsh plugin --profile web add @goodandready/dsh-messenger-gateway
87
87
  - `/get` 与 `/files` 命令仅对白名单用户可用,且永远不会返回隐藏文件(dotfiles,如 `.env`);
88
88
  - 本地回环请求只接受固定的 Host(`localhost` / `127.0.0.1` / `[::1]`)— 防 DNS Rebinding;如需在受信任的本地反向代理后使用,可显式开启 `security.trustProxy`。
89
89
  - 持久化状态:写入先 fsync 再原子重命名,文件带 `schemaVersion`(旧格式自动迁移),每次保存保留 `.bak`,损坏文件以 `.corrupt-*` 保留并可从 `.bak` 恢复——绝不静默清空访问(fail-closed + 显式错误);
90
+ - 设置卡片由配置 schema 生成:所有设置均可见可编辑(高级区含白名单模式、机器人语言、审批灵敏度、流式回复、Mini App、成本页脚、预算告警、论坛镜像与记忆注入);机密只以「已配置」标志形式报告,绝不返回浏览器;`/mute` 停止向该聊天的所有出站投递(notify bridge、messenger.send、HTTP、cron、论坛镜像),不影响实时对话;
91
+ - 热路径全异步:cwd 解析带 10 秒缓存,入站消息不再执行同步 stat/realpath(网络文件系统尤其重要);outbox 持久化按突发批量合并写入,stop() 时强制落盘;无 webServer 服务的环境也能加载插件(路由跳过并告警),reload/dispose 后不会残留已停止的 gateway;
90
92
 
91
93
  ---
92
94
 
package/lib/client.js CHANGED
@@ -178,6 +178,31 @@ window.__ModuleLoader__.load({
178
178
  // Cron badge
179
179
  'badge.cron_count': 'Cron: {count}',
180
180
  'badge.api_degraded': 'Telegram API degraded ({count})',
181
+ // Settings parity (issue 237): schema fields surfaced in the card
182
+ allowlistMode: 'Allowlist Mode',
183
+ allowlistModeHint: 'closed (default) refuses unknown users until paired; open admits everyone when the list is empty — for public bots only.',
184
+ allowlistClosed: 'closed (fail-closed)',
185
+ allowlistOpen: 'open (public)',
186
+ defaultLocale: 'Bot Language',
187
+ defaultLocaleHint: 'Language for bot service messages (en / zh).',
188
+ webAppEnabled: 'Mini App dashboard enabled',
189
+ webAppUrl: 'Mini App URL',
190
+ webAppUrlHint: 'Public HTTPS URL; empty = auto-detect from webhook origin.',
191
+ costFooter: 'Show cost footer under replies',
192
+ budgetAlert: 'Budget alert threshold (USD, 0 = off)',
193
+ forumMirrorEnable: 'Mirror replies into forum topics',
194
+ forumMirrorChat: 'Forum mirror chat ID',
195
+ memoryEnable: 'Inject agent memories (memory-brain)',
196
+ memoryBaseUrl: 'Memory service URL',
197
+ memoryBaseUrlHint: 'Default http://127.0.0.1:28080; empty = default.',
198
+ approvalsSensitivity: 'Approval Sensitivity',
199
+ approvalsSensitivityHint: 'Which tool calls require confirmation before execution.',
200
+ sensAll: 'all tool calls',
201
+ sensMutations: 'mutations only',
202
+ sensDisabled: 'disabled',
203
+ streamingEnable: 'Stream replies into one message',
204
+ streamEditInterval: 'Stream edit interval (ms)',
205
+ mediaGroupDebounce: 'Album grouping debounce (ms)',
181
206
  }
182
207
 
183
208
  const zh = {
@@ -332,6 +357,31 @@ window.__ModuleLoader__.load({
332
357
  // Cron badge
333
358
  'badge.cron_count': '定时任务: {count}',
334
359
  'badge.api_degraded': 'Telegram API 异常 ({count} 次连续错误)',
360
+ // Settings parity (issue 237)
361
+ allowlistMode: '白名单模式',
362
+ allowlistModeHint: 'closed(默认)在配对通过前拒绝未知用户;open 在列表为空时放行所有人——仅适用于公共机器人。',
363
+ allowlistClosed: 'closed(默认拒绝)',
364
+ allowlistOpen: 'open(公共)',
365
+ defaultLocale: '机器人语言',
366
+ defaultLocaleHint: '机器人服务消息的语言(en / zh)。',
367
+ webAppEnabled: '启用 Mini App 面板',
368
+ webAppUrl: 'Mini App 地址',
369
+ webAppUrlHint: '公网 HTTPS 地址;留空则从 webhook 来源自动推断。',
370
+ costFooter: '在回复下方显示成本页脚',
371
+ budgetAlert: '预算告警阈值(USD,0 = 关闭)',
372
+ forumMirrorEnable: '将回复镜像到论坛话题',
373
+ forumMirrorChat: '论坛镜像 chat ID',
374
+ memoryEnable: '注入代理记忆(memory-brain)',
375
+ memoryBaseUrl: '记忆服务地址',
376
+ memoryBaseUrlHint: '默认 http://127.0.0.1:28080;留空使用默认值。',
377
+ approvalsSensitivity: '审批灵敏度',
378
+ approvalsSensitivityHint: '哪些工具调用需要先确认再执行。',
379
+ sensAll: '所有工具调用',
380
+ sensMutations: '仅修改型调用',
381
+ sensDisabled: '禁用',
382
+ streamingEnable: '将回复流式写入同一条消息',
383
+ streamEditInterval: '流式编辑间隔(毫秒)',
384
+ mediaGroupDebounce: '相册分组防抖(毫秒)',
335
385
  }
336
386
 
337
387
 
@@ -476,7 +526,7 @@ window.__ModuleLoader__.load({
476
526
  )
477
527
  }
478
528
 
479
- const SETTINGS_KEYS = ['enabled', 'telegram', 'discord', 'slack', 'agent', 'media', 'tts']
529
+ const SETTINGS_KEYS = ['enabled', 'defaultLocale', 'telegram', 'discord', 'slack', 'agent', 'media', 'tts', 'memory']
480
530
 
481
531
  function draftFromStored(s) {
482
532
  const src = (s && typeof s === 'object') ? s : {}
@@ -486,11 +536,14 @@ window.__ModuleLoader__.load({
486
536
  const a = src.agent || {}
487
537
  const m = src.media || {}
488
538
  const tts = src.tts || {}
539
+ const mem = src.memory || {}
489
540
  return {
490
541
  enabled: src.enabled !== false,
542
+ defaultLocale: src.defaultLocale === 'zh' ? 'zh' : 'en',
491
543
  telegram: {
492
544
  enabled: t.enabled === true,
493
545
  allowedUserIds: Array.isArray(t.allowedUserIds) ? t.allowedUserIds : [],
546
+ allowlistMode: t.allowlistMode === 'open' ? 'open' : 'closed',
494
547
  pollTimeoutSeconds: Number(t.pollTimeoutSeconds) || 50,
495
548
  pollIntervalMs: Number(t.pollIntervalMs) || 500,
496
549
  commands: Array.isArray(t.commands) ? t.commands : [],
@@ -516,9 +569,20 @@ window.__ModuleLoader__.load({
516
569
  transport: t.transport === 'webhook' ? 'webhook' : 'poll',
517
570
  webhookUrl: t.webhookUrl || '',
518
571
  webhookPath: t.webhookPath || '/dsh-messenger-gateway/telegram/webhook',
572
+ // Configured-flags come from the server projection (issue 237): the badge
573
+ // and placeholder must reflect the STORED secret, not the draft.
574
+ webhookSecretConfigured: t.webhookSecretConfigured === true,
575
+ botTokenConfigured: t.botTokenConfigured === true,
519
576
  voiceMode: t.voiceMode || 'mirror',
520
577
  quickActions: t.quickActions === true,
521
578
  artifactPreviews: t.artifactPreviews !== false,
579
+ webAppEnabled: t.webAppEnabled !== false,
580
+ webAppUrl: t.webAppUrl || '',
581
+ costFooter: t.costFooter === true,
582
+ budgetAlertThresholdUsd: Number(t.budgetAlertThresholdUsd) || 0,
583
+ mediaGroupDebounceMs: Number(t.mediaGroupDebounceMs) || 650,
584
+ forumMirrorEnabled: t.forumMirrorEnabled === true,
585
+ forumMirrorChatId: t.forumMirrorChatId != null ? t.forumMirrorChatId : '',
522
586
  notifyBridge: t.notifyBridge || { enabled: false, events: ['task_done', 'error'], home: 'default', excludeSessionPrefixes: ['msgw-'] },
523
587
  alerts: t.alerts || { enabled: false, chatId: '', threadId: 0, home: '', events: ['error', 'pairing'] },
524
588
  botToken: t.botToken || '',
@@ -530,13 +594,11 @@ window.__ModuleLoader__.load({
530
594
  enabled: d.enabled === true,
531
595
  botToken: d.botToken || '',
532
596
  webhookUrl: d.webhookUrl || '',
533
- allowedChannelIds: Array.isArray(d.allowedChannelIds) ? d.allowedChannelIds : [],
534
597
  },
535
598
  slack: {
536
599
  enabled: sl.enabled === true,
537
600
  botToken: sl.botToken || '',
538
601
  webhookUrl: sl.webhookUrl || '',
539
- defaultChannel: sl.defaultChannel || '',
540
602
  },
541
603
  agent: {
542
604
  provider: a.provider || '',
@@ -559,6 +621,14 @@ window.__ModuleLoader__.load({
559
621
  maxChars: Number(tts.maxChars) || 4000,
560
622
  voiceSummary: tts.voiceSummary === true,
561
623
  },
624
+ memory: {
625
+ enabled: mem.enabled !== false,
626
+ baseUrl: typeof mem.baseUrl === 'string' ? mem.baseUrl : '',
627
+ tokenEnv: mem.tokenEnv || 'MEMORY_BRAIN_TOKEN',
628
+ autoInject: mem.autoInject !== false,
629
+ budget: Number(mem.budget) || 2000,
630
+ timeoutMs: Number(mem.timeoutMs) || 3500,
631
+ },
562
632
  }
563
633
  }
564
634
 
@@ -571,7 +641,6 @@ window.__ModuleLoader__.load({
571
641
  const [allowText, setAllowText] = React.useState('')
572
642
  const [discordToken, setDiscordToken] = React.useState('')
573
643
  const [slackToken, setSlackToken] = React.useState('')
574
- const [discordChannelsText, setDiscordChannelsText] = React.useState('')
575
644
  const [updateState, setUpdateState] = React.useState({
576
645
  checking: false,
577
646
  updating: false,
@@ -612,7 +681,6 @@ window.__ModuleLoader__.load({
612
681
  if (snapStatus === 'ready' && cfg === null) {
613
682
  setCfg(draftFromStored(stored))
614
683
  setAllowText(idsToText(stored?.telegram?.allowedUserIds))
615
- setDiscordChannelsText(idsToText(stored?.discord?.allowedChannelIds))
616
684
  }
617
685
  }, [snapStatus, stored, cfg])
618
686
 
@@ -752,7 +820,6 @@ window.__ModuleLoader__.load({
752
820
  next.telegram.allowedUserIds = textToIds(allowText)
753
821
  if (discordToken.trim()) next.discord = { ...next.discord, botToken: discordToken.trim() }
754
822
  if (slackToken.trim()) next.slack = { ...next.slack, botToken: slackToken.trim() }
755
- next.discord.allowedChannelIds = textToIds(discordChannelsText)
756
823
 
757
824
  const broken = []
758
825
  for (const key of SETTINGS_KEYS) {
@@ -1304,15 +1371,6 @@ window.__ModuleLoader__.load({
1304
1371
  placeholder: 'https://discord.com/api/webhooks/...',
1305
1372
  onChange: (e) => setCfg({ ...cfg, discord: { ...cfg.discord, webhookUrl: e.target.value } }),
1306
1373
  })
1307
- ),
1308
- React.createElement(Field, { label: t('discordChannels'), hint: t('discordChannelsHint') },
1309
- React.createElement('textarea', {
1310
- className: 'msgw-textarea',
1311
- value: discordChannelsText,
1312
- onChange: (e) => setDiscordChannelsText(e.target.value),
1313
- rows: 2,
1314
- placeholder: '123456789012345678, 987654321098765432',
1315
- })
1316
1374
  )
1317
1375
  ),
1318
1376
 
@@ -1352,14 +1410,6 @@ window.__ModuleLoader__.load({
1352
1410
  placeholder: 'https://hooks.slack.com/services/...',
1353
1411
  onChange: (e) => setCfg({ ...cfg, slack: { ...cfg.slack, webhookUrl: e.target.value } }),
1354
1412
  })
1355
- ),
1356
- React.createElement(Field, { label: t('slackDefaultChannel'), hint: t('slackDefaultChannelHint') },
1357
- React.createElement('input', {
1358
- className: 'msgw-input',
1359
- value: cfg.slack?.defaultChannel || '',
1360
- placeholder: '#general or C12345678',
1361
- onChange: (e) => setCfg({ ...cfg, slack: { ...cfg.slack, defaultChannel: e.target.value } }),
1362
- })
1363
1413
  )
1364
1414
  ),
1365
1415
 
@@ -1570,6 +1620,138 @@ window.__ModuleLoader__.load({
1570
1620
  value: Math.round((cfg.agent?.idleTimeoutMs ?? 3600000) / 1000),
1571
1621
  onChange: (e) => setCfg({ ...cfg, agent: { ...cfg.agent, idleTimeoutMs: (Number(e.target.value) || 3600) * 1000 } }),
1572
1622
  })
1623
+ ),
1624
+ // Settings parity (issue 237): schema fields that had no UI surface.
1625
+ React.createElement(Field, { label: t('allowlistMode'), hint: t('allowlistModeHint') },
1626
+ React.createElement(
1627
+ 'select',
1628
+ {
1629
+ className: 'msgw-select',
1630
+ value: cfg.telegram?.allowlistMode || 'closed',
1631
+ onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, allowlistMode: e.target.value } }),
1632
+ },
1633
+ React.createElement('option', { value: 'closed' }, t('allowlistClosed')),
1634
+ React.createElement('option', { value: 'open' }, t('allowlistOpen'))
1635
+ )
1636
+ ),
1637
+ React.createElement(Field, { label: t('defaultLocale'), hint: t('defaultLocaleHint') },
1638
+ React.createElement(
1639
+ 'select',
1640
+ {
1641
+ className: 'msgw-select',
1642
+ value: cfg.defaultLocale || 'en',
1643
+ onChange: (e) => setCfg({ ...cfg, defaultLocale: e.target.value }),
1644
+ },
1645
+ React.createElement('option', { value: 'en' }, 'English'),
1646
+ React.createElement('option', { value: 'zh' }, '中文')
1647
+ )
1648
+ ),
1649
+ React.createElement(Field, { label: t('approvalsSensitivity'), hint: t('approvalsSensitivityHint') },
1650
+ React.createElement(
1651
+ 'select',
1652
+ {
1653
+ className: 'msgw-select',
1654
+ value: cfg.telegram?.approvalsSensitivity || 'mutations',
1655
+ onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, approvalsSensitivity: e.target.value } }),
1656
+ },
1657
+ React.createElement('option', { value: 'all' }, t('sensAll')),
1658
+ React.createElement('option', { value: 'mutations' }, t('sensMutations')),
1659
+ React.createElement('option', { value: 'disabled' }, t('sensDisabled'))
1660
+ )
1661
+ ),
1662
+ React.createElement('label', { className: 'msgw-check' },
1663
+ React.createElement('input', {
1664
+ type: 'checkbox',
1665
+ checked: cfg.telegram?.streaming === true,
1666
+ onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, streaming: e.target.checked } }),
1667
+ }),
1668
+ t('streamingEnable')
1669
+ ),
1670
+ React.createElement(Field, { label: t('streamEditInterval') },
1671
+ React.createElement('input', {
1672
+ type: 'number',
1673
+ className: 'msgw-input',
1674
+ min: 200,
1675
+ max: 10000,
1676
+ value: cfg.telegram?.streamEditIntervalMs ?? 1200,
1677
+ onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, streamEditIntervalMs: Number(e.target.value) || 1200 } }),
1678
+ })
1679
+ ),
1680
+ React.createElement(Field, { label: t('mediaGroupDebounce') },
1681
+ React.createElement('input', {
1682
+ type: 'number',
1683
+ className: 'msgw-input',
1684
+ min: 0,
1685
+ max: 5000,
1686
+ value: cfg.telegram?.mediaGroupDebounceMs ?? 650,
1687
+ onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, mediaGroupDebounceMs: Number(e.target.value) || 650 } }),
1688
+ })
1689
+ ),
1690
+ React.createElement('label', { className: 'msgw-check' },
1691
+ React.createElement('input', {
1692
+ type: 'checkbox',
1693
+ checked: cfg.telegram?.webAppEnabled !== false,
1694
+ onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, webAppEnabled: e.target.checked } }),
1695
+ }),
1696
+ t('webAppEnabled')
1697
+ ),
1698
+ React.createElement(Field, { label: t('webAppUrl'), hint: t('webAppUrlHint') },
1699
+ React.createElement('input', {
1700
+ className: 'msgw-input',
1701
+ value: cfg.telegram?.webAppUrl || '',
1702
+ placeholder: 'https://bot.example.com',
1703
+ onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, webAppUrl: e.target.value } }),
1704
+ })
1705
+ ),
1706
+ React.createElement('label', { className: 'msgw-check' },
1707
+ React.createElement('input', {
1708
+ type: 'checkbox',
1709
+ checked: cfg.telegram?.costFooter === true,
1710
+ onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, costFooter: e.target.checked } }),
1711
+ }),
1712
+ t('costFooter')
1713
+ ),
1714
+ React.createElement(Field, { label: t('budgetAlert') },
1715
+ React.createElement('input', {
1716
+ type: 'number',
1717
+ step: '0.5',
1718
+ min: 0,
1719
+ className: 'msgw-input',
1720
+ value: cfg.telegram?.budgetAlertThresholdUsd ?? 0,
1721
+ onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, budgetAlertThresholdUsd: Number(e.target.value) || 0 } }),
1722
+ })
1723
+ ),
1724
+ React.createElement('label', { className: 'msgw-check' },
1725
+ React.createElement('input', {
1726
+ type: 'checkbox',
1727
+ checked: cfg.telegram?.forumMirrorEnabled === true,
1728
+ onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, forumMirrorEnabled: e.target.checked } }),
1729
+ }),
1730
+ t('forumMirrorEnable')
1731
+ ),
1732
+ React.createElement(Field, { label: t('forumMirrorChat') },
1733
+ React.createElement('input', {
1734
+ className: 'msgw-input',
1735
+ value: cfg.telegram?.forumMirrorChatId || '',
1736
+ placeholder: '-1001234567890',
1737
+ onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, forumMirrorChatId: e.target.value } }),
1738
+ })
1739
+ ),
1740
+ React.createElement('label', { className: 'msgw-check' },
1741
+ React.createElement('input', {
1742
+ type: 'checkbox',
1743
+ checked: cfg.memory?.enabled !== false,
1744
+ onChange: (e) => setCfg({ ...cfg, memory: { ...cfg.memory, enabled: e.target.checked } }),
1745
+ }),
1746
+ t('memoryEnable')
1747
+ ),
1748
+ React.createElement(Field, { label: t('memoryBaseUrl'), hint: t('memoryBaseUrlHint') },
1749
+ React.createElement('input', {
1750
+ className: 'msgw-input',
1751
+ value: cfg.memory?.baseUrl || '',
1752
+ placeholder: 'http://127.0.0.1:28080',
1753
+ onChange: (e) => setCfg({ ...cfg, memory: { ...cfg.memory, baseUrl: e.target.value } }),
1754
+ })
1573
1755
  )
1574
1756
  ) : null
1575
1757
  ),
package/lib/config.js CHANGED
@@ -80,12 +80,8 @@ export const PluginConfig = z.object({
80
80
  home: z.string().default(''),
81
81
  events: z.array(z.string()).default(['error', 'pairing']),
82
82
  }).default({ enabled: false }),
83
- forumMirror: z.object({
84
- enabled: z.boolean().default(false),
85
- chatId: z.union([z.number(), z.string()]).default(''),
86
- }).default({ enabled: false }),
87
- forumMirrorChatId: z.union([z.number(), z.string()]).default(''),
88
- forumMirrorEnabled: z.boolean().default(false),
83
+ forumMirrorChatId: z.union([z.number(), z.string()]).default('').description('Mirror assistant replies of every session into this forum topic chat'),
84
+ forumMirrorEnabled: z.boolean().default(false).description('Mirror assistant replies into a dedicated forum topic per session'),
89
85
  }).volatile(),
90
86
  discord: z.object({
91
87
  enabled: z.boolean().default(false),
@@ -92,6 +92,7 @@ export async function mirrorSessionToForumTopic(gw, session) {
92
92
 
93
93
  const tgCfg = gw.config.telegram || {}
94
94
  if (!tgCfg.forumMirrorEnabled || !tgCfg.forumMirrorChatId) return
95
+ if (gw.isMuted?.(tgCfg.forumMirrorChatId)) return
95
96
 
96
97
  const tgAdapter = gw.adapters.get('telegram')
97
98
  if (!tgAdapter || typeof tgAdapter.createForumTopic !== 'function') return
@@ -121,6 +122,8 @@ export async function relayTurnToForumMirror(gw, session, _event) {
121
122
  const threadInfo = gw.sessionToThread.get(sessionId)
122
123
  if (!threadInfo) return
123
124
  if (gw.pending.has(sessionId)) return
125
+ // Muted chat: no forum mirroring either (#231).
126
+ if (gw.isMuted?.(threadInfo.chatId)) return
124
127
 
125
128
  const tgAdapter = gw.adapters.get('telegram')
126
129
  if (!tgAdapter) return
@@ -260,7 +260,7 @@ export async function runGatewayTurn(gw, chat, input, signal) {
260
260
  const tg = gw.tg()
261
261
  const streaming = tg.streaming === true && typeof startStream === 'function'
262
262
  const progressEnabled = tg.progressEnabled !== false
263
- const collector = { parts: [], lastText: '', streamText: '', reasoningText: '', toolName: '', images: [], reason: undefined, onStream: undefined }
263
+ const collector = { lastText: '', streamText: '', reasoningText: '', toolName: '', images: [], reason: undefined, onStream: undefined }
264
264
  gw.pending.set(sessionId, collector)
265
265
  let stopTyping = () => {}
266
266
  let stream = null
@@ -337,7 +337,7 @@ export async function runGatewayTurn(gw, chat, input, signal) {
337
337
  if (progress) try { await progress.remove() } catch (err) { gw.logger?.debug?.('progress.remove failed after turn:', err?.message || err) }
338
338
  progress = null
339
339
  if (typeof react === 'function') react('').catch?.((e) => { gw.logger?.debug?.('react clear error:', e?.message || e) })
340
- const rawText = stripImageUrls(collector.lastText || collector.streamText || collector.parts.join('\n\n'))
340
+ const rawText = stripImageUrls(collector.lastText || collector.streamText)
341
341
  const rawAnswer = formatReasoningFinal(rawText, collector.reasoningText, {
342
342
  showReasoning: tg.showReasoning !== false,
343
343
  thoughtCollapse: tg.thoughtCollapse !== false,
package/lib/gateway.js CHANGED
@@ -26,7 +26,7 @@ import { handleGatewayCommand } from './gateway-commands.js'
26
26
  import { handleGatewayCallback } from './gateway-callbacks.js'
27
27
  import { runGatewayTurn, buildUserContent, answerApproval } from './gateway-turn.js'
28
28
  import {
29
- collectDynamicSkills, syncTelegramCommands,
29
+ syncTelegramCommands,
30
30
  mirrorSessionToForumTopic, relayTurnToForumMirror,
31
31
  restoreSkillGesture,
32
32
  } from './forum-mirror.js'
@@ -435,6 +435,12 @@ export class Gateway {
435
435
  if (!home) throw new Error('target.chatId required (or set telegram home channel)')
436
436
  resolved = { ...home, ...resolved, chatId: home.chatId, threadId: resolved.threadId ?? home.threadId }
437
437
  }
438
+ // /mute stops ALL outbound delivery to the chat (#231): notify bridge,
439
+ // messenger tool, HTTP sends and cron prompts all funnel through here.
440
+ // The interactive turn conversation (chat.reply) is unaffected.
441
+ if (resolved.chatId !== undefined && this.isMuted?.(resolved.chatId)) {
442
+ return { ok: true, muted: true }
443
+ }
438
444
  const adapter = this.getAdapter(resolved.platform)
439
445
  if (!adapter?.sendTo) throw new Error(`adapter ${resolved.platform} unavailable`)
440
446
  try {
@@ -633,24 +639,6 @@ export class Gateway {
633
639
  return handleGatewayCommand(this, key, text, input)
634
640
  }
635
641
 
636
- async collectDynamicSkills() {
637
- const skills = await collectDynamicSkills(this.ctx)
638
- if (!this.skillNameMap) this.skillNameMap = new Map()
639
- if (!this.rawSkillNames) this.rawSkillNames = new Set()
640
- this.skillNameMap.clear()
641
- this.rawSkillNames.clear()
642
- for (const s of skills) {
643
- const rawName = String(s.name || '').trim()
644
- if (!rawName) continue
645
- this.rawSkillNames.add(rawName.toLowerCase())
646
- const sanitized = rawName.replace(/^\//, '').toLowerCase().replace(/[^a-z0-9_]/g, '_').slice(0, 32)
647
- if (sanitized && sanitized !== rawName) {
648
- this.skillNameMap.set(sanitized, rawName)
649
- }
650
- }
651
- return skills
652
- }
653
-
654
642
  async syncTelegramCommands() {
655
643
  return syncTelegramCommands(this)
656
644
  }
package/lib/index.js CHANGED
@@ -25,7 +25,7 @@ export const inject = ['agentDefaultModel', 'agents', 'sessions', 'loader', 'set
25
25
  export const SETTINGS_NAMESPACE = 'dsh-messenger-gateway'
26
26
  export { Config }
27
27
 
28
- function resolveConfig(raw) {
28
+ export function resolveConfig(raw) {
29
29
  // Unwrap once here: everything downstream reads plain values.
30
30
  const plain = plainConfig(raw)
31
31
  const cfg = plainConfig(Config(plain))
@@ -36,85 +36,73 @@ function resolveConfig(raw) {
36
36
  return cfg
37
37
  }
38
38
 
39
+ // Fields with role('secret') in the schema (#232): the projection never
40
+ // exposes the value — only a `<field>Configured` flag (plus proxyUrlMasked
41
+ // for the proxy). Keeping this list explicit makes the security surface
42
+ // reviewable.
43
+ const SECRET_FIELDS = new Set([
44
+ 'telegram.botToken',
45
+ 'telegram.webhookSecret',
46
+ 'telegram.proxyUrl',
47
+ 'discord.botToken',
48
+ 'slack.botToken',
49
+ 'webhooks.secret',
50
+ 'memory.token',
51
+ ])
52
+
53
+ // Fields never exposed to the client (server-internal values).
54
+ const HIDDEN_FIELDS = new Set([
55
+ 'media.cacheDir',
56
+ ])
57
+
39
58
  export function publicConfig(cfg, gw, ctx) {
40
- const internalBaseURL = gw?.baseUrl?.() || resolveInternalBaseUrl(cfg, ctx)
41
59
  const proxy = describeProxy(cfg.telegram?.proxyUrl)
42
- return {
43
- enabled: cfg.enabled,
44
- internalBaseURL,
45
- telegram: {
46
- enabled: cfg.telegram.enabled,
47
- allowedUserIds: cfg.telegram.allowedUserIds,
48
- pollTimeoutSeconds: cfg.telegram.pollTimeoutSeconds,
49
- pollIntervalMs: cfg.telegram.pollIntervalMs,
50
- commands: cfg.telegram.commands,
51
- textFormat: cfg.telegram.textFormat,
52
- homeChatId: cfg.telegram.homeChatId,
53
- homeThreadId: cfg.telegram.homeThreadId,
54
- homes: listHomes(cfg.telegram),
55
- pairingEnabled: cfg.telegram.pairingEnabled,
56
- streaming: cfg.telegram.streaming,
57
- streamEditIntervalMs: cfg.telegram.streamEditIntervalMs,
58
- progressEnabled: cfg.telegram.progressEnabled,
59
- showReasoning: cfg.telegram.showReasoning,
60
- thoughtCollapse: cfg.telegram.thoughtCollapse,
61
- approvalsEnabled: cfg.telegram.approvalsEnabled,
62
- approvalsSensitivity: cfg.telegram.approvalsSensitivity,
63
- approvalsTimeoutMs: cfg.telegram.approvalsTimeoutMs,
64
- groupsEnabled: cfg.telegram.groupsEnabled,
65
- groupRequireMention: cfg.telegram.groupRequireMention,
66
- reactionsEnabled: cfg.telegram.reactionsEnabled,
67
- transport: cfg.telegram.transport,
68
- webhookUrl: cfg.telegram.webhookUrl,
69
- webhookPath: cfg.telegram.webhookPath,
70
- webhookSecretConfigured: Boolean(String(cfg.telegram.webhookSecret || '').trim()),
71
- botTokenConfigured: Boolean(String(cfg.telegram.botToken || '').trim()),
72
- proxyUrlConfigured: Boolean(String(cfg.telegram.proxyUrl || '').trim()),
73
- proxyUrlMasked: maskProxyUrl(cfg.telegram.proxyUrl || ''),
74
- apiRoot: cfg.telegram.apiRoot || '',
75
- proxyActive: Boolean(proxy.active),
76
- proxyLabel: proxy.label || '',
77
- proxySource: proxy.source || '',
78
- proxyError: proxy.error || '',
79
- voiceMode: cfg.telegram.voiceMode,
80
- quickActions: cfg.telegram.quickActions !== false,
81
- artifactPreviews: cfg.telegram.artifactPreviews !== false,
82
- notifyBridge: {
83
- enabled: Boolean(cfg.telegram.notifyBridge?.enabled),
84
- events: cfg.telegram.notifyBridge?.events || ['task_done', 'error'],
85
- home: cfg.telegram.notifyBridge?.home || 'default',
86
- excludeSessionPrefixes: cfg.telegram.notifyBridge?.excludeSessionPrefixes || ['msgw-'],
87
- },
88
- forumMirrorEnabled: Boolean(cfg.telegram.forumMirrorEnabled),
89
- forumMirrorChatId: cfg.telegram.forumMirrorChatId || '',
90
- },
91
- discord: {
92
- enabled: Boolean(cfg.discord?.enabled),
93
- botTokenConfigured: Boolean(String(cfg.discord?.botToken || '').trim()),
94
- webhookConfigured: Boolean(String(cfg.discord?.webhookUrl || '').trim()),
95
- },
96
- slack: {
97
- enabled: Boolean(cfg.slack?.enabled),
98
- botTokenConfigured: Boolean(String(cfg.slack?.botToken || '').trim()),
99
- webhookConfigured: Boolean(String(cfg.slack?.webhookUrl || '').trim()),
100
- },
101
- media: { maxDocBytes: cfg.media.maxDocBytes, maxTextInjectBytes: cfg.media.maxTextInjectBytes, maxImageBytes: cfg.media.maxImageBytes },
102
- tts: cfg.tts,
103
- agent: {
104
- provider: cfg.agent.provider,
105
- model: cfg.agent.model,
106
- cwd: cfg.agent.cwd || '',
107
- effectiveCwd: resolveEffectiveCwd(cfg.agent.cwd, ctx?.logger),
108
- defaultCwd: process.cwd(),
109
- cwdWarning: getCwdWarning(cfg.agent.cwd),
110
- photoOnlyMode: cfg.agent.photoOnlyMode,
111
- maxMessageLength: cfg.agent.maxMessageLength,
112
- turnTimeoutMs: cfg.agent.turnTimeoutMs,
113
- idleTimeoutMs: cfg.agent.idleTimeoutMs,
114
- instructionPrefix: cfg.agent.instructionPrefix,
115
- sessionScope: cfg.agent.sessionScope,
116
- },
60
+ // Schema-driven projection (#232): start from the resolved config itself —
61
+ // every schema field is projected automatically — then replace secrets
62
+ // with configured-flags and append derived runtime values. The parity test
63
+ // asserts every resolved schema leaf is covered.
64
+ const projected = {}
65
+ for (const [section, value] of Object.entries(cfg)) {
66
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
67
+ const out = {}
68
+ for (const [key, v] of Object.entries(value)) {
69
+ const path = `${section}.${key}`
70
+ if (HIDDEN_FIELDS.has(path)) continue
71
+ if (SECRET_FIELDS.has(path)) {
72
+ out[`${key}Configured`] = Boolean(String(v ?? '').trim())
73
+ if (path === 'telegram.proxyUrl') out.proxyUrlMasked = maskProxyUrl(v || '')
74
+ continue
75
+ }
76
+ out[key] = v
77
+ }
78
+ projected[section] = out
79
+ } else {
80
+ projected[section] = value
81
+ }
82
+ }
83
+ const tg = projected.telegram || {}
84
+ // Derived runtime values (not stored config) appended on top of the walk.
85
+ tg.homes = listHomes(cfg.telegram)
86
+ tg.proxyActive = Boolean(proxy.active)
87
+ tg.proxyLabel = proxy.label || ''
88
+ tg.proxySource = proxy.source || ''
89
+ tg.proxyError = proxy.error || ''
90
+ projected.internalBaseURL = gw?.baseUrl?.() || resolveInternalBaseUrl(cfg, ctx)
91
+ projected.discord = {
92
+ ...projected.discord,
93
+ webhookConfigured: Boolean(String(cfg.discord?.webhookUrl || '').trim()),
117
94
  }
95
+ projected.slack = {
96
+ ...projected.slack,
97
+ webhookConfigured: Boolean(String(cfg.slack?.webhookUrl || '').trim()),
98
+ }
99
+ projected.agent = {
100
+ ...projected.agent,
101
+ effectiveCwd: resolveEffectiveCwd(cfg.agent?.cwd, ctx?.logger),
102
+ defaultCwd: process.cwd(),
103
+ cwdWarning: getCwdWarning(cfg.agent?.cwd),
104
+ }
105
+ return projected
118
106
  }
119
107
 
120
108
  async function readJsonSafe(req, res, maxBytes = 1_048_576) {
@@ -133,7 +121,14 @@ async function readJsonSafe(req, res, maxBytes = 1_048_576) {
133
121
  }
134
122
 
135
123
  export function registerMessengerRoute(ctx, getGw, path, action, source) {
136
- ctx.effect(() => (ctx.get?.('webServer') || ctx.webServer).register({
124
+ ctx.effect(() => {
125
+ // Guarded registration (#230): no webServer in the profile — skip loudly.
126
+ const ws = ctx.get?.('webServer') || ctx.webServer
127
+ if (!ws?.register) {
128
+ ctx.logger?.warn?.('dsh-messenger-gateway: webServer service unavailable — HTTP routes are skipped')
129
+ return () => {}
130
+ }
131
+ return ws.register({
137
132
  kind: 'exact', path,
138
133
  handler: async (req, res) => {
139
134
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
@@ -158,7 +153,8 @@ export function registerMessengerRoute(ctx, getGw, path, action, source) {
158
153
  writeJson(res, httpStatusForError(err), { ok: false, error: err.message })
159
154
  }
160
155
  },
161
- }), `dsh-messenger-gateway: ${action}`)
156
+ })
157
+ }, `dsh-messenger-gateway: ${action}`)
162
158
  }
163
159
 
164
160
  function isExcludedSession(sessionId, prefixes) {
@@ -176,6 +172,17 @@ export function apply(ctx, config) {
176
172
  let settingsApi
177
173
  const getWebServer = () => ctx.get?.('webServer') || ctx.webServer
178
174
 
175
+ // Single guarded route registration (#230): a profile without a webServer
176
+ // must not crash plugin load — routes are skipped with a warning instead.
177
+ const registerRoute = (registration) => {
178
+ const ws = getWebServer()
179
+ if (!ws?.register) {
180
+ ctx.logger?.warn?.('dsh-messenger-gateway: webServer service unavailable — HTTP routes are skipped')
181
+ return () => {}
182
+ }
183
+ return ws.register(registration)
184
+ }
185
+
179
186
  // Секреты (botToken и т. п.) не отдаются браузеру, а карточка сохраняет секции
180
187
  // целиком — без этой защиты каждое сохранение (например, смена прокси) затирало
181
188
  // бы токен пустым значением. См. lib/secret-guard.js.
@@ -390,6 +397,12 @@ export function apply(ctx, config) {
390
397
  isReady: () => Boolean(settingsBridge.getSettingsApi()),
391
398
  }
392
399
 
400
+ // getGw resolves the LIVE gateway for route handlers and the notify bridge.
401
+ // The ctx.get fallback never fires in production (no service registers that
402
+ // name — the plugin provides `messenger`); it exists as an explicit
403
+ // integration seam for embedding hosts and tests. After dispose the closure
404
+ // variable is cleared (#230), and the fallback returns nothing in a real
405
+ // host, so a stopped gateway is never handed out.
393
406
  const getGw = () => gateway || ctx.get?.('messenger-gateway')
394
407
 
395
408
  ctx.effect(() => ctx.provide('messenger', createMessengerService(getGw)), 'dsh-messenger-gateway: messenger service')
@@ -626,7 +639,7 @@ export function apply(ctx, config) {
626
639
  }
627
640
  }, 'dsh-messenger-gateway: notify bridge')
628
641
 
629
- ctx.effect(() => getWebServer().register({
642
+ ctx.effect(() => registerRoute({
630
643
  kind: 'exact', path: '/dsh-messenger-gateway/status',
631
644
  handler: async (req, res) => {
632
645
  if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
@@ -667,7 +680,7 @@ export function apply(ctx, config) {
667
680
  },
668
681
  }), 'dsh-messenger-gateway: status')
669
682
 
670
- ctx.effect(() => getWebServer().register({
683
+ ctx.effect(() => registerRoute({
671
684
  kind: 'exact', path: '/dsh-messenger-gateway/smoke',
672
685
  handler: async (req, res) => {
673
686
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
@@ -682,7 +695,7 @@ export function apply(ctx, config) {
682
695
  },
683
696
  }), 'dsh-messenger-gateway: smoke test')
684
697
 
685
- ctx.effect(() => getWebServer().register({
698
+ ctx.effect(() => registerRoute({
686
699
  kind: 'exact', path: '/dsh-messenger-gateway/messenger',
687
700
  handler: async (req, res) => {
688
701
  if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
@@ -691,7 +704,7 @@ export function apply(ctx, config) {
691
704
  },
692
705
  }), 'dsh-messenger-gateway: messenger schema')
693
706
 
694
- ctx.effect(() => getWebServer().register({
707
+ ctx.effect(() => registerRoute({
695
708
  kind: 'exact', path: '/dsh-messenger-gateway/events',
696
709
  handler: async (req, res) => {
697
710
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
@@ -744,7 +757,7 @@ export function apply(ctx, config) {
744
757
  },
745
758
  }), 'dsh-messenger-gateway: webhook events')
746
759
 
747
- ctx.effect(() => getWebServer().register({
760
+ ctx.effect(() => registerRoute({
748
761
  kind: 'exact', path: '/dsh-messenger-gateway/config',
749
762
  handler: async (req, res) => {
750
763
  if (req.method !== 'GET' && req.method !== 'PUT') return writeJson(res, 405, { ok: false, error: 'GET or PUT' })
@@ -780,6 +793,10 @@ export function apply(ctx, config) {
780
793
  if (payload.discord && !String(payload.discord.botToken || '').trim()) nextDiscord.botToken = cur.discord?.botToken
781
794
  const nextSlack = { ...(cur.slack || {}), ...(payload.slack || {}) }
782
795
  if (payload.slack && !String(payload.slack.botToken || '').trim()) nextSlack.botToken = cur.slack?.botToken
796
+ // memory.token is a secret: a payload without it must keep the
797
+ // stored value, so the section merges like every other (#237).
798
+ const nextMemory = { ...(cur.memory || {}), ...(payload.memory || {}) }
799
+ if (payload.memory && !String(payload.memory.token || '').trim()) nextMemory.token = cur.memory?.token
783
800
  await api.replace(Config({
784
801
  ...cur,
785
802
  ...payload,
@@ -789,6 +806,7 @@ export function apply(ctx, config) {
789
806
  tts: { ...cur.tts, ...(payload.tts || {}) },
790
807
  agent: { ...cur.agent, ...(payload.agent || {}) },
791
808
  media: { ...cur.media, ...(payload.media || {}) },
809
+ memory: nextMemory,
792
810
  }))
793
811
  })
794
812
  sync()
@@ -799,7 +817,7 @@ export function apply(ctx, config) {
799
817
  },
800
818
  }), 'dsh-messenger-gateway: config')
801
819
 
802
- ctx.effect(() => getWebServer().register({
820
+ ctx.effect(() => registerRoute({
803
821
  kind: 'exact', path: '/dsh-messenger-gateway/pairing',
804
822
  handler: async (req, res) => {
805
823
  if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
@@ -814,7 +832,7 @@ export function apply(ctx, config) {
814
832
  },
815
833
  }), 'dsh-messenger-gateway: pairing list')
816
834
 
817
- ctx.effect(() => getWebServer().register({
835
+ ctx.effect(() => registerRoute({
818
836
  kind: 'exact', path: '/dsh-messenger-gateway/pairing/approve',
819
837
  handler: async (req, res) => {
820
838
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
@@ -828,7 +846,7 @@ export function apply(ctx, config) {
828
846
  },
829
847
  }), 'dsh-messenger-gateway: pairing approve')
830
848
 
831
- ctx.effect(() => getWebServer().register({
849
+ ctx.effect(() => registerRoute({
832
850
  kind: 'exact', path: '/dsh-messenger-gateway/pairing/reject',
833
851
  handler: async (req, res) => {
834
852
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
@@ -900,6 +918,9 @@ export function apply(ctx, config) {
900
918
  if (gateway) gateway.stop()
901
919
  } catch (err) {
902
920
  ctx.logger?.warn?.(`[dsh-messenger-gateway] gateway stop on dispose failed: ${err?.message || err}`)
921
+ } finally {
922
+ // getGw() must not hand out a stopped gateway after dispose (#230).
923
+ gateway = undefined
903
924
  }
904
925
  if (typeof webhookRouteDispose === 'function') webhookRouteDispose()
905
926
  }, 'dsh-messenger-gateway: stop gateway')
package/lib/outbound.js CHANGED
@@ -141,7 +141,9 @@ export async function buildOutboundFiles(ctx, baseUrl, collector, opts = {}) {
141
141
  logger?.warn?.(`outbound image: ${e.message}`)
142
142
  }
143
143
  }
144
- const urls = [...new Set(extractImageUrls(collector.parts.join('\n')))]
144
+ // Inline plugin image URLs are extracted from the actual assistant text
145
+ // (the old collector.parts was declared but never filled — #234).
146
+ const urls = [...new Set(extractImageUrls(collector.lastText || collector.streamText || ''))]
145
147
  for (const path of urls) {
146
148
  if (files.length >= maxFiles) break
147
149
  if (signal?.aborted) break
package/lib/outbox.js CHANGED
@@ -125,6 +125,10 @@ export function createOutboxQueue(options = {}) {
125
125
 
126
126
  let pending = []
127
127
  let dlq = []
128
+ // Jobs added locally since the last successful persist (#225): batched
129
+ // persistence means the disk can lag behind memory, and the merge filter
130
+ // must never drop such jobs as "removed by another writer".
131
+ const unsavedIds = new Set()
128
132
  let timer = null
129
133
  let isStopped = false
130
134
  const lockPath = `${storagePath}.lock`
@@ -136,7 +140,9 @@ export function createOutboxQueue(options = {}) {
136
140
  const data = JSON.parse(raw)
137
141
  // Merge (#218): adopt jobs added to disk by another writer; drop our
138
142
  // in-memory copies that another writer has already removed (it sent
139
- // or DLQ'd them under the lock). In-memory runtime state (backoff
143
+ // or DLQ'd them under the lock). Jobs enqueued LOCALLY but not yet
144
+ // persisted (#225 batching) are exempt — the disk lagging behind
145
+ // memory must not delete them. In-memory runtime state (backoff
140
146
  // nextRetryAt) for jobs still on disk is preserved.
141
147
  const diskPending = Array.isArray(data.pending) ? data.pending : []
142
148
  const diskDlq = Array.isArray(data.dlq) ? data.dlq : []
@@ -144,7 +150,7 @@ export function createOutboxQueue(options = {}) {
144
150
  for (const j of diskPending) {
145
151
  if (!pending.some((m) => m.id === j.id)) pending.push(j)
146
152
  }
147
- pending = pending.filter((m) => diskPendingIds.has(m.id))
153
+ pending = pending.filter((m) => diskPendingIds.has(m.id) || unsavedIds.has(m.id))
148
154
  const diskDlqIds = new Set(diskDlq.map((j) => j.id))
149
155
  for (const j of diskDlq) {
150
156
  if (!dlq.some((m) => m.id === j.id)) dlq.push(j)
@@ -168,6 +174,9 @@ export function createOutboxQueue(options = {}) {
168
174
  // schemaVersion envelope (#227): future format changes migrate instead
169
175
  // of misreading; readers stay tolerant of legacy files without it.
170
176
  await writeJsonAtomic(storagePath, { schemaVersion: OUTBOX_SCHEMA_VERSION, pending, dlq })
177
+ // Disk now covers every in-memory job (#225): the merge filter may
178
+ // treat them as persisted again.
179
+ unsavedIds.clear()
171
180
  } catch (err) {
172
181
  if (logger) {
173
182
  logger.warn?.(`[outbox] failed to persist queue to disk: ${err.message}`)
@@ -175,6 +184,41 @@ export function createOutboxQueue(options = {}) {
175
184
  }
176
185
  }
177
186
 
187
+ // Batched persistence (#225): bursts of enqueues coalesce into a single
188
+ // disk write. flush() still persists on every dirty pass under its own
189
+ // lock, so the debounce only covers the enqueue window; stop() forces the
190
+ // deferred write out before the process can exit.
191
+ const PERSIST_DEBOUNCE_MS = 250
192
+ let persistTimer = null
193
+
194
+ function writeUnderLock() {
195
+ return (async () => {
196
+ while (!acquireLock(lockPath)) {
197
+ await new Promise((r) => setTimeout(r, 50))
198
+ }
199
+ try {
200
+ // Merge other writers' jobs BEFORE writing (#218): a deferred batched
201
+ // persist must never overwrite a newer on-disk state with stale
202
+ // in-memory content.
203
+ loadDiskIntoMemory()
204
+ await persist()
205
+ } finally {
206
+ releaseLock(lockPath)
207
+ }
208
+ })()
209
+ }
210
+
211
+ function schedulePersist() {
212
+ if (persistTimer) return
213
+ persistTimer = setTimeout(() => {
214
+ persistTimer = null
215
+ writeUnderLock().catch((err) => {
216
+ logger?.warn?.(`[outbox] deferred persist failed: ${err?.message || err}`)
217
+ })
218
+ }, PERSIST_DEBOUNCE_MS)
219
+ persistTimer.unref?.()
220
+ }
221
+
178
222
  const PID = process.pid
179
223
  const CLAIM_MS = 60_000
180
224
 
@@ -277,7 +321,10 @@ export function createOutboxQueue(options = {}) {
277
321
  // Merge under the lock (#218): adopt jobs another instance enqueued.
278
322
  loadDiskIntoMemory()
279
323
  pending.push(item)
280
- await persist()
324
+ unsavedIds.add(item.id)
325
+ // Persist batched (#225): the trailing flush() persists the queue on its
326
+ // dirty pass; schedulePersist is the fallback when flush is lock-starved.
327
+ schedulePersist()
281
328
  } finally {
282
329
  releaseLock(lockPath)
283
330
  }
@@ -295,6 +342,14 @@ export function createOutboxQueue(options = {}) {
295
342
  }
296
343
 
297
344
  function stop() {
345
+ if (persistTimer) {
346
+ clearTimeout(persistTimer)
347
+ persistTimer = null
348
+ // Force the last enqueue window out before the process can exit (#225).
349
+ writeUnderLock().catch((err) => {
350
+ logger?.warn?.(`[outbox] final persist on stop failed: ${err?.message || err}`)
351
+ })
352
+ }
298
353
  isStopped = true
299
354
  if (timer) {
300
355
  clearInterval(timer)
@@ -11,9 +11,11 @@
11
11
  export const SECRET_FIELDS = [
12
12
  ['telegram', 'botToken'],
13
13
  ['telegram', 'webhookSecret'],
14
+ ['telegram', 'proxyUrl'],
14
15
  ['discord', 'botToken'],
15
16
  ['slack', 'botToken'],
16
17
  ['webhooks', 'secret'],
18
+ ['memory', 'token'],
17
19
  ]
18
20
 
19
21
  function keyOf(section, field) {
package/lib/updater.js CHANGED
@@ -244,7 +244,14 @@ export async function runDirectUpdate(options, target = runtime()) {
244
244
 
245
245
  export function registerPluginUpdater(ctx, options) {
246
246
  const getWebServer = () => ctx.get?.('webServer') || ctx.webServer
247
- return getWebServer().register({
247
+ // Guarded registration (#230): a profile without a webServer skips the
248
+ // updater route instead of crashing plugin load.
249
+ const ws = getWebServer()
250
+ if (!ws?.register) {
251
+ ctx.logger?.warn?.('dsh-messenger-gateway: webServer service unavailable — updater route is skipped')
252
+ return () => {}
253
+ }
254
+ return ws.register({
248
255
  kind: 'exact',
249
256
  path: options.endpoint || '/dsh-messenger-gateway/update',
250
257
  handler: async (request, response) => {
package/lib/webapp.js CHANGED
@@ -585,7 +585,8 @@ export function createWebAppHtml(options = {}) {
585
585
  document.getElementById('stat-uptime').textContent = hrs + 'h ' + mins + 'm'
586
586
  document.getElementById('stat-sent').textContent = s.stats && s.stats.sent || 0
587
587
  document.getElementById('stat-chats').textContent = s.activeChats || 0
588
- document.getElementById('stat-outbox').textContent = s.outbox && s.outbox.pending || 0
588
+ document.getElementById('stat-outbox').textContent = (s.outbox && s.outbox.pending || 0)
589
+ + ((s.outbox && s.outbox.dlq) ? ' (+' + s.outbox.dlq + ' DLQ)' : '')
589
590
  document.getElementById('tg-details').textContent = 'Bot: @' + (s.botUsername || 'none') + ' | Transport: ' + (s.config && s.config.telegram && s.config.telegram.transport || 'poll')
590
591
  document.getElementById('adapters-list').textContent = (s.adapters || []).map(a => '• ' + a + ': active').join('\n') || 'None'
591
592
  document.getElementById('model-details').textContent = 'Model: ' + (s.config && s.config.agent && s.config.agent.model || 'default') + ' | CWD: ' + (s.config && s.config.agent && s.config.agent.effectiveCwd || 'standard')
@@ -703,10 +704,12 @@ export function createWebAppHandler(options = {}) {
703
704
  activeChats: gw?.messenger?.activeChats?.() || 0,
704
705
  adapters: gw?.messenger?.adapters?.() || [],
705
706
  stats: gw?.stats || {},
706
- outbox: {
707
- pending: gw?.outbox?.pendingCount || 0,
708
- dlq: gw?.outbox?.dlqCount || 0,
709
- },
707
+ outbox: (() => {
708
+ // Real queue counters (#231): the outbox exposes status(), not
709
+ // pendingCount/dlqCount properties — the old reads were always 0.
710
+ const ob = gw?.outbox?.status?.()
711
+ return { pending: ob?.pendingCount || 0, dlq: ob?.dlqCount || 0 }
712
+ })(),
710
713
  config: {
711
714
  telegram: {
712
715
  transport: tgCfg.transport || 'poll',
package/lib/workspace.js CHANGED
@@ -7,43 +7,87 @@ import os from 'node:os'
7
7
  import path from 'node:path'
8
8
  import { writeJsonAtomic, writeJsonAtomicSync, readJsonStateSync, StateCorruptError } from './storage-atomic.js'
9
9
 
10
+ // Resolved-path cache (#225): getCwdWarning + resolveEffectiveCwd run on every
11
+ // inbound message; statSync/realpathSync block the event loop — painfully so
12
+ // on a network filesystem. Results are memoized for a short TTL: long enough
13
+ // to de-hot the path, short enough to notice a directory created moments ago.
14
+ const CWD_CACHE_TTL_MS = 10_000
15
+ const CWD_CACHE_MAX = 64
16
+ const cwdCache = new Map()
17
+
18
+ function cachedCwdEntry(trimmed) {
19
+ const hit = cwdCache.get(trimmed)
20
+ if (hit && hit.expires > Date.now()) return hit
21
+ return null
22
+ }
23
+
24
+ function storeCwdEntry(trimmed, entry) {
25
+ entry.expires = Date.now() + CWD_CACHE_TTL_MS
26
+ cwdCache.set(trimmed, entry)
27
+ if (cwdCache.size > CWD_CACHE_MAX) {
28
+ const oldest = cwdCache.keys().next().value
29
+ cwdCache.delete(oldest)
30
+ }
31
+ }
32
+
10
33
  /**
11
34
  * Validates configured cwd path and returns an error description if invalid.
12
35
  * Empty or unconfigured cwd returns null (defaults to host launch dir).
36
+ * Results are cached for CWD_CACHE_TTL_MS (#225).
13
37
  */
14
38
  export function getCwdWarning(configuredCwd) {
15
39
  const trimmed = typeof configuredCwd === 'string' ? configuredCwd.trim() : ''
16
40
  if (!trimmed) return null
41
+ const hit = cachedCwdEntry(trimmed)
42
+ if (hit) return hit.warning
43
+ let warning = null
17
44
  try {
18
45
  const resolved = resolve(trimmed)
19
46
  const st = statSync(resolved)
20
47
  if (!st.isDirectory()) {
21
- return `Path "${trimmed}" is not a directory`
48
+ warning = `Path "${trimmed}" is not a directory`
22
49
  }
23
- return null
24
50
  } catch (err) {
25
51
  const code = err?.code || err?.message || String(err)
26
- return `Directory "${trimmed}" does not exist or is not accessible (${code})`
52
+ warning = `Directory "${trimmed}" does not exist or is not accessible (${code})`
27
53
  }
54
+ storeCwdEntry(trimmed, { warning })
55
+ return warning
28
56
  }
29
57
 
30
58
  /**
31
59
  * Resolves effective working directory for agent sessions and file operations.
32
60
  * Falls back to process.cwd() if configured cwd is empty or invalid.
61
+ * stat/realpath results are cached for CWD_CACHE_TTL_MS (#225); the fallback
62
+ * warning is logged once per cache lifetime instead of on every message.
33
63
  */
34
64
  export function resolveEffectiveCwd(configuredCwd, logger) {
35
65
  const trimmed = typeof configuredCwd === 'string' ? configuredCwd.trim() : ''
36
66
  if (!trimmed) return process.cwd()
37
- const warning = getCwdWarning(trimmed)
38
- if (warning) {
39
- logger?.warn?.(`[dsh-messenger-gateway] ${warning}, falling back to process.cwd()`)
40
- return process.cwd()
67
+ let entry = cachedCwdEntry(trimmed)
68
+ if (!entry) {
69
+ const warning = getCwdWarning(trimmed)
70
+ let resolved
71
+ if (warning) {
72
+ resolved = process.cwd()
73
+ } else {
74
+ try {
75
+ resolved = realpathSync(resolve(trimmed))
76
+ } catch {
77
+ resolved = resolve(trimmed)
78
+ }
79
+ }
80
+ entry = { warning, resolved }
81
+ storeCwdEntry(trimmed, entry)
41
82
  }
42
- try {
43
- return realpathSync(resolve(trimmed))
44
- } catch {
45
- return resolve(trimmed)
83
+ if (entry.warning) {
84
+ if (!entry.warned) {
85
+ entry.warned = true
86
+ logger?.warn?.(`[dsh-messenger-gateway] ${entry.warning}, falling back to process.cwd()`)
87
+ }
88
+ return process.cwd()
46
89
  }
90
+ return entry.resolved
47
91
  }
48
92
 
49
93
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-messenger-gateway",
3
- "version": "0.4.45",
3
+ "version": "0.4.47",
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",