@goodandready/dsh-messenger-gateway 0.4.46 → 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,7 @@ 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
167
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
168
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
169
170
  - `sessionList`: `true` (default) — enables `/sessions` and `/resume` commands in chat
package/README.ru.md CHANGED
@@ -102,6 +102,7 @@ graph LR
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
104
  * Карточка настроек строится из схемы конфигурации: все настройки видимы и редактируемы (в расширенной секции — режим белого списка, язык бота, чувствительность подтверждений, стриминг, Mini App, футер стоимости, бюджетные алерты, зеркалирование в форумы и инъекция памяти), секреты отдаются только флагом «настроен» и никогда не возвращаются в браузер; `/mute` останавливает ВСЮ исходящую доставку в чат (notify bridge, messenger.send, HTTP, cron, зеркалирование), не затрагивая живой диалог;
105
+ * Горячий путь асинхронный: резолв cwd кэшируется (TTL 10 с) — входящие сообщения не выполняют синхронных stat/realpath (важно для сетевых ФС); запись outbox батчится (одно отложенное сохранение на всплеск enqueue) и принудительно сбрасывается при остановке; плагин загружается и без сервиса webServer (маршруты пропускаются с предупреждением), а после reload/dispose остановленный gateway недостижим;
105
106
 
106
107
  ### 6. 🤖 Команды бота (`commands.js`)
107
108
  * `/start` — приветствие и запуск сопряжения;
package/README.zh.md CHANGED
@@ -88,6 +88,7 @@ dsh plugin --profile web add @goodandready/dsh-messenger-gateway
88
88
  - 本地回环请求只接受固定的 Host(`localhost` / `127.0.0.1` / `[::1]`)— 防 DNS Rebinding;如需在受信任的本地反向代理后使用,可显式开启 `security.trustProxy`。
89
89
  - 持久化状态:写入先 fsync 再原子重命名,文件带 `schemaVersion`(旧格式自动迁移),每次保存保留 `.bak`,损坏文件以 `.corrupt-*` 保留并可从 `.bak` 恢复——绝不静默清空访问(fail-closed + 显式错误);
90
90
  - 设置卡片由配置 schema 生成:所有设置均可见可编辑(高级区含白名单模式、机器人语言、审批灵敏度、流式回复、Mini App、成本页脚、预算告警、论坛镜像与记忆注入);机密只以「已配置」标志形式报告,绝不返回浏览器;`/mute` 停止向该聊天的所有出站投递(notify bridge、messenger.send、HTTP、cron、论坛镜像),不影响实时对话;
91
+ - 热路径全异步:cwd 解析带 10 秒缓存,入站消息不再执行同步 stat/realpath(网络文件系统尤其重要);outbox 持久化按突发批量合并写入,stop() 时强制落盘;无 webServer 服务的环境也能加载插件(路由跳过并告警),reload/dispose 后不会残留已停止的 gateway;
91
92
 
92
93
  ---
93
94
 
@@ -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'
@@ -639,24 +639,6 @@ export class Gateway {
639
639
  return handleGatewayCommand(this, key, text, input)
640
640
  }
641
641
 
642
- async collectDynamicSkills() {
643
- const skills = await collectDynamicSkills(this.ctx)
644
- if (!this.skillNameMap) this.skillNameMap = new Map()
645
- if (!this.rawSkillNames) this.rawSkillNames = new Set()
646
- this.skillNameMap.clear()
647
- this.rawSkillNames.clear()
648
- for (const s of skills) {
649
- const rawName = String(s.name || '').trim()
650
- if (!rawName) continue
651
- this.rawSkillNames.add(rawName.toLowerCase())
652
- const sanitized = rawName.replace(/^\//, '').toLowerCase().replace(/[^a-z0-9_]/g, '_').slice(0, 32)
653
- if (sanitized && sanitized !== rawName) {
654
- this.skillNameMap.set(sanitized, rawName)
655
- }
656
- }
657
- return skills
658
- }
659
-
660
642
  async syncTelegramCommands() {
661
643
  return syncTelegramCommands(this)
662
644
  }
package/lib/index.js CHANGED
@@ -121,7 +121,14 @@ async function readJsonSafe(req, res, maxBytes = 1_048_576) {
121
121
  }
122
122
 
123
123
  export function registerMessengerRoute(ctx, getGw, path, action, source) {
124
- 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({
125
132
  kind: 'exact', path,
126
133
  handler: async (req, res) => {
127
134
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
@@ -146,7 +153,8 @@ export function registerMessengerRoute(ctx, getGw, path, action, source) {
146
153
  writeJson(res, httpStatusForError(err), { ok: false, error: err.message })
147
154
  }
148
155
  },
149
- }), `dsh-messenger-gateway: ${action}`)
156
+ })
157
+ }, `dsh-messenger-gateway: ${action}`)
150
158
  }
