@peopl-health/nexus 5.59.6 → 5.59.7

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.
@@ -10,6 +10,7 @@ const { logger } = require('../../utils/logger');
10
10
  const { escapePatientMessageMarkers, formatPatientMessage } = require('../../helpers/patientMessageHelper');
11
11
 
12
12
  const { getMessageTools, formatMessage } = require('../../helpers/messageHelper');
13
+ const { messagesWithAcceptedAttempt } = require('../../helpers/deliveryAttemptHelper');
13
14
 
14
15
  const { safeParse, isPlainObject } = require('../../utils/jsonUtils');
15
16
  const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
@@ -19,6 +20,8 @@ const { getMessages, countMessages } = require('../../services/messageService');
19
20
  const { getTurnScopedToolNames, getReplayArgsByTool } = require('../../services/toolRegistryService');
20
21
  const { CURRENT_TURN } = require('../promptPlacement');
21
22
 
23
+ const { DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../../models/deliveryAttemptModel');
24
+
22
25
  const { MemoryManager } = require('./MemoryManager');
23
26
 
24
27
  const DEFAULT_MAX_HISTORICAL_MESSAGES = 50;
@@ -30,10 +33,16 @@ const CAREGIVER_TURN_PREFIX = '[cuidador]';
30
33
  const CURRENT_TURN_GAP_MS = 15 * 60 * 1000;
31
34
  const CURRENT_TURN_MAX_MESSAGES = 15;
32
35
  const OUTBOUND_TAIL_MAX_MESSAGES = 10;
36
+ const OUTBOUND_TAIL_SCAN_MESSAGES = 50;
33
37
  const TURN_TIMESTAMP_PREFIX_RX = /^\[[^\]]*\]\s*/;
34
38
 
39
+ const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
40
+
35
41
  const inline = (value) => sanitizeInlineText(value, Infinity);
36
42
 
43
+ const deliveredWhileWaitingNote = (text) =>
44
+ `${OPERATOR_TURN_PREFIX} Mientras este turno esperaba, ya le enviaste al paciente: "${text}". No repitas ese contenido. Responde con normalidad y por completo a todo lo demás que escribió el paciente.`;
45
+
37
46
  function readComorbidities(value) {
38
47
  const parsed = typeof value === 'string' ? safeParse(value, null) : value;
39
48
  if (!isPlainObject(parsed)) return inline(value);
@@ -113,9 +122,11 @@ class DefaultMemoryManager extends MemoryManager {
113
122
  }
114
123
 
115
124
  for (const msg of await this._outboundTail(thread.code, beforeCheckpoint, config)) {
116
- const prefix = this._speakerPrefix(msg, null);
117
125
  for (const content of formatMessage(msg).filter(Boolean)) {
118
- context.push({ [CURRENT_TURN]: true, role: 'user', content: `${prefix}${content}`, type: 'message' });
126
+ const line = msg.origin === 'assistant'
127
+ ? deliveredWhileWaitingNote(content.replace(TURN_TIMESTAMP_PREFIX_RX, ''))
128
+ : `${this._speakerPrefix(msg, null)}${content}`;
129
+ context.push({ [CURRENT_TURN]: true, role: 'user', content: line, type: 'message' });
119
130
  }
120
131
  }
121
132
 
@@ -130,15 +141,21 @@ class DefaultMemoryManager extends MemoryManager {
130
141
  const upperBound = config.tailUpperBound ?? (config.beforeCheckpoint ? null : new Date());
131
142
  if (!beforeCheckpoint || !upperBound) return [];
132
143
 
133
- const tail = await getMessages(
134
- {
135
- numero: code,
136
- origin: 'whatsapp_platform',
137
- createdAt: { $gt: beforeCheckpoint, $lte: upperBound },
138
- },
139
- { sort: { createdAt: -1 }, limit: OUTBOUND_TAIL_MAX_MESSAGES },
140
- );
141
- return tail.reverse();
144
+ const window = { numero: code, createdAt: { $gt: beforeCheckpoint, $lte: upperBound } };
145
+ const newest = { sort: { createdAt: -1 }, limit: OUTBOUND_TAIL_MAX_MESSAGES };
146
+ const [team, replies] = await Promise.all([
147
+ getMessages({ ...window, origin: 'whatsapp_platform' }, newest),
148
+ getMessages(
149
+ { ...window, origin: 'assistant', 'statusInfo.status': { $nin: UNDELIVERED_STATUSES } },
150
+ { ...newest, limit: OUTBOUND_TAIL_SCAN_MESSAGES },
151
+ ),
152
+ ]);
153
+ const transportConfirmed = (msg) => Boolean(msg.message_id) || DELIVERY_ATTEMPT_LANDED_STATUSES.includes(msg.statusInfo?.status);
154
+ const accepted = await messagesWithAcceptedAttempt(replies.filter(m => !transportConfirmed(m)).map(m => m._id));
155
+ const delivered = replies
156
+ .filter(m => transportConfirmed(m) || accepted.has(String(m._id)))
157
+ .slice(0, OUTBOUND_TAIL_MAX_MESSAGES);
158
+ return [...team, ...delivered].sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
142
159
  }
143
160
 
144
161
  _currentTurnMessages(ordered) {
@@ -83,4 +83,15 @@ async function updateDeliveryAttemptByTwilioSid(twilioSid, { status, errorCode =
83
83
  }
84
84
  }
85
85
 
86
- module.exports = { recordDeliveryAttempt, updateDeliveryAttemptByTwilioSid };
86
+ async function messagesWithAcceptedAttempt(messageIds) {
87
+ if (!messageIds?.length) return new Set();
88
+ const ids = await DeliveryAttempt.distinct('messageId', {
89
+ messageId: { $in: messageIds },
90
+ kind: 'freeform',
91
+ twilioSid: { $ne: null },
92
+ status: { $nin: ['failed', 'undelivered'] },
93
+ });
94
+ return new Set(ids.map(String));
95
+ }
96
+
97
+ module.exports = { recordDeliveryAttempt, updateDeliveryAttemptByTwilioSid, messagesWithAcceptedAttempt };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.59.6",
3
+ "version": "5.59.7",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",