@goodandready/dsh-messenger-gateway 0.4.40 → 0.4.42

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
File without changes
File without changes
package/lib/ask.js CHANGED
File without changes
package/lib/documents.js CHANGED
File without changes
File without changes
@@ -19,10 +19,6 @@ import { rememberUserFact, listUserMemories, forgetUserMemory } from './memory-b
19
19
  import { formatSessionCostReport } from './cost-tracker.js'
20
20
 
21
21
 
22
- export function releaseChatTurn(chat) {
23
- chat.busy = Promise.resolve()
24
- }
25
-
26
22
  export async function handleGatewayCommand(gw, key, text, input) {
27
23
  const parts = text.split(/\s+/)
28
24
  const cmd = parts[0].toLowerCase().split('@')[0]
@@ -248,6 +244,20 @@ export async function handleGatewayCommand(gw, key, text, input) {
248
244
  const sessions = gw.ctx.get?.('sessions') || gw.ctx.sessions
249
245
  try { await sessions?.flush(newChat.agent.session) } catch (err) { gw.logger?.debug?.('fork session flush error:', err?.message || err) }
250
246
  }
247
+ // Full teardown of the old chat before replacement (#214): the old
248
+ // agent must stop receiving events and the id mappings must not route
249
+ // ask/approvals from the old session into the new chat.
250
+ try {
251
+ await chat.dispose()
252
+ } catch (err) { gw.logger?.debug?.('fork: old chat dispose error:', err?.message || err) }
253
+ const oldId = String(oldSession.id)
254
+ gw.sessionToChat.delete(oldId)
255
+ const threadInfo = gw.sessionToThread.get(oldId)
256
+ if (threadInfo) {
257
+ gw.threadToSession.delete(`${threadInfo.chatId}:${threadInfo.threadId}`)
258
+ gw.sessionToThread.delete(oldId)
259
+ }
260
+ gw.pending.delete(oldId)
251
261
  gw.chats.set(key, newChat)
252
262
  return reply(`🔀 Forked session!\nOld session: ${oldSession.id}\nNew session: ${newChat.agent.session.id}\nContext preserved (${oldMessages.length} messages).`)
253
263
  } catch (err) {
@@ -655,8 +665,10 @@ export async function handleGatewayCommand(gw, key, text, input) {
655
665
  const chat = gw.chats.get(key)
656
666
  if (chat?.turnActive || chat?.abort) {
657
667
  try { chat.abort?.abort() } catch { /* safe best-effort stop abort */ }
658
- releaseChatTurn(chat)
659
668
  chat.turnActive = false
669
+ // busy deliberately KEEPS the interrupted run's chain (#213): the next
670
+ // turn dispatches as chat.busy.then(...) and therefore starts only
671
+ // after the aborted run has fully drained — no parallel runTurn.
660
672
  return reply(t('msg.turn_stopped', {}, locale))
661
673
  }
662
674
  return reply('Nothing to stop.')
@@ -23,12 +23,24 @@ const PLUGIN = 'dsh-messenger-gateway'
23
23
  export function whenIdleWithTimeout(agent, timeoutMs, signal) {
24
24
  const idle = agent.whenIdle()
25
25
  if (!timeoutMs || timeoutMs <= 0) return idle
26
+ // Full cleanup (#220): on ANY resolution path (idle win, timeout, abort) the
27
+ // timer is cleared and the abort listener removed — no leaks accumulate
28
+ // across long-lived chats.
29
+ let timer = null
30
+ let onAbort = null
31
+ const cleanup = () => {
32
+ if (timer) { clearTimeout(timer); timer = null }
33
+ if (signal && onAbort) { signal.removeEventListener('abort', onAbort); onAbort = null }
34
+ }
26
35
  return Promise.race([
27
- idle,
36
+ idle.finally(cleanup),
28
37
  new Promise((_, reject) => {
29
- const timer = setTimeout(() => reject(new Error('turn timeout (' + timeoutMs + 'ms)')), timeoutMs)
38
+ timer = setTimeout(() => { cleanup(); reject(new Error('turn timeout (' + timeoutMs + 'ms)')) }, timeoutMs)
30
39
  timer.unref?.()
31
- signal?.addEventListener('abort', () => { clearTimeout(timer); reject(new DOMException('Aborted', 'AbortError')) }, { once: true })
40
+ if (signal) {
41
+ onAbort = () => { cleanup(); reject(new DOMException('Aborted', 'AbortError')) }
42
+ signal.addEventListener('abort', onAbort, { once: true })
43
+ }
32
44
  }),
33
45
  ])
34
46
  }
@@ -240,6 +252,10 @@ export async function runGatewayTurn(gw, chat, input, signal) {
240
252
  const { reply, typing, startStream, startProgress, react, inboundWasVoice, userId } = input
241
253
  const turnStartTime = Date.now()
242
254
  chat.turnActive = true
255
+ // Ownership token (#211): the dispatch site stores the AbortController on
256
+ // chat.turnOwner; the finally block below clears chat state only when this
257
+ // turn still owns it, so a stale turn never strips a newer turn's abort.
258
+ const turnOwner = chat.turnOwner
243
259
  const sessionId = chat.agent.session.id
244
260
  const tg = gw.tg()
245
261
  const streaming = tg.streaming === true && typeof startStream === 'function'
@@ -307,6 +323,8 @@ export async function runGatewayTurn(gw, chat, input, signal) {
307
323
  const turnTimeoutMs = Number(gw.config.agent?.turnTimeoutMs) || 600_000
308
324
  await whenIdleWithTimeout(chat.agent, turnTimeoutMs, signal)
309
325
  if (signal.aborted) {
326
+ // Stale edits must not overwrite the stopped message (#216)
327
+ scheduler?.cancel()
310
328
  if (progress) try { await progress.remove() } catch (err) { gw.logger?.debug?.('progress.remove failed on abort:', err?.message || err) }
311
329
  if (typeof react === 'function') react('').catch?.((e) => { gw.logger?.debug?.('react clear error:', e?.message || e) })
312
330
  const stoppedMsg = t('msg.turn_stopped', {}, gw.resolveLocale(input))
@@ -433,6 +451,8 @@ export async function runGatewayTurn(gw, chat, input, signal) {
433
451
  })
434
452
  }
435
453
  } catch (err) {
454
+ // Stale edits must not overwrite the error message (#216)
455
+ scheduler?.cancel()
436
456
  if (!signal?.aborted) {
437
457
  gw.sendAlert('error', {
438
458
  code: err?.code || 'EXCEPTION',
@@ -451,10 +471,17 @@ export async function runGatewayTurn(gw, chat, input, signal) {
451
471
  }
452
472
  } finally {
453
473
  stopTyping()
474
+ // Drop pending edits: after finalize/abort nothing may overwrite the
475
+ // delivered message (#216)
476
+ scheduler?.cancel()
454
477
  if (progress) try { await progress.remove() } catch (err) { gw.logger?.debug?.('progress.remove failed in finally:', err?.message || err) }
455
478
  if (typeof react === 'function') react('').catch?.((e) => { gw.logger?.debug?.('react clear error in finally:', e?.message || e) })
456
- chat.turnActive = false
457
- chat.abort = undefined
458
- gw.pending.delete(sessionId)
479
+ // Ownership-scoped cleanup (#211): if a newer turn already took over the
480
+ // chat state, this stale turn must leave it alone.
481
+ if (chat.turnOwner === turnOwner) {
482
+ chat.turnActive = false
483
+ chat.abort = undefined
484
+ gw.pending.delete(sessionId)
485
+ }
459
486
  }
460
487
  }
package/lib/gateway.js CHANGED
@@ -46,6 +46,8 @@ export class Gateway {
46
46
  this.config = config
47
47
  this.hooks = hooks
48
48
  this.chats = new Map()
49
+ // Single-flight chat creation (#215): key -> in-flight createChat promise
50
+ this.chatCreating = new Map()
49
51
  this.sessionToChat = new Map()
50
52
  this.sessionToThread = new Map()
51
53
  this.threadToSession = new Map()
@@ -174,14 +176,20 @@ export class Gateway {
174
176
  const turnInput = { ...input, attachments: [], inboundWasVoice: false }
175
177
  chat.turnActive = true
176
178
  try { chat.abort?.abort?.() } catch { /* safe best-effort abort */ }
177
- chat.abort = new AbortController()
178
- const run = chat.busy.then(() => this.runTurn(chat, turnInput, chat.abort.signal))
179
+ const ac = new AbortController()
180
+ // Per-turn ownership token (#211): state cleanup is ownership-scoped, so a
181
+ // stale turn can never clear a newer turn's abort/state.
182
+ chat.turnOwner = ac
183
+ chat.abort = ac
184
+ const run = chat.busy.then(() => this.runTurn(chat, turnInput, ac.signal))
179
185
  chat.busy = run.catch((e) => { void e })
180
186
  run.catch((err) => {
181
187
  const msg = err instanceof Error ? err.message : String(err)
182
188
  this.ctx.logger?.warn?.(`dsh-messenger-gateway: cron turn: ${msg}`)
183
- chat.turnActive = false
184
- chat.abort = undefined
189
+ if (chat.turnOwner === ac) {
190
+ chat.turnActive = false
191
+ chat.abort = undefined
192
+ }
185
193
  })
186
194
  return run
187
195
  }
@@ -556,8 +564,13 @@ export class Gateway {
556
564
  // Mark busy BEFORE yielding to the poll loop, otherwise steer/stop never see an active turn.
557
565
  chat.turnActive = true
558
566
  try { chat.abort?.abort?.() } catch { /* safe best-effort abort */ }
559
- chat.abort = new AbortController()
560
- const run = chat.busy.then(() => this.runTurn(chat, turnInput, chat.abort.signal))
567
+ const ac = new AbortController()
568
+ // Per-turn ownership token (#211): state cleanup is ownership-scoped, so
569
+ // a stale turn's finally/error handler can never clear a newer turn's
570
+ // abort/state.
571
+ chat.turnOwner = ac
572
+ chat.abort = ac
573
+ const run = chat.busy.then(() => this.runTurn(chat, turnInput, ac.signal))
561
574
  chat.busy = run.catch((e) => { void e })
562
575
  // Do NOT await: Telegram poll is sequential; awaiting blocked steer and /stop until the turn finished.
563
576
  run.catch((err) => {
@@ -570,8 +583,10 @@ export class Gateway {
570
583
  chatId: input.chatId,
571
584
  threadId: input.threadId,
572
585
  }).catch((e) => this.recordApiFailure('alert.turn', e))
573
- chat.turnActive = false
574
- chat.abort = undefined
586
+ if (chat.turnOwner === ac) {
587
+ chat.turnActive = false
588
+ chat.abort = undefined
589
+ }
575
590
  })
576
591
  } catch (err) {
577
592
  const msg = err instanceof Error ? err.message : String(err)
@@ -617,10 +632,21 @@ export class Gateway {
617
632
  async getOrCreateChat(key, input) {
618
633
  let chat = this.chats.get(key)
619
634
  if (!chat) {
620
- const threadKey = `${input.chatId}:${input.threadId || 0}`
621
- const existingSessionId = this.threadToSession.get(threadKey)
622
- chat = await this.createChat(key, input, existingSessionId)
623
- this.chats.set(key, chat)
635
+ // Single-flight (#215): webhook updates and media-group flushes can hit
636
+ // the same key concurrently; without a shared in-flight promise each
637
+ // caller creates its own session and the loser is never disposed.
638
+ let flight = this.chatCreating.get(key)
639
+ if (!flight) {
640
+ flight = (async () => {
641
+ const threadKey = `${input.chatId}:${input.threadId || 0}`
642
+ const existingSessionId = this.threadToSession.get(threadKey)
643
+ const created = await this.createChat(key, input, existingSessionId)
644
+ this.chats.set(key, created)
645
+ return created
646
+ })()
647
+ this.chatCreating.set(key, flight)
648
+ }
649
+ chat = await flight
624
650
  }
625
651
  chat.lastUsed = Date.now()
626
652
  chat.target = { platform: input.platform, chatId: input.chatId, threadId: input.threadId || 0 }
package/lib/stream.js CHANGED
@@ -171,9 +171,11 @@ export function createEditScheduler(editFn, intervalMs = 1200, firstChunkDelayMs
171
171
  let lastSent = ''
172
172
  let inFlight = Promise.resolve()
173
173
  let retryDelayMs = 0
174
+ let cancelled = false
174
175
 
175
176
  const flush = () => {
176
177
  timer = null
178
+ if (cancelled) return
177
179
  if (pending === null || pending === lastSent) return
178
180
  const text = pending
179
181
  inFlight = inFlight.then(async () => {
@@ -183,12 +185,13 @@ export function createEditScheduler(editFn, intervalMs = 1200, firstChunkDelayMs
183
185
  retryDelayMs = 0
184
186
  await new Promise((r) => setTimeout(r, delay))
185
187
  }
188
+ if (cancelled) return
186
189
  await editFn(text)
187
190
  lastSent = text
188
191
  } catch (err) {
189
192
  logger?.debug?.('stream chunk edit failed:', err?.message || err)
190
193
  const retry = parseRetryAfter(err)
191
- if (retry > 0) {
194
+ if (retry > 0 && !cancelled) {
192
195
  retryDelayMs = retry
193
196
  // Re-schedule flush with retry delay
194
197
  if (!timer) {
@@ -202,6 +205,7 @@ export function createEditScheduler(editFn, intervalMs = 1200, firstChunkDelayMs
202
205
 
203
206
  return {
204
207
  push(text) {
208
+ if (cancelled) return
205
209
  pending = text
206
210
  if (timer) return
207
211
  // Fast first chunk: when lastSent is empty, dispatch quickly so user sees immediate response.
@@ -210,16 +214,26 @@ export function createEditScheduler(editFn, intervalMs = 1200, firstChunkDelayMs
210
214
  timer = setTimeout(flush, delay)
211
215
  timer.unref?.()
212
216
  },
217
+ // cancel() drops every pending edit and stops the timer: after finalize,
218
+ // abort or error the message must not be overwritten by stale text (#216).
219
+ cancel() {
220
+ cancelled = true
221
+ pending = null
222
+ if (timer) { clearTimeout(timer); timer = null }
223
+ },
213
224
  async flush() {
214
225
  if (timer) { clearTimeout(timer); timer = null }
226
+ if (cancelled) return
215
227
  flush()
216
228
  await inFlight
229
+ if (cancelled) return
217
230
  // If there's still a pending difference (e.g. rate limit delay happened), wait and retry
218
231
  if (pending !== null && pending !== lastSent) {
219
232
  if (retryDelayMs > 0) {
220
233
  await new Promise((r) => setTimeout(r, retryDelayMs + 50))
221
234
  retryDelayMs = 0
222
235
  }
236
+ if (cancelled) return
223
237
  try {
224
238
  await editFn(pending)
225
239
  lastSent = pending
package/lib/webapp.js CHANGED
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-messenger-gateway",
3
- "version": "0.4.40",
3
+ "version": "0.4.42",
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",