151
159
 
152
160
  function isExcludedSession(sessionId, prefixes) {
@@ -164,6 +172,17 @@ export function apply(ctx, config) {
164
172
  let settingsApi
165
173
  const getWebServer = () => ctx.get?.('webServer') || ctx.webServer
166
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
+
167
186
  // Секреты (botToken и т. п.) не отдаются браузеру, а карточка сохраняет секции
168
187
  // целиком — без этой защиты каждое сохранение (например, смена прокси) затирало
169
188
  // бы токен пустым значением. См. lib/secret-guard.js.
@@ -378,6 +397,12 @@ export function apply(ctx, config) {
378
397
  isReady: () => Boolean(settingsBridge.getSettingsApi()),
379
398
  }
380
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.
381
406
  const getGw = () => gateway || ctx.get?.('messenger-gateway')
382
407
 
383
408
  ctx.effect(() => ctx.provide('messenger', createMessengerService(getGw)), 'dsh-messenger-gateway: messenger service')
@@ -614,7 +639,7 @@ export function apply(ctx, config) {
614
639
  }
615
640
  }, 'dsh-messenger-gateway: notify bridge')
616
641
 
617
- ctx.effect(() => getWebServer().register({
642
+ ctx.effect(() => registerRoute({
618
643
  kind: 'exact', path: '/dsh-messenger-gateway/status',
619
644
  handler: async (req, res) => {
620
645
  if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
@@ -655,7 +680,7 @@ export function apply(ctx, config) {
655
680
  },
656
681
  }), 'dsh-messenger-gateway: status')
657
682
 
658
- ctx.effect(() => getWebServer().register({
683
+ ctx.effect(() => registerRoute({
659
684
  kind: 'exact', path: '/dsh-messenger-gateway/smoke',
660
685
  handler: async (req, res) => {
661
686
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
@@ -670,7 +695,7 @@ export function apply(ctx, config) {
670
695
  },
671
696
  }), 'dsh-messenger-gateway: smoke test')
672
697
 
673
- ctx.effect(() => getWebServer().register({
698
+ ctx.effect(() => registerRoute({
674
699
  kind: 'exact', path: '/dsh-messenger-gateway/messenger',
675
700
  handler: async (req, res) => {
676
701
  if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
@@ -679,7 +704,7 @@ export function apply(ctx, config) {
679
704
  },
680
705
  }), 'dsh-messenger-gateway: messenger schema')
681
706
 
682
- ctx.effect(() => getWebServer().register({
707
+ ctx.effect(() => registerRoute({
683
708
  kind: 'exact', path: '/dsh-messenger-gateway/events',
684
709
  handler: async (req, res) => {
685
710
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
@@ -732,7 +757,7 @@ export function apply(ctx, config) {
732
757
  },
733
758
  }), 'dsh-messenger-gateway: webhook events')
734
759
 
735
- ctx.effect(() => getWebServer().register({
760
+ ctx.effect(() => registerRoute({
736
761
  kind: 'exact', path: '/dsh-messenger-gateway/config',
737
762
  handler: async (req, res) => {
738
763
  if (req.method !== 'GET' && req.method !== 'PUT') return writeJson(res, 405, { ok: false, error: 'GET or PUT' })
@@ -792,7 +817,7 @@ export function apply(ctx, config) {
792
817
  },
793
818
  }), 'dsh-messenger-gateway: config')
794
819
 
795
- ctx.effect(() => getWebServer().register({
820
+ ctx.effect(() => registerRoute({
796
821
  kind: 'exact', path: '/dsh-messenger-gateway/pairing',
797
822
  handler: async (req, res) => {
798
823
  if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
@@ -807,7 +832,7 @@ export function apply(ctx, config) {
807
832
  },
808
833
  }), 'dsh-messenger-gateway: pairing list')
809
834
 
810
- ctx.effect(() => getWebServer().register({
835
+ ctx.effect(() => registerRoute({
811
836
  kind: 'exact', path: '/dsh-messenger-gateway/pairing/approve',
812
837
  handler: async (req, res) => {
813
838
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
@@ -821,7 +846,7 @@ export function apply(ctx, config) {
821
846
  },
822
847
  }), 'dsh-messenger-gateway: pairing approve')
823
848
 
824
- ctx.effect(() => getWebServer().register({
849
+ ctx.effect(() => registerRoute({
825
850
  kind: 'exact', path: '/dsh-messenger-gateway/pairing/reject',
826
851
  handler: async (req, res) => {
827
852
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
@@ -893,6 +918,9 @@ export function apply(ctx, config) {
893
918
  if (gateway) gateway.stop()
894
919
  } catch (err) {
895
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
896
924
  }
897
925
  if (typeof webhookRouteDispose === 'function') webhookRouteDispose()
898
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)
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/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.46",
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",