@goodandready/dsh-messenger-gateway 0.4.41 → 0.4.43
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 +2 -0
- package/lib/gateway-commands.js +14 -0
- package/lib/gateway-turn.js +22 -3
- package/lib/gateway.js +28 -8
- package/lib/outbox.js +135 -33
- package/lib/stream.js +15 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -157,6 +157,8 @@ In addition to Telegram, outbound messages can be dispatched to Discord and Slac
|
|
|
157
157
|
- `telegram.apiRoot` with plain `http` is only accepted for loopback hosts (a local Bot API server); the webhook URL is logged without its secret path
|
|
158
158
|
- `webhooks.enabled: false` removes the messenger write routes entirely; GET `/update` and `/messenger` require trusted callers
|
|
159
159
|
- `webAppEnabled: false` takes the whole Mini App surface down (dashboard and every `/api/*` answer 404) and clears the menu button
|
|
160
|
+
- The outbox queue (alerts, cron, autonomous messages) is multi-writer safe: all mutations take an exclusive lock and reload on-disk state, so two gateway processes sharing a home neither lose nor duplicate jobs; DLQ alerts bypass the queue and are rate-limited per chat
|
|
161
|
+
- Note: turn replies to the user are streamed directly and are not covered by the outbox retry guarantee (by design — streaming edits cannot be replayed)
|
|
160
162
|
- Inline keyboard `replyMarkup` sent via `/messenger/send` is schema-validated (button text/actions, sizes) before delivery
|
|
161
163
|
- All state files (pairing, outbox, voice prefs) are written with `0600` permissions inside `0700` directories
|
|
162
164
|
- `sessionList`: `true` (default) — enables `/sessions` and `/resume` commands in chat
|
package/lib/gateway-commands.js
CHANGED
|
@@ -244,6 +244,20 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
244
244
|
const sessions = gw.ctx.get?.('sessions') || gw.ctx.sessions
|
|
245
245
|
try { await sessions?.flush(newChat.agent.session) } catch (err) { gw.logger?.debug?.('fork session flush error:', err?.message || err) }
|
|
246
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)
|
|
247
261
|
gw.chats.set(key, newChat)
|
|
248
262
|
return reply(`🔀 Forked session!\nOld session: ${oldSession.id}\nNew session: ${newChat.agent.session.id}\nContext preserved (${oldMessages.length} messages).`)
|
|
249
263
|
} catch (err) {
|
package/lib/gateway-turn.js
CHANGED
|
@@ -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
|
-
|
|
38
|
+
timer = setTimeout(() => { cleanup(); reject(new Error('turn timeout (' + timeoutMs + 'ms)')) }, timeoutMs)
|
|
30
39
|
timer.unref?.()
|
|
31
|
-
|
|
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
|
}
|
|
@@ -311,6 +323,8 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
311
323
|
const turnTimeoutMs = Number(gw.config.agent?.turnTimeoutMs) || 600_000
|
|
312
324
|
await whenIdleWithTimeout(chat.agent, turnTimeoutMs, signal)
|
|
313
325
|
if (signal.aborted) {
|
|
326
|
+
// Stale edits must not overwrite the stopped message (#216)
|
|
327
|
+
scheduler?.cancel()
|
|
314
328
|
if (progress) try { await progress.remove() } catch (err) { gw.logger?.debug?.('progress.remove failed on abort:', err?.message || err) }
|
|
315
329
|
if (typeof react === 'function') react('').catch?.((e) => { gw.logger?.debug?.('react clear error:', e?.message || e) })
|
|
316
330
|
const stoppedMsg = t('msg.turn_stopped', {}, gw.resolveLocale(input))
|
|
@@ -437,6 +451,8 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
437
451
|
})
|
|
438
452
|
}
|
|
439
453
|
} catch (err) {
|
|
454
|
+
// Stale edits must not overwrite the error message (#216)
|
|
455
|
+
scheduler?.cancel()
|
|
440
456
|
if (!signal?.aborted) {
|
|
441
457
|
gw.sendAlert('error', {
|
|
442
458
|
code: err?.code || 'EXCEPTION',
|
|
@@ -455,6 +471,9 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
455
471
|
}
|
|
456
472
|
} finally {
|
|
457
473
|
stopTyping()
|
|
474
|
+
// Drop pending edits: after finalize/abort nothing may overwrite the
|
|
475
|
+
// delivered message (#216)
|
|
476
|
+
scheduler?.cancel()
|
|
458
477
|
if (progress) try { await progress.remove() } catch (err) { gw.logger?.debug?.('progress.remove failed in finally:', err?.message || err) }
|
|
459
478
|
if (typeof react === 'function') react('').catch?.((e) => { gw.logger?.debug?.('react clear error in finally:', e?.message || e) })
|
|
460
479
|
// Ownership-scoped cleanup (#211): if a newer turn already took over the
|
package/lib/gateway.js
CHANGED
|
@@ -48,6 +48,8 @@ export class Gateway {
|
|
|
48
48
|
this.chats = new Map()
|
|
49
49
|
// Single-flight chat creation (#215): key -> in-flight createChat promise
|
|
50
50
|
this.chatCreating = new Map()
|
|
51
|
+
// DLQ alert rate limiting (#226): chatId -> last alert timestamp
|
|
52
|
+
this.dlqAlertAt = new Map()
|
|
51
53
|
this.sessionToChat = new Map()
|
|
52
54
|
this.sessionToThread = new Map()
|
|
53
55
|
this.threadToSession = new Map()
|
|
@@ -76,12 +78,7 @@ export class Gateway {
|
|
|
76
78
|
await this.messengerSend(job.target, job.payload)
|
|
77
79
|
},
|
|
78
80
|
onDlq: (job, err) => {
|
|
79
|
-
this.
|
|
80
|
-
code: 'OUTBOX_DLQ',
|
|
81
|
-
message: `Outbox message failed permanently to ${job.target?.chatId}: ${err.message}`,
|
|
82
|
-
chatId: job.target?.chatId,
|
|
83
|
-
threadId: job.target?.threadId,
|
|
84
|
-
}).catch((e) => this.recordApiFailure('outbox.dlq_alert', e))
|
|
81
|
+
this.notifyDlq(job, err)
|
|
85
82
|
},
|
|
86
83
|
logger: this.logger,
|
|
87
84
|
})
|
|
@@ -227,15 +224,38 @@ export class Gateway {
|
|
|
227
224
|
return out
|
|
228
225
|
}
|
|
229
226
|
|
|
230
|
-
|
|
227
|
+
// DLQ alert delivery (#226): sent DIRECTLY (bypassing the outbox — alerting
|
|
228
|
+
// about the queue through the queue is the recursion) and deduplicated per
|
|
229
|
+
// chat (one alert per chat per 60s) so a permanently failing chat does not
|
|
230
|
+
// generate an alert storm.
|
|
231
|
+
notifyDlq(job, err) {
|
|
232
|
+
const chatId = String(job.target?.chatId || '')
|
|
233
|
+
const now = Date.now()
|
|
234
|
+
const last = this.dlqAlertAt.get(chatId) || 0
|
|
235
|
+
if (now - last < 60_000) {
|
|
236
|
+
this.logger?.warn?.(`[outbox] DLQ alert for ${chatId} suppressed (rate limit): ${err?.message || err}`)
|
|
237
|
+
return
|
|
238
|
+
}
|
|
239
|
+
this.dlqAlertAt.set(chatId, now)
|
|
240
|
+
this.sendAlert('error', {
|
|
241
|
+
code: 'OUTBOX_DLQ',
|
|
242
|
+
message: `Outbox message failed permanently to ${job.target?.chatId}: ${err.message}`,
|
|
243
|
+
chatId: job.target?.chatId,
|
|
244
|
+
threadId: job.target?.threadId,
|
|
245
|
+
}, { bypassOutbox: true }).catch((e) => this.recordApiFailure('outbox.dlq_alert', e))
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async sendAlert(type, payload = {}, opts = {}) {
|
|
231
249
|
try {
|
|
232
250
|
const target = resolveAlertTarget(this)
|
|
233
251
|
if (!target) return
|
|
252
|
+
if (this.config.telegram?.alerts?.enabled === false) return
|
|
234
253
|
const allowedEvents = this.config.telegram?.alerts?.events || ['error', 'pairing']
|
|
235
254
|
if (type !== 'status' && !allowedEvents.includes(type)) return
|
|
236
255
|
|
|
237
256
|
const text = formatAlertMessage(type, payload)
|
|
238
|
-
|
|
257
|
+
// bypassOutbox: DLQ alerts must not re-enter the queue they report on (#226)
|
|
258
|
+
await this.sendToMessenger(target, { text }, opts.bypassOutbox ? { reliable: false } : opts)
|
|
239
259
|
} catch (err) {
|
|
240
260
|
this.ctx.logger?.warn?.(`sendAlert (${type}): ${err.message}`)
|
|
241
261
|
}
|
package/lib/outbox.js
CHANGED
|
@@ -1,21 +1,67 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Outbound Transactional Queue (Outbox DLQ) with Offline Recovery & Backoff (#155).
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* Guarantee scope (#217): the queue covers alerts, cron prompts and
|
|
5
|
+
* autonomous messages — everything sent through sendToMessenger. Turn
|
|
6
|
+
* replies to the user are streamed directly (adapter.sendReply) because
|
|
7
|
+
* streaming edits cannot be replayed from a queue; that limitation is
|
|
8
|
+
* documented in DESIGN.md.
|
|
9
|
+
*
|
|
10
|
+
* Single-writer safety (#218): every mutation (enqueue / flush / retry /
|
|
11
|
+
* clear) takes an exclusive lock file scoped to the queue path and reloads
|
|
12
|
+
* the on-disk state inside the lock — the disk copy is the source of truth,
|
|
13
|
+
* so two gateway processes sharing a home neither lose nor duplicate jobs.
|
|
14
|
+
*
|
|
6
15
|
* - Atomic persistent disk queue (~/.dsh/storages/outbox-queue.json).
|
|
7
16
|
* - Exponential backoff with jitter and Telegram 429 `retry_after` awareness.
|
|
8
17
|
* - Dead Letter Queue (DLQ) for items failing after max retries or terminal errors.
|
|
9
18
|
* - Recovery of pending uncommitted outbound jobs on gateway startup.
|
|
10
19
|
*/
|
|
11
20
|
|
|
12
|
-
import { existsSync, readFileSync } from 'node:fs'
|
|
13
|
-
import { join } from 'node:path'
|
|
21
|
+
import { existsSync, readFileSync, openSync, writeSync, closeSync, unlinkSync, statSync, mkdirSync } from 'node:fs'
|
|
22
|
+
import { join, dirname } from 'node:path'
|
|
14
23
|
import { homedir } from 'node:os'
|
|
15
24
|
import { randomUUID } from 'node:crypto'
|
|
16
25
|
import { writeJsonAtomic } from './storage-atomic.js'
|
|
17
26
|
import { isTopicGoneError } from './telegram-errors.js'
|
|
18
27
|
|
|
28
|
+
const LOCK_STALE_MS = 30_000
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Exclusive lock file scoped to the queue (#218). Returns false when another
|
|
32
|
+
* writer holds a fresh lock; steals locks older than LOCK_STALE_MS (crashed
|
|
33
|
+
* writer). The caller must releaseLock() when it returns true.
|
|
34
|
+
*/
|
|
35
|
+
export function acquireLock(lockPath, staleMs = LOCK_STALE_MS) {
|
|
36
|
+
mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 })
|
|
37
|
+
try {
|
|
38
|
+
const fd = openSync(lockPath, 'wx')
|
|
39
|
+
try { writeSync(fd, String(process.pid)) } catch { /* best-effort */ }
|
|
40
|
+
closeSync(fd)
|
|
41
|
+
return true
|
|
42
|
+
} catch (err) {
|
|
43
|
+
if (err.code !== 'EEXIST') throw err
|
|
44
|
+
}
|
|
45
|
+
let ageMs = 0
|
|
46
|
+
try {
|
|
47
|
+
ageMs = Date.now() - statSync(lockPath).mtimeMs
|
|
48
|
+
} catch { ageMs = staleMs + 1 }
|
|
49
|
+
if (ageMs < staleMs) return false
|
|
50
|
+
try { unlinkSync(lockPath) } catch { return false }
|
|
51
|
+
try {
|
|
52
|
+
const fd = openSync(lockPath, 'wx')
|
|
53
|
+
try { writeSync(fd, String(process.pid)) } catch { /* best-effort */ }
|
|
54
|
+
closeSync(fd)
|
|
55
|
+
return true
|
|
56
|
+
} catch {
|
|
57
|
+
return false
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function releaseLock(lockPath) {
|
|
62
|
+
try { unlinkSync(lockPath) } catch { /* already gone */ }
|
|
63
|
+
}
|
|
64
|
+
|
|
19
65
|
export function resolveOutboxStoragePath(baseDir) {
|
|
20
66
|
if (baseDir) return join(baseDir, 'outbox-queue.json')
|
|
21
67
|
const dshHome = (typeof process !== 'undefined' && process.env?.DSH_HOME) || ''
|
|
@@ -79,16 +125,30 @@ export function createOutboxQueue(options = {}) {
|
|
|
79
125
|
let pending = []
|
|
80
126
|
let dlq = []
|
|
81
127
|
let timer = null
|
|
82
|
-
let isFlushing = false
|
|
83
128
|
let isStopped = false
|
|
129
|
+
const lockPath = `${storagePath}.lock`
|
|
84
130
|
|
|
85
|
-
function
|
|
131
|
+
function loadDiskIntoMemory() {
|
|
86
132
|
try {
|
|
87
133
|
if (existsSync(storagePath)) {
|
|
88
134
|
const raw = readFileSync(storagePath, 'utf8')
|
|
89
135
|
const data = JSON.parse(raw)
|
|
90
|
-
|
|
91
|
-
|
|
136
|
+
// Merge (#218): adopt jobs added to disk by another writer; drop our
|
|
137
|
+
// in-memory copies that another writer has already removed (it sent
|
|
138
|
+
// or DLQ'd them under the lock). In-memory runtime state (backoff
|
|
139
|
+
// nextRetryAt) for jobs still on disk is preserved.
|
|
140
|
+
const diskPending = Array.isArray(data.pending) ? data.pending : []
|
|
141
|
+
const diskDlq = Array.isArray(data.dlq) ? data.dlq : []
|
|
142
|
+
const diskPendingIds = new Set(diskPending.map((j) => j.id))
|
|
143
|
+
for (const j of diskPending) {
|
|
144
|
+
if (!pending.some((m) => m.id === j.id)) pending.push(j)
|
|
145
|
+
}
|
|
146
|
+
pending = pending.filter((m) => diskPendingIds.has(m.id))
|
|
147
|
+
const diskDlqIds = new Set(diskDlq.map((j) => j.id))
|
|
148
|
+
for (const j of diskDlq) {
|
|
149
|
+
if (!dlq.some((m) => m.id === j.id)) dlq.push(j)
|
|
150
|
+
}
|
|
151
|
+
dlq = dlq.filter((m) => diskDlqIds.has(m.id))
|
|
92
152
|
if (pending.length > 0 && logger) {
|
|
93
153
|
logger.info?.(`[outbox] recovered ${pending.length} pending outbound jobs from disk`)
|
|
94
154
|
}
|
|
@@ -100,7 +160,7 @@ export function createOutboxQueue(options = {}) {
|
|
|
100
160
|
}
|
|
101
161
|
}
|
|
102
162
|
|
|
103
|
-
|
|
163
|
+
loadDiskIntoMemory()
|
|
104
164
|
|
|
105
165
|
async function persist() {
|
|
106
166
|
try {
|
|
@@ -112,17 +172,36 @@ export function createOutboxQueue(options = {}) {
|
|
|
112
172
|
}
|
|
113
173
|
}
|
|
114
174
|
|
|
175
|
+
const PID = process.pid
|
|
176
|
+
const CLAIM_MS = 60_000
|
|
177
|
+
|
|
115
178
|
async function flush() {
|
|
116
|
-
if (
|
|
179
|
+
if (isStopped) return
|
|
117
180
|
if (!pending.length) return
|
|
118
|
-
|
|
181
|
+
// Brief retry loop: enqueue()'s void flush may transiently hold the lock.
|
|
182
|
+
let lk = false
|
|
183
|
+
for (let i = 0; i < 3 && !lk; i++) {
|
|
184
|
+
lk = acquireLock(lockPath)
|
|
185
|
+
if (!lk) await new Promise((r) => setTimeout(r, 50))
|
|
186
|
+
}
|
|
187
|
+
if (!lk) return // genuinely busy: the lock holder will process everything
|
|
119
188
|
const now = Date.now()
|
|
120
189
|
let dirty = false
|
|
121
190
|
|
|
122
191
|
try {
|
|
192
|
+
// Adopt jobs enqueued by another writer while we didn't hold the lock;
|
|
193
|
+
// keep our in-memory runtime state (nextRetryAt backoff) for known ids.
|
|
194
|
+
loadDiskIntoMemory()
|
|
195
|
+
|
|
123
196
|
const readyJobs = pending.filter((j) => (j.nextRetryAt || 0) <= now)
|
|
124
197
|
for (const job of readyJobs) {
|
|
125
198
|
if (isStopped) break
|
|
199
|
+
// Job claim (#218): a job locked by another live writer is skipped —
|
|
200
|
+
// claims expire after CLAIM_MS so a crashed writer's jobs are adopted.
|
|
201
|
+
if (job.claimedBy && job.claimedBy !== PID && job.claimUntil > now) continue
|
|
202
|
+
job.claimedBy = PID
|
|
203
|
+
job.claimUntil = now + CLAIM_MS
|
|
204
|
+
dirty = true
|
|
126
205
|
try {
|
|
127
206
|
if (typeof senderFn !== 'function') {
|
|
128
207
|
throw new Error('outbox senderFn not configured')
|
|
@@ -160,6 +239,7 @@ export function createOutboxQueue(options = {}) {
|
|
|
160
239
|
const retryAfter = parseRetryAfter(err)
|
|
161
240
|
const delayMs = computeOutboxBackoffMs(job.attempts, retryAfter)
|
|
162
241
|
job.nextRetryAt = Date.now() + delayMs
|
|
242
|
+
job.claimUntil = 0 // backoff: release the claim for the retry window
|
|
163
243
|
dirty = true
|
|
164
244
|
if (logger) {
|
|
165
245
|
logger.warn?.(`[outbox] job ${job.id} failed (attempt ${job.attempts}/${max}), retrying in ${Math.round(delayMs / 1000)}s: ${job.lastError}`)
|
|
@@ -168,10 +248,10 @@ export function createOutboxQueue(options = {}) {
|
|
|
168
248
|
}
|
|
169
249
|
}
|
|
170
250
|
} finally {
|
|
171
|
-
isFlushing = false
|
|
172
251
|
if (dirty) {
|
|
173
252
|
await persist()
|
|
174
253
|
}
|
|
254
|
+
releaseLock(lockPath)
|
|
175
255
|
}
|
|
176
256
|
}
|
|
177
257
|
|
|
@@ -187,8 +267,17 @@ export function createOutboxQueue(options = {}) {
|
|
|
187
267
|
nextRetryAt: Date.now(),
|
|
188
268
|
lastError: null,
|
|
189
269
|
}
|
|
190
|
-
|
|
191
|
-
|
|
270
|
+
while (!acquireLock(lockPath)) {
|
|
271
|
+
await new Promise((r) => setTimeout(r, 100))
|
|
272
|
+
}
|
|
273
|
+
try {
|
|
274
|
+
// Merge under the lock (#218): adopt jobs another instance enqueued.
|
|
275
|
+
loadDiskIntoMemory()
|
|
276
|
+
pending.push(item)
|
|
277
|
+
await persist()
|
|
278
|
+
} finally {
|
|
279
|
+
releaseLock(lockPath)
|
|
280
|
+
}
|
|
192
281
|
void flush()
|
|
193
282
|
return item
|
|
194
283
|
}
|
|
@@ -221,31 +310,44 @@ export function createOutboxQueue(options = {}) {
|
|
|
221
310
|
|
|
222
311
|
async function retryDlq() {
|
|
223
312
|
if (!dlq.length) return 0
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
313
|
+
while (!acquireLock(lockPath)) {
|
|
314
|
+
await new Promise((r) => setTimeout(r, 100))
|
|
315
|
+
}
|
|
316
|
+
let count = 0
|
|
317
|
+
try {
|
|
318
|
+
count = dlq.length
|
|
319
|
+
for (const item of dlq) {
|
|
320
|
+
pending.push({
|
|
321
|
+
id: item.id || randomUUID(),
|
|
322
|
+
type: item.type,
|
|
323
|
+
target: item.target,
|
|
324
|
+
payload: item.payload,
|
|
325
|
+
attempts: 0,
|
|
326
|
+
maxAttempts: defaultMaxAttempts,
|
|
327
|
+
createdAt: Date.now(),
|
|
328
|
+
nextRetryAt: Date.now(),
|
|
329
|
+
lastError: null,
|
|
330
|
+
})
|
|
331
|
+
}
|
|
332
|
+
dlq = []
|
|
333
|
+
await persist()
|
|
334
|
+
} finally {
|
|
335
|
+
releaseLock(lockPath)
|
|
237
336
|
}
|
|
238
|
-
dlq = []
|
|
239
|
-
await persist()
|
|
240
337
|
await flush()
|
|
241
338
|
return count
|
|
242
339
|
}
|
|
243
340
|
|
|
244
341
|
async function clearDlq() {
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
342
|
+
if (!acquireLock(lockPath)) return 0
|
|
343
|
+
try {
|
|
344
|
+
const count = dlq.length
|
|
345
|
+
dlq = []
|
|
346
|
+
await persist()
|
|
347
|
+
return count
|
|
348
|
+
} finally {
|
|
349
|
+
releaseLock(lockPath)
|
|
350
|
+
}
|
|
249
351
|
}
|
|
250
352
|
|
|
251
353
|
return {
|
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodandready/dsh-messenger-gateway",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.43",
|
|
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",
|