@peopl-health/nexus 5.59.5 → 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
|
-
|
|
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
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
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) {
|
|
@@ -32,6 +32,7 @@ const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMess
|
|
|
32
32
|
const { BatchingManager } = require('../core/BatchingManager');
|
|
33
33
|
const { ProcessingPipeline } = require('../core/ProcessingPipeline');
|
|
34
34
|
const { preProcessMessages, configureOpenAIProvider, AssistantProcessor, TURN_KIND } = require('../clinical');
|
|
35
|
+
const { deliveryOutcome } = require('../clinical/AssistantProcessor');
|
|
35
36
|
const { UNASSIGNED, alertOpsForClaimedMessage, coverIfUnassigned, coverUnansweredPatient } = require('../clinical/services/pausedSafetyNetService');
|
|
36
37
|
const { buildOutreachCarrier } = require('../clinical/services/outreachCarrierService');
|
|
37
38
|
const { routineOutreachCollisionReason } = require('../clinical/services/outreachSweepService');
|
|
@@ -52,6 +53,8 @@ const { invokeInteractiveRoute } = require('./interactiveRouteService');
|
|
|
52
53
|
|
|
53
54
|
const { PhiProcessor } = require('./PhiProcessor');
|
|
54
55
|
|
|
56
|
+
const PENDING_INSTRUCTION_WINDOW_MS = 2 * 60 * 1000;
|
|
57
|
+
|
|
55
58
|
const unbatchedRoutes = {
|
|
56
59
|
__proto__: null,
|
|
57
60
|
flow: 'handleFlow',
|
|
@@ -695,7 +698,7 @@ class NexusMessaging {
|
|
|
695
698
|
* PROCESSING PIPELINE
|
|
696
699
|
*/
|
|
697
700
|
|
|
698
|
-
async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true } = {}) {
|
|
701
|
+
async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true, onSent = null } = {}) {
|
|
699
702
|
let capturedResult = null;
|
|
700
703
|
const discardResponseFn = async (result) => {
|
|
701
704
|
await this.assistantProcessor.discardResponse(chatId, result);
|
|
@@ -719,6 +722,7 @@ class NexusMessaging {
|
|
|
719
722
|
return;
|
|
720
723
|
}
|
|
721
724
|
await this.assistantProcessor.sendResponse(chatId, result);
|
|
725
|
+
if (onSent && result?.delivery && deliveryOutcome(result.delivery) !== 'known_not_sent') await onSent(result);
|
|
722
726
|
};
|
|
723
727
|
|
|
724
728
|
const admission = mode === 'queue'
|
|
@@ -823,32 +827,67 @@ class NexusMessaging {
|
|
|
823
827
|
messageData,
|
|
824
828
|
this._saveMessageFn,
|
|
825
829
|
async ({ body, _id }) => {
|
|
830
|
+
let answered = [];
|
|
826
831
|
const runResult = await this._executeWithPipeline(code, 'instruction', 'queue',
|
|
827
|
-
async (preProcessResult, shouldContinue, runId) =>
|
|
828
|
-
code,
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
toolChoice: 'none',
|
|
833
|
-
turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
|
|
834
|
-
runId,
|
|
835
|
-
shouldContinue,
|
|
836
|
-
signal: this.batchingManager.getAbortSignal(runId),
|
|
832
|
+
async (preProcessResult, shouldContinue, runId) => {
|
|
833
|
+
const batch = await this._pendingInstructionBatch(code, _id, body);
|
|
834
|
+
if (!batch.length) {
|
|
835
|
+
logger.info('[processInstruction] Instruction already answered by an earlier run', { code, runId });
|
|
836
|
+
return null;
|
|
837
837
|
}
|
|
838
|
-
|
|
838
|
+
const result = await this.assistantProcessor.process({
|
|
839
|
+
code,
|
|
840
|
+
runOptions: {
|
|
841
|
+
prePromptResult: preProcessResult,
|
|
842
|
+
additionalInstructions: batch.map(m => m.body).join('\n\n'),
|
|
843
|
+
toolChoice: 'none',
|
|
844
|
+
turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
|
|
845
|
+
runId,
|
|
846
|
+
shouldContinue,
|
|
847
|
+
signal: this.batchingManager.getAbortSignal(runId),
|
|
848
|
+
}
|
|
849
|
+
});
|
|
850
|
+
answered = batch.map(m => m._id).filter(Boolean);
|
|
851
|
+
return result;
|
|
852
|
+
},
|
|
853
|
+
{
|
|
854
|
+
onSent: async () => {
|
|
855
|
+
if (!answered.length) return;
|
|
856
|
+
try {
|
|
857
|
+
await updateMessage({ _id: { $in: answered } }, { $set: { processed: true } });
|
|
858
|
+
} catch (err) {
|
|
859
|
+
logger.error('[processInstruction] Could not mark instructions processed', { error: err.message, code });
|
|
860
|
+
}
|
|
861
|
+
},
|
|
862
|
+
},
|
|
839
863
|
);
|
|
840
|
-
if (_id) {
|
|
841
|
-
try {
|
|
842
|
-
await updateMessage({ _id }, { $set: { processed: true } });
|
|
843
|
-
} catch (err) {
|
|
844
|
-
logger.error('[processInstruction] Could not mark instruction processed', { error: err.message, code });
|
|
845
|
-
}
|
|
846
|
-
}
|
|
847
864
|
return runResult;
|
|
848
865
|
},
|
|
849
866
|
);
|
|
850
867
|
}
|
|
851
868
|
|
|
869
|
+
async _pendingInstructionBatch(code, ownId, ownBody) {
|
|
870
|
+
if (!ownId) return [{ _id: null, body: ownBody }];
|
|
871
|
+
try {
|
|
872
|
+
const rows = await getMessages(
|
|
873
|
+
{
|
|
874
|
+
numero: code,
|
|
875
|
+
origin: 'instruction',
|
|
876
|
+
message_id: /^instruction_/,
|
|
877
|
+
$or: [{ _id: ownId }, { processed: false, createdAt: { $gte: new Date(Date.now() - PENDING_INSTRUCTION_WINDOW_MS) } }],
|
|
878
|
+
},
|
|
879
|
+
{ sort: { _id: 1 }, select: '_id body processed' },
|
|
880
|
+
);
|
|
881
|
+
const own = rows.find(m => String(m._id) === String(ownId));
|
|
882
|
+
if (own?.processed) return [];
|
|
883
|
+
const batch = rows.filter(m => m === own || !m.processed).map(m => (m === own ? { _id: ownId, body: ownBody } : m));
|
|
884
|
+
return own ? batch : [...batch, { _id: ownId, body: ownBody }];
|
|
885
|
+
} catch (err) {
|
|
886
|
+
logger.error('[processInstruction] Could not read pending instructions', { error: err.message, code });
|
|
887
|
+
return [{ _id: ownId, body: ownBody }];
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
852
891
|
/*
|
|
853
892
|
* A turn nobody asked for: no inbound message, and no obligation to produce an outbound.
|
|
854
893
|
* Unlike processInstruction this keeps the full clinical toolset and lets the agent end in a hold,
|
|
@@ -83,4 +83,15 @@ async function updateDeliveryAttemptByTwilioSid(twilioSid, { status, errorCode =
|
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
-
|
|
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 };
|