@peopl-health/nexus 5.75.2 → 5.75.4
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.
|
@@ -41,6 +41,15 @@ const anyReplyFilter = (code, since) => ({
|
|
|
41
41
|
]
|
|
42
42
|
});
|
|
43
43
|
|
|
44
|
+
const staffSendFilter = (code, since) => ({
|
|
45
|
+
numero: code,
|
|
46
|
+
from_me: true,
|
|
47
|
+
origin: { $in: HUMAN_ORIGINS },
|
|
48
|
+
triggeredBy: { $regex: '@' },
|
|
49
|
+
'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
|
|
50
|
+
createdAt: { $gt: since }
|
|
51
|
+
});
|
|
52
|
+
|
|
44
53
|
const settledHumanReplyFilter = (code, since, unconfirmedBefore) => ({
|
|
45
54
|
...humanReplyFilter(code, since),
|
|
46
55
|
$or: [
|
|
@@ -81,6 +90,7 @@ module.exports = {
|
|
|
81
90
|
anyReplyFilter,
|
|
82
91
|
humanReplyFilter,
|
|
83
92
|
settledHumanReplyFilter,
|
|
93
|
+
staffSendFilter,
|
|
84
94
|
CHOICE_LABEL_KEYS,
|
|
85
95
|
configureSafetyNet,
|
|
86
96
|
_resetSafetyNetConfig,
|
|
@@ -8,10 +8,12 @@ const {
|
|
|
8
8
|
getSafetyNetLabel,
|
|
9
9
|
getSafetyNetPhone,
|
|
10
10
|
getSafetyNetUnassignedContentSid,
|
|
11
|
-
getTapWindowMs
|
|
11
|
+
getTapWindowMs,
|
|
12
|
+
staffSendFilter
|
|
12
13
|
} = require('../config/safetyNetConfig');
|
|
13
14
|
const { logger } = require('../../utils/logger');
|
|
14
15
|
const { phoneDigits } = require('../../helpers/whatsappHelper');
|
|
16
|
+
const { isStaffSend } = require('../../helpers/staffSendHelper');
|
|
15
17
|
|
|
16
18
|
const { patientIsDeceased, pausedSince } = require('../../helpers/pausedThreadHelper');
|
|
17
19
|
const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../../helpers/sendClaimHelper');
|
|
@@ -31,6 +33,12 @@ const CHOICES = ['callback'];
|
|
|
31
33
|
const PAUSED = 'paused';
|
|
32
34
|
const UNASSIGNED = 'unassigned';
|
|
33
35
|
const REQUEST_CATEGORY = 'contact_team_member';
|
|
36
|
+
const COURTESY_ONLY = 'courtesy_only';
|
|
37
|
+
const UNANSWERED_LOOKBACK = 20;
|
|
38
|
+
const COURTESY_ANCHORS = new Set(['hola', 'gracias', 'agradezco', 'agradecida', 'agradecido', 'saludos', 'buen', 'buenas', 'buenos', 'bendiciones']);
|
|
39
|
+
const COURTESY_MODIFIERS = new Set(['muchas', 'mil', 'tardes', 'dias', 'días', 'noches', 'su', 'tu', 'la', 'informacion', 'información', 'igualmente']);
|
|
40
|
+
const COURTESY_EMOJI = /(?:😊|🙂|🙏|❤|👍)\uFE0F?[\u{1F3FB}-\u{1F3FF}]?/gu;
|
|
41
|
+
const COURTESY_CHARACTERS = /^[\p{L}\s.,!¡]*$/u;
|
|
34
42
|
|
|
35
43
|
const REQUEST_COPY = {
|
|
36
44
|
callback: {
|
|
@@ -109,6 +117,32 @@ function templateFor(reason) {
|
|
|
109
117
|
return getSafetyNetUnassignedContentSid() || getSafetyNetContentSid();
|
|
110
118
|
}
|
|
111
119
|
|
|
120
|
+
const writtenText = (message) => String(message?.plainBody || message?.body || '').trim();
|
|
121
|
+
|
|
122
|
+
function isCourtesyText(text) {
|
|
123
|
+
const plain = text.normalize('NFC').replace(COURTESY_EMOJI, ' ');
|
|
124
|
+
if (!COURTESY_CHARACTERS.test(plain)) return false;
|
|
125
|
+
const words = plain.toLowerCase().split(/[^\p{L}]+/u).filter(Boolean);
|
|
126
|
+
return words.some((word) => COURTESY_ANCHORS.has(word))
|
|
127
|
+
&& words.every((word) => COURTESY_ANCHORS.has(word) || COURTESY_MODIFIERS.has(word));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const isCourtesy = (message) => !message.media?.mediaType && !message.media?.key && !message.interactive_type
|
|
131
|
+
&& isCourtesyText(writtenText(message));
|
|
132
|
+
|
|
133
|
+
async function hasOnlyCourtesyUnanswered(code) {
|
|
134
|
+
try {
|
|
135
|
+
const unanswered = await getMessages(
|
|
136
|
+
{ numero: code, from_me: false, createdAt: { $gt: new Date(Date.now() - getOfferWindowMs()) } },
|
|
137
|
+
{ sort: { createdAt: -1 }, limit: UNANSWERED_LOOKBACK, select: { body: 1, plainBody: 1, media: 1, interactive_type: 1 } }
|
|
138
|
+
);
|
|
139
|
+
return unanswered.length > 0 && unanswered.length < UNANSWERED_LOOKBACK && unanswered.every(isCourtesy);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
logger.warn('[PausedSafetyNet] Could not read the unanswered messages; offering the net', { code, error: error.message });
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
112
146
|
async function offerSafetyNet({ code, reason = PAUSED }) {
|
|
113
147
|
try {
|
|
114
148
|
if (!code || !getSafetyNetContentSid() || !getSafetyNetPhone()) return { sent: false, reason: 'not_configured' };
|
|
@@ -117,6 +151,7 @@ async function offerSafetyNet({ code, reason = PAUSED }) {
|
|
|
117
151
|
if (await pausedSince(code, new Date(Date.now() - getPauseQuietMs()))) return { sent: false, reason: 'just_paused' };
|
|
118
152
|
if (await humanRepliedSince(code, new Date(Date.now() - getHumanQuietMs()))) return { sent: false, reason: 'human_active' };
|
|
119
153
|
if (await anyoneRepliedSince(code, new Date(Date.now() - getActivityQuietMs()))) return { sent: false, reason: 'conversation_active' };
|
|
154
|
+
if (await hasOnlyCourtesyUnanswered(code)) return { sent: false, reason: COURTESY_ONLY };
|
|
120
155
|
|
|
121
156
|
const contentSid = templateFor(reason);
|
|
122
157
|
await warnIfPhoneDiffersFromTemplate(contentSid);
|
|
@@ -154,7 +189,23 @@ async function unansweredText(code) {
|
|
|
154
189
|
{ numero: code, from_me: false, interactive_type: null },
|
|
155
190
|
{ sort: { createdAt: -1 }, limit: 1 }
|
|
156
191
|
);
|
|
157
|
-
return written ? written
|
|
192
|
+
return written ? writtenText(written) : null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function staffSenderSince(code, since) {
|
|
196
|
+
try {
|
|
197
|
+
const [sent] = await getMessages(staffSendFilter(code, since), { sort: { createdAt: -1 }, limit: 1 });
|
|
198
|
+
return isStaffSend(sent?.triggeredBy) ? sent.triggeredBy : null;
|
|
199
|
+
} catch (error) {
|
|
200
|
+
logger.warn('[PausedSafetyNet] Could not read who last wrote to the patient', { code, error: error.message });
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function opsAlertFor(code, reason) {
|
|
206
|
+
const alert = OPS_ALERTS[reason] || OPS_ALERTS.paused;
|
|
207
|
+
const staff = await staffSenderSince(code, new Date(Date.now() - getHumanQuietMs()));
|
|
208
|
+
return staff ? { ...alert, summary: `escribió después de un mensaje de ${staff}` } : alert;
|
|
158
209
|
}
|
|
159
210
|
|
|
160
211
|
const assistantNamedOn = (thread) => Boolean(thread?.getAssistantId?.() || thread?.assistant_id);
|
|
@@ -175,11 +226,12 @@ async function coverUnansweredPatient({ code, reason = PAUSED }) {
|
|
|
175
226
|
if (!claim.acquired) return;
|
|
176
227
|
|
|
177
228
|
const results = await Promise.allSettled([
|
|
178
|
-
unansweredText(code)
|
|
229
|
+
Promise.all([unansweredText(code), opsAlertFor(code, reason)])
|
|
230
|
+
.then(([text, alert]) => recordPausedThreadMessage({ code, text, alert })),
|
|
179
231
|
offerSafetyNet({ code, reason }),
|
|
180
232
|
]);
|
|
181
233
|
|
|
182
|
-
const covered = results.every((r) => r.status === 'fulfilled');
|
|
234
|
+
const covered = results.every((r) => r.status === 'fulfilled') && results[1].value?.reason !== COURTESY_ONLY;
|
|
183
235
|
if (covered) await completeSendClaim(claim.claimId);
|
|
184
236
|
else await releaseSendClaim(claim.claimId);
|
|
185
237
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const { getTriageRecommendationEventModel } = require('../models/triageRecommendationEventModel');
|
|
1
2
|
const { buildRetriggerPayload } = require('../helpers/triageRetriggerHelper');
|
|
2
3
|
const { Symptoms_ID } = require('../../config/airtableConfig');
|
|
3
4
|
const { logger } = require('../../utils/logger');
|
|
@@ -23,6 +24,23 @@ const RETRY_SETTLE_MS = 5 * 60 * 1000;
|
|
|
23
24
|
const retryClaims = new WriteClaimStore({ namespace: 'recom-orphan-retry', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
|
|
24
25
|
const ticketClaims = new WriteClaimStore({ namespace: 'recom-orphan-ticket', ttlMs: SCAN_WINDOW_MS, maxSize: 500 });
|
|
25
26
|
|
|
27
|
+
const FAILURE_REASONS = {
|
|
28
|
+
gate_inconsistent: 'el filtro de seguridad devolvió una urgencia inconsistente',
|
|
29
|
+
gate_malformed: 'el filtro de seguridad devolvió una respuesta inválida',
|
|
30
|
+
gate_incomplete: 'el filtro de seguridad no terminó su respuesta',
|
|
31
|
+
gate_provider_failed: 'el proveedor del modelo falló en el filtro de seguridad',
|
|
32
|
+
plan_provider_failed: 'el proveedor del modelo falló al armar las recomendaciones',
|
|
33
|
+
plan_incomplete: 'el plan de recomendaciones quedó incompleto',
|
|
34
|
+
plan_invalid: 'el plan de recomendaciones no pasó la validación',
|
|
35
|
+
plan_malformed: 'el plan de recomendaciones llegó malformado',
|
|
36
|
+
plan_empty: 'el plan no trajo recomendaciones',
|
|
37
|
+
plan_all_denied: 'ninguna recomendación correspondía a los síntomas reportados',
|
|
38
|
+
mirror_failed: 'no se pudo guardar la fila de recomendaciones en Airtable',
|
|
39
|
+
profile_read_failed: 'no se pudo leer el perfil clínico',
|
|
40
|
+
no_clinical_profile: 'la paciente no tiene perfil clínico',
|
|
41
|
+
error: 'el generador falló inesperadamente',
|
|
42
|
+
};
|
|
43
|
+
|
|
26
44
|
const FIELDS = ['Created', 'triaje_symptoms_id', 'whatsapp_id', 'symptom_name_positive'];
|
|
27
45
|
|
|
28
46
|
const botIsPaused = (code) => threadIsPaused(code, { label: '[recommendationRecovery]' });
|
|
@@ -55,13 +73,36 @@ function describe(row) {
|
|
|
55
73
|
};
|
|
56
74
|
}
|
|
57
75
|
|
|
76
|
+
async function lastSettle(triageRecordId) {
|
|
77
|
+
try {
|
|
78
|
+
return await getTriageRecommendationEventModel()
|
|
79
|
+
.findOne({ triageRecordId }).sort({ createdAt: -1 }).select('status stage reason hardRejectIssues')
|
|
80
|
+
.maxTimeMS(2000)
|
|
81
|
+
.lean();
|
|
82
|
+
} catch (error) {
|
|
83
|
+
logger.warn('[recommendationRecovery] could not read the last settle event', { triageRecordId, error: error.message });
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function failureReason(settle) {
|
|
89
|
+
if (settle === undefined) return { label: 'motivo no disponible', code: 'settle_unreadable' };
|
|
90
|
+
if (!settle) return { label: 'no hay registro de ejecución del generador', code: 'no_settle_event' };
|
|
91
|
+
const code = [settle.status, settle.stage, settle.reason].filter(Boolean).join('/');
|
|
92
|
+
return { label: FAILURE_REASONS[settle.reason] || `el generador terminó con ${code}`, code, issues: settle.hardRejectIssues || [] };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const issueText = (issue) => (typeof issue === 'string' ? issue : `${issue?.path}: ${issue?.problem}`);
|
|
96
|
+
|
|
58
97
|
async function fileOpsTicket(orphan) {
|
|
59
98
|
if (!orphan.code) return false;
|
|
99
|
+
const reason = failureReason(await lastSettle(orphan.triageRecordId));
|
|
100
|
+
const issues = reason.issues?.length ? ` Problemas: ${reason.issues.map(issueText).join('; ').slice(0, 500)}.` : '';
|
|
60
101
|
return recordUnresolvedRequest({
|
|
61
102
|
code: orphan.code,
|
|
62
103
|
trace: null,
|
|
63
|
-
question:
|
|
64
|
-
details: `Triaje ${orphan.triageId ?? orphan.triageRecordId} (${orphan.createdAt}) con ${orphan.positiveSymptoms} síntomas positivos no tiene recomendaciones. Revisar si procede reenviarlas.`,
|
|
104
|
+
question: `El triaje de la paciente no generó recomendaciones: ${reason.label}.`,
|
|
105
|
+
details: `Triaje ${orphan.triageId ?? orphan.triageRecordId} (${orphan.createdAt}) con ${orphan.positiveSymptoms} síntomas positivos no tiene recomendaciones. Motivo: ${reason.code}.${issues} Revisar si procede reenviarlas.`,
|
|
65
106
|
category: 'contact_team_member',
|
|
66
107
|
urgency: 'soon',
|
|
67
108
|
});
|
|
@@ -186,6 +227,7 @@ module.exports = {
|
|
|
186
227
|
DEFAULT_SWEEP_INTERVAL_MS,
|
|
187
228
|
sweepUnrecoveredTriages,
|
|
188
229
|
orphanFormula,
|
|
230
|
+
_fileOpsTicket: fileOpsTicket,
|
|
189
231
|
_handledClaims: retryClaims,
|
|
190
232
|
_ticketClaims: ticketClaims,
|
|
191
233
|
CLAIM_TTL_MS,
|
|
@@ -749,10 +749,19 @@ async function pendingMirrorPayload(runId) {
|
|
|
749
749
|
...(excludeRecordId ? { excludeRecordId } : {}), ...(excludeRecordIds ? { excludeRecordIds } : {}) };
|
|
750
750
|
}
|
|
751
751
|
|
|
752
|
-
function gateCorrectionNote(issues) {
|
|
752
|
+
function gateCorrectionNote(issues, repairs = []) {
|
|
753
|
+
const statusRepairs = repairs.filter((repair) => repair.includes('(aritmética de eventos)'));
|
|
753
754
|
return [
|
|
754
755
|
'Tu respuesta anterior fue rechazada por incoherencia del gate:',
|
|
755
756
|
...issues.map((issue) => `- ${issue}`),
|
|
757
|
+
...(statusRepairs.length ? [
|
|
758
|
+
'El servidor recalculó el estado de tus red flags a partir de sus eventos:',
|
|
759
|
+
...statusRepairs.map((repair) => `- ${repair}`),
|
|
760
|
+
'Un red flag solo es confirmed o partially_confirmed si events_confirmed copia textualmente al menos un '
|
|
761
|
+
+ 'clinical_event de su definition que el paciente sí reportó; con events_confirmed vacío queda inconclusive '
|
|
762
|
+
+ '(o denied si hay events_denied). Si el paciente reportó un evento que forma parte del red flag, inclúyelo '
|
|
763
|
+
+ 'en definition y cópialo igual en events_confirmed.',
|
|
764
|
+
] : []),
|
|
756
765
|
'Corrige y vuelve a emitir el gate completo. Si no puedes sostener urgent_under_24h=true '
|
|
757
766
|
+ 'con al menos un red flag confirmed o partially_confirmed, emítelo como false.',
|
|
758
767
|
].join('\n');
|
|
@@ -777,7 +786,7 @@ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, pa
|
|
|
777
786
|
attempts = attempt;
|
|
778
787
|
const last = attempt === GATE_MAX_ATTEMPTS;
|
|
779
788
|
const input = [{ role: 'user', content: casoBase }];
|
|
780
|
-
if (priorIssues) input.push({ role: 'user', content: gateCorrectionNote(priorIssues) });
|
|
789
|
+
if (priorIssues) input.push({ role: 'user', content: gateCorrectionNote(priorIssues, gateRepairs) });
|
|
781
790
|
let result;
|
|
782
791
|
try {
|
|
783
792
|
result = await callProviderWithBackoff(() => provider.runStructured({
|