@peopl-health/nexus 5.54.0-dev.8031 → 5.54.1

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.
@@ -162,6 +162,7 @@ class TwilioProvider extends MessageProvider {
162
162
  errorSource: 'twilio_sync',
163
163
  errorCode: twilioErr.code, errorMessage: twilioErr.message
164
164
  });
165
+ twilioErr.acceptedChunks = i;
165
166
  throw twilioErr;
166
167
  }
167
168
  await recordDeliveryAttempt({ messageData, messageId: parentId, twilioResult: result, kind, body: sends[i].body || null, variables: sentVariables });
@@ -203,7 +203,13 @@ class NexusMessaging {
203
203
  }
204
204
 
205
205
  async _transport(messageData) {
206
- const result = await this.provider.sendMessage(await this._repairOutbound(messageData));
206
+ let result;
207
+ try {
208
+ result = await this.provider.sendMessage(await this._repairOutbound(messageData));
209
+ } catch (error) {
210
+ await this._markSendFailed(messageData, error);
211
+ throw error;
212
+ }
207
213
 
208
214
  if (messageData.parentMessageId && result?.finalize && this.messageStorage?.finalizePendingMessage) {
209
215
  await this.messageStorage.finalizePendingMessage(messageData.parentMessageId, result.finalize.sid, {
@@ -217,6 +223,27 @@ class NexusMessaging {
217
223
  return result;
218
224
  }
219
225
 
226
+ async _markSendFailed(messageData, error) {
227
+ if (!messageData.parentMessageId || !this.messageStorage?.finalizePendingMessage) return;
228
+ if (error?.acceptedChunks > 0) {
229
+ logger.warn('[NexusMessaging] A long reply reached the patient only in part', {
230
+ code: messageData.code, acceptedChunks: error.acceptedChunks, error: error.message,
231
+ });
232
+ return;
233
+ }
234
+ try {
235
+ await this.messageStorage.finalizePendingMessage(messageData.parentMessageId, null, {
236
+ status: 'failed',
237
+ errorMessage: String(error?.message || error).slice(0, 500),
238
+ updatedAt: new Date(),
239
+ });
240
+ } catch (markError) {
241
+ logger.warn('[NexusMessaging] A failed send could not be marked failed', {
242
+ code: messageData.code, error: markError.message,
243
+ });
244
+ }
245
+ }
246
+
220
247
  async initialize(options = {}) {
221
248
  const { provider, providerConfig, mongoUri, messageStorage, llm, llmConfig, meta } = options;
222
249
 
@@ -8,7 +8,7 @@ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
8
8
  const { inboundRecoveryLive } = require('../clinical/flags/inboundRecoveryFlags');
9
9
  const { recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
10
10
  const { WriteClaimStore } = require('../clinical/services/writeClaimStore');
11
- const { getMessages, countMessages } = require('./messageService');
11
+ const { getMessages, countMessages, aggregateMessages } = require('./messageService');
12
12
 
13
13
  const MIN_AGE_MS = 5 * 60 * 1000;
14
14
  const MAX_AGE_MS = 60 * 60 * 1000;
@@ -23,6 +23,8 @@ const PATIENT_CONTACT_WINDOW = { timeZone: 'America/Monterrey', startHour: 8, en
23
23
  const recoveryClaims = new WriteClaimStore({ namespace: 'inbound-recovery', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
24
24
  const ticketClaims = new WriteClaimStore({ namespace: 'inbound-recovery-ticket', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
25
25
 
26
+ const FAILED_SEND = { 'statusInfo.status': 'failed', message_id: null };
27
+
26
28
  async function unansweredThreads(now) {
27
29
  return Thread.find(
28
30
  {
@@ -34,6 +36,21 @@ async function unansweredThreads(now) {
34
36
  ).sort({ lastMessageAt: 1 }).limit(SCAN_LIMIT).lean();
35
37
  }
36
38
 
39
+ async function codesWithAFailedSend(now) {
40
+ const rows = await aggregateMessages([
41
+ { $match: { ...FAILED_SEND, from_me: true, createdAt: { $gte: new Date(now.getTime() - MAX_AGE_MS) } } },
42
+ { $group: { _id: '$numero', firstFailedAt: { $min: '$createdAt' } } },
43
+ { $sort: { firstFailedAt: 1 } },
44
+ { $limit: SCAN_LIMIT },
45
+ ]);
46
+ return rows.map((row) => row._id);
47
+ }
48
+
49
+ async function candidateCodes(now) {
50
+ const [threads, failedSends] = await Promise.all([unansweredThreads(now), codesWithAFailedSend(now)]);
51
+ return [...new Set([...threads.map((thread) => thread.code), ...failedSends].filter(Boolean))];
52
+ }
53
+
37
54
  const threadIsOwnedByAHuman = (code) => botIsPaused(code, { label: '[inboundRecovery]' });
38
55
 
39
56
  async function stillUnanswered(code, now = new Date()) {
@@ -46,7 +63,7 @@ async function stillUnanswered(code, now = new Date()) {
46
63
  const ageMs = now.getTime() - new Date(newest.createdAt).getTime();
47
64
  if (!Number.isFinite(ageMs) || ageMs < MIN_AGE_MS || ageMs > MAX_AGE_MS) return null;
48
65
 
49
- const replies = await countMessages({ numero: code, from_me: true, createdAt: { $gt: newest.createdAt } });
66
+ const replies = await countMessages({ numero: code, from_me: true, createdAt: { $gt: newest.createdAt }, $nor: [FAILED_SEND] });
50
67
  return replies === 0 ? newest : null;
51
68
  }
52
69
 
@@ -69,24 +86,23 @@ async function sweepUnansweredInbound({
69
86
  isPaused = threadIsOwnedByAHuman,
70
87
  alert = recordUnresolvedRequest,
71
88
  } = {}) {
72
- let threads;
89
+ let codes;
73
90
  try {
74
- threads = await unansweredThreads(now);
91
+ codes = await candidateCodes(now);
75
92
  } catch (error) {
76
93
  logger.error('[inboundRecovery] unanswered scan failed', { error: error.message });
77
94
  return { scanned: 0, recovered: 0, alerted: 0, skipped: 0 };
78
95
  }
79
96
 
80
97
  const candidates = [];
81
- for (const thread of threads) {
82
- if (!thread.code) continue;
83
- if (isProcessing(thread.code)) continue;
98
+ for (const code of codes) {
99
+ if (isProcessing(code)) continue;
84
100
  try {
85
- const inbound = await stillUnanswered(thread.code, now);
86
- if (inbound) candidates.push({ code: thread.code, inbound });
101
+ const inbound = await stillUnanswered(code, now);
102
+ if (inbound) candidates.push({ code, inbound });
87
103
  } catch (error) {
88
104
  logger.error('[inboundRecovery] could not read one conversation; leaving it for the next pass', {
89
- code: thread.code, error: error.message,
105
+ code, error: error.message,
90
106
  });
91
107
  }
92
108
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.54.0-dev.8031",
3
+ "version": "5.54.1",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